YamlEncoder.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Encoder;
  11. use Symfony\Component\Serializer\Exception\RuntimeException;
  12. use Symfony\Component\Yaml\Dumper;
  13. use Symfony\Component\Yaml\Parser;
  14. use Symfony\Component\Yaml\Yaml;
  15. /**
  16. * Encodes YAML data.
  17. *
  18. * @author Kévin Dunglas <dunglas@gmail.com>
  19. */
  20. class YamlEncoder implements EncoderInterface, DecoderInterface
  21. {
  22. public const FORMAT = 'yaml';
  23. private const ALTERNATIVE_FORMAT = 'yml';
  24. public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';
  25. public const YAML_INLINE = 'yaml_inline';
  26. public const YAML_INDENT = 'yaml_indent';
  27. public const YAML_FLAGS = 'yaml_flags';
  28. private $dumper;
  29. private $parser;
  30. private $defaultContext = [
  31. self::YAML_INLINE => 0,
  32. self::YAML_INDENT => 0,
  33. self::YAML_FLAGS => 0,
  34. ];
  35. public function __construct(Dumper $dumper = null, Parser $parser = null, array $defaultContext = [])
  36. {
  37. if (!class_exists(Dumper::class)) {
  38. throw new RuntimeException('The YamlEncoder class requires the "Yaml" component. Install "symfony/yaml" to use it.');
  39. }
  40. $this->dumper = $dumper ?: new Dumper();
  41. $this->parser = $parser ?: new Parser();
  42. $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function encode($data, string $format, array $context = [])
  48. {
  49. $context = array_merge($this->defaultContext, $context);
  50. if (isset($context[self::PRESERVE_EMPTY_OBJECTS])) {
  51. $context[self::YAML_FLAGS] |= Yaml::DUMP_OBJECT_AS_MAP;
  52. }
  53. return $this->dumper->dump($data, $context[self::YAML_INLINE], $context[self::YAML_INDENT], $context[self::YAML_FLAGS]);
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function supportsEncoding(string $format)
  59. {
  60. return self::FORMAT === $format || self::ALTERNATIVE_FORMAT === $format;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function decode(string $data, string $format, array $context = [])
  66. {
  67. $context = array_merge($this->defaultContext, $context);
  68. return $this->parser->parse($data, $context[self::YAML_FLAGS]);
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function supportsDecoding(string $format)
  74. {
  75. return self::FORMAT === $format || self::ALTERNATIVE_FORMAT === $format;
  76. }
  77. }