Yaml.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Drupal\Component\Serialization;
  3. /**
  4. * Provides a YAML serialization implementation.
  5. *
  6. * Proxy implementation that will choose the best library based on availability.
  7. */
  8. class Yaml implements SerializationInterface {
  9. /**
  10. * The YAML implementation to use.
  11. *
  12. * @var \Drupal\Component\Serialization\SerializationInterface
  13. */
  14. protected static $serializer;
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public static function encode($data) {
  19. // Instead of using \Drupal\Component\Serialization\Yaml::getSerializer(),
  20. // always using Symfony for writing the data, to reduce the risk of having
  21. // differences if different environments (like production and development)
  22. // do not match in terms of what YAML implementation is available.
  23. return YamlSymfony::encode($data);
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public static function decode($raw) {
  29. $serializer = static::getSerializer();
  30. return $serializer::decode($raw);
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public static function getFileExtension() {
  36. return 'yml';
  37. }
  38. /**
  39. * Determines which implementation to use for parsing YAML.
  40. */
  41. protected static function getSerializer() {
  42. if (!isset(static::$serializer)) {
  43. // Use the PECL YAML extension if it is available. It has better
  44. // performance for file reads and is YAML compliant.
  45. if (extension_loaded('yaml')) {
  46. static::$serializer = YamlPecl::class;
  47. }
  48. else {
  49. // Otherwise, fallback to the Symfony implementation.
  50. static::$serializer = YamlSymfony::class;
  51. }
  52. }
  53. return static::$serializer;
  54. }
  55. }