YamlExtension.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 Symfony\Component\Yaml\Yaml;
  13. use Twig\Extension\AbstractExtension;
  14. use Twig\TwigFilter;
  15. /**
  16. * Provides integration of the Yaml component with Twig.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class YamlExtension extends AbstractExtension
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function getFilters()
  26. {
  27. return array(
  28. new TwigFilter('yaml_encode', array($this, 'encode')),
  29. new TwigFilter('yaml_dump', array($this, 'dump')),
  30. );
  31. }
  32. public function encode($input, $inline = 0, $dumpObjects = 0)
  33. {
  34. static $dumper;
  35. if (null === $dumper) {
  36. $dumper = new YamlDumper();
  37. }
  38. if (defined('Symfony\Component\Yaml\Yaml::DUMP_OBJECT')) {
  39. if (is_bool($dumpObjects)) {
  40. @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
  41. $flags = $dumpObjects ? Yaml::DUMP_OBJECT : 0;
  42. } else {
  43. $flags = $dumpObjects;
  44. }
  45. return $dumper->dump($input, $inline, 0, $flags);
  46. }
  47. return $dumper->dump($input, $inline, 0, false, $dumpObjects);
  48. }
  49. public function dump($value, $inline = 0, $dumpObjects = false)
  50. {
  51. if (is_resource($value)) {
  52. return '%Resource%';
  53. }
  54. if (is_array($value) || is_object($value)) {
  55. return '%'.gettype($value).'% '.$this->encode($value, $inline, $dumpObjects);
  56. }
  57. return $this->encode($value, $inline, $dumpObjects);
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function getName()
  63. {
  64. return 'yaml';
  65. }
  66. }