DumpExtension.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. final 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;
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function getFunctions(): array
  36. {
  37. return [
  38. new TwigFunction('dump', [$this, 'dump'], ['is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true]),
  39. ];
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function getTokenParsers(): array
  45. {
  46. return [new DumpTokenParser()];
  47. }
  48. public function dump(Environment $env, array $context): ?string
  49. {
  50. if (!$env->isDebug()) {
  51. return null;
  52. }
  53. if (2 === \func_num_args()) {
  54. $vars = [];
  55. foreach ($context as $key => $value) {
  56. if (!$value instanceof Template) {
  57. $vars[$key] = $value;
  58. }
  59. }
  60. $vars = [$vars];
  61. } else {
  62. $vars = \func_get_args();
  63. unset($vars[0], $vars[1]);
  64. }
  65. $dump = fopen('php://memory', 'r+');
  66. $this->dumper = $this->dumper ?: new HtmlDumper();
  67. $this->dumper->setCharset($env->getCharset());
  68. foreach ($vars as $value) {
  69. $this->dumper->dump($this->cloner->cloneVar($value), $dump);
  70. }
  71. return stream_get_contents($dump, -1, 0);
  72. }
  73. }