DumpExtension.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\Bridge\Twig\TokenParser\DumpTokenParser;
  12. use Symfony\Component\VarDumper\Cloner\ClonerInterface;
  13. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  14. use Twig\Environment;
  15. use Twig\Extension\AbstractExtension;
  16. use Twig\Template;
  17. use Twig\TwigFunction;
  18. /**
  19. * Provides integration of the dump() function with Twig.
  20. *
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. */
  23. class DumpExtension extends AbstractExtension
  24. {
  25. private $cloner;
  26. private $dumper;
  27. public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null)
  28. {
  29. $this->cloner = $cloner;
  30. $this->dumper = $dumper ?: new HtmlDumper();
  31. }
  32. public function getFunctions()
  33. {
  34. return array(
  35. new TwigFunction('dump', array($this, 'dump'), array('is_safe' => array('html'), 'needs_context' => true, 'needs_environment' => true)),
  36. );
  37. }
  38. public function getTokenParsers()
  39. {
  40. return array(new DumpTokenParser());
  41. }
  42. public function getName()
  43. {
  44. return 'dump';
  45. }
  46. public function dump(Environment $env, $context)
  47. {
  48. if (!$env->isDebug()) {
  49. return;
  50. }
  51. if (2 === func_num_args()) {
  52. $vars = array();
  53. foreach ($context as $key => $value) {
  54. if (!$value instanceof Template) {
  55. $vars[$key] = $value;
  56. }
  57. }
  58. $vars = array($vars);
  59. } else {
  60. $vars = func_get_args();
  61. unset($vars[0], $vars[1]);
  62. }
  63. $dump = fopen('php://memory', 'r+b');
  64. $this->dumper->setCharset($env->getCharset());
  65. foreach ($vars as $value) {
  66. $this->dumper->dump($this->cloner->cloneVar($value), $dump);
  67. }
  68. return stream_get_contents($dump, -1, 0);
  69. }
  70. }