DumpNode.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\Node;
  11. use Twig\Compiler;
  12. use Twig\Node\Node;
  13. /**
  14. * @author Julien Galenski <julien.galenski@gmail.com>
  15. */
  16. final class DumpNode extends Node
  17. {
  18. private $varPrefix;
  19. public function __construct($varPrefix, ?Node $values, int $lineno, string $tag = null)
  20. {
  21. $nodes = [];
  22. if (null !== $values) {
  23. $nodes['values'] = $values;
  24. }
  25. parent::__construct($nodes, [], $lineno, $tag);
  26. $this->varPrefix = $varPrefix;
  27. }
  28. public function compile(Compiler $compiler): void
  29. {
  30. $compiler
  31. ->write("if (\$this->env->isDebug()) {\n")
  32. ->indent();
  33. if (!$this->hasNode('values')) {
  34. // remove embedded templates (macros) from the context
  35. $compiler
  36. ->write(sprintf('$%svars = [];'."\n", $this->varPrefix))
  37. ->write(sprintf('foreach ($context as $%1$skey => $%1$sval) {'."\n", $this->varPrefix))
  38. ->indent()
  39. ->write(sprintf('if (!$%sval instanceof \Twig\Template) {'."\n", $this->varPrefix))
  40. ->indent()
  41. ->write(sprintf('$%1$svars[$%1$skey] = $%1$sval;'."\n", $this->varPrefix))
  42. ->outdent()
  43. ->write("}\n")
  44. ->outdent()
  45. ->write("}\n")
  46. ->addDebugInfo($this)
  47. ->write(sprintf('\Symfony\Component\VarDumper\VarDumper::dump($%svars);'."\n", $this->varPrefix));
  48. } elseif (($values = $this->getNode('values')) && 1 === $values->count()) {
  49. $compiler
  50. ->addDebugInfo($this)
  51. ->write('\Symfony\Component\VarDumper\VarDumper::dump(')
  52. ->subcompile($values->getNode(0))
  53. ->raw(");\n");
  54. } else {
  55. $compiler
  56. ->addDebugInfo($this)
  57. ->write('\Symfony\Component\VarDumper\VarDumper::dump(['."\n")
  58. ->indent();
  59. foreach ($values as $node) {
  60. $compiler->write('');
  61. if ($node->hasAttribute('name')) {
  62. $compiler
  63. ->string($node->getAttribute('name'))
  64. ->raw(' => ');
  65. }
  66. $compiler
  67. ->subcompile($node)
  68. ->raw(",\n");
  69. }
  70. $compiler
  71. ->outdent()
  72. ->write("]);\n");
  73. }
  74. $compiler
  75. ->outdent()
  76. ->write("}\n");
  77. }
  78. }