YamlExtension.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\Bridge\Twig\Extension;
  11. use Symfony\Component\Yaml\Dumper as YamlDumper;
  12. use Twig\Extension\AbstractExtension;
  13. use Twig\TwigFilter;
  14. /**
  15. * Provides integration of the Yaml component with Twig.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. final class YamlExtension extends AbstractExtension
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function getFilters(): array
  25. {
  26. return [
  27. new TwigFilter('yaml_encode', [$this, 'encode']),
  28. new TwigFilter('yaml_dump', [$this, 'dump']),
  29. ];
  30. }
  31. public function encode($input, int $inline = 0, int $dumpObjects = 0): string
  32. {
  33. static $dumper;
  34. if (null === $dumper) {
  35. $dumper = new YamlDumper();
  36. }
  37. if (\defined('Symfony\Component\Yaml\Yaml::DUMP_OBJECT')) {
  38. return $dumper->dump($input, $inline, 0, $dumpObjects);
  39. }
  40. return $dumper->dump($input, $inline, 0, false, $dumpObjects);
  41. }
  42. public function dump($value, int $inline = 0, int $dumpObjects = 0): string
  43. {
  44. if (\is_resource($value)) {
  45. return '%Resource%';
  46. }
  47. if (\is_array($value) || \is_object($value)) {
  48. return '%'.\gettype($value).'% '.$this->encode($value, $inline, $dumpObjects);
  49. }
  50. return $this->encode($value, $inline, $dumpObjects);
  51. }
  52. }