Yaml.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Config\Writer;
  10. use Zend\Config\Exception;
  11. class Yaml extends AbstractWriter
  12. {
  13. /**
  14. * YAML encoder callback
  15. *
  16. * @var callable
  17. */
  18. protected $yamlEncoder;
  19. /**
  20. * Constructor
  21. *
  22. * @param callable|string|null $yamlEncoder
  23. */
  24. public function __construct($yamlEncoder = null)
  25. {
  26. if ($yamlEncoder !== null) {
  27. $this->setYamlEncoder($yamlEncoder);
  28. } else {
  29. if (function_exists('yaml_emit')) {
  30. $this->setYamlEncoder('yaml_emit');
  31. }
  32. }
  33. }
  34. /**
  35. * Get callback for decoding YAML
  36. *
  37. * @return callable
  38. */
  39. public function getYamlEncoder()
  40. {
  41. return $this->yamlEncoder;
  42. }
  43. /**
  44. * Set callback for decoding YAML
  45. *
  46. * @param callable $yamlEncoder the decoder to set
  47. * @return Yaml
  48. * @throws Exception\InvalidArgumentException
  49. */
  50. public function setYamlEncoder($yamlEncoder)
  51. {
  52. if (!is_callable($yamlEncoder)) {
  53. throw new Exception\InvalidArgumentException('Invalid parameter to setYamlEncoder() - must be callable');
  54. }
  55. $this->yamlEncoder = $yamlEncoder;
  56. return $this;
  57. }
  58. /**
  59. * processConfig(): defined by AbstractWriter.
  60. *
  61. * @param array $config
  62. * @return string
  63. * @throws Exception\RuntimeException
  64. */
  65. public function processConfig(array $config)
  66. {
  67. if (null === $this->getYamlEncoder()) {
  68. throw new Exception\RuntimeException("You didn't specify a Yaml callback encoder");
  69. }
  70. $config = call_user_func($this->getYamlEncoder(), $config);
  71. if (null === $config) {
  72. throw new Exception\RuntimeException("Error generating YAML data");
  73. }
  74. return $config;
  75. }
  76. }