vendor/twig/twig/src/Node/WithNode.php line 23

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) Fabien Potencier
  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 Twig\Node;
  11. use Twig\Compiler;
  12. /**
  13. * Represents a nested "with" scope.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class WithNode extends Node
  18. {
  19. public function __construct(Node $body, ?Node $variables, bool $only, int $lineno, string $tag = null)
  20. {
  21. $nodes = ['body' => $body];
  22. if (null !== $variables) {
  23. $nodes['variables'] = $variables;
  24. }
  25. parent::__construct($nodes, ['only' => $only], $lineno, $tag);
  26. }
  27. public function compile(Compiler $compiler)
  28. {
  29. $compiler->addDebugInfo($this);
  30. if ($this->hasNode('variables')) {
  31. $node = $this->getNode('variables');
  32. $varsName = $compiler->getVarName();
  33. $compiler
  34. ->write(sprintf('$%s = ', $varsName))
  35. ->subcompile($node)
  36. ->raw(";\n")
  37. ->write(sprintf("if (!twig_test_iterable(\$%s)) {\n", $varsName))
  38. ->indent()
  39. ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.', ")
  40. ->repr($node->getTemplateLine())
  41. ->raw(", \$this->getSourceContext());\n")
  42. ->outdent()
  43. ->write("}\n")
  44. ->write(sprintf("\$%s = twig_to_array(\$%s);\n", $varsName, $varsName))
  45. ;
  46. if ($this->getAttribute('only')) {
  47. $compiler->write("\$context = ['_parent' => \$context];\n");
  48. } else {
  49. $compiler->write("\$context['_parent'] = \$context;\n");
  50. }
  51. $compiler->write(sprintf("\$context = \$this->env->mergeGlobals(array_merge(\$context, \$%s));\n", $varsName));
  52. } else {
  53. $compiler->write("\$context['_parent'] = \$context;\n");
  54. }
  55. $compiler
  56. ->subcompile($this->getNode('body'))
  57. ->write("\$context = \$context['_parent'];\n")
  58. ;
  59. }
  60. }
  61. class_alias('Twig\Node\WithNode', 'Twig_Node_With');