YamlSymfony.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Drupal\Component\Serialization;
  3. use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
  4. use Symfony\Component\Yaml\Parser;
  5. use Symfony\Component\Yaml\Dumper;
  6. use Symfony\Component\Yaml\Yaml as SymfonyYaml;
  7. /**
  8. * Default serialization for YAML using the Symfony component.
  9. */
  10. class YamlSymfony implements SerializationInterface {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public static function encode($data) {
  15. try {
  16. // Set the indentation to 2 to match Drupal's coding standards.
  17. $yaml = new Dumper(2);
  18. return $yaml->dump($data, PHP_INT_MAX, 0, SymfonyYaml::DUMP_EXCEPTION_ON_INVALID_TYPE);
  19. }
  20. catch (\Exception $e) {
  21. throw new InvalidDataTypeException($e->getMessage(), $e->getCode(), $e);
  22. }
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public static function decode($raw) {
  28. try {
  29. $yaml = new Parser();
  30. // Make sure we have a single trailing newline. A very simple config like
  31. // 'foo: bar' with no newline will fail to parse otherwise.
  32. return $yaml->parse($raw, SymfonyYaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
  33. }
  34. catch (\Exception $e) {
  35. throw new InvalidDataTypeException($e->getMessage(), $e->getCode(), $e);
  36. }
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public static function getFileExtension() {
  42. return 'yml';
  43. }
  44. }