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 $variablesbool $onlyint $linenostring $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): void
  28.     {
  29.         $compiler->addDebugInfo($this);
  30.         $parentContextName $compiler->getVarName();
  31.         $compiler->write(sprintf("\$%s = \$context;\n"$parentContextName));
  32.         if ($this->hasNode('variables')) {
  33.             $node $this->getNode('variables');
  34.             $varsName $compiler->getVarName();
  35.             $compiler
  36.                 ->write(sprintf('$%s = '$varsName))
  37.                 ->subcompile($node)
  38.                 ->raw(";\n")
  39.                 ->write(sprintf("if (!twig_test_iterable(\$%s)) {\n"$varsName))
  40.                 ->indent()
  41.                 ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.', ")
  42.                 ->repr($node->getTemplateLine())
  43.                 ->raw(", \$this->getSourceContext());\n")
  44.                 ->outdent()
  45.                 ->write("}\n")
  46.                 ->write(sprintf("\$%s = twig_to_array(\$%s);\n"$varsName$varsName))
  47.             ;
  48.             if ($this->getAttribute('only')) {
  49.                 $compiler->write("\$context = [];\n");
  50.             }
  51.             $compiler->write(sprintf("\$context = \$this->env->mergeGlobals(array_merge(\$context, \$%s));\n"$varsName));
  52.         }
  53.         $compiler
  54.             ->subcompile($this->getNode('body'))
  55.             ->write(sprintf("\$context = \$%s;\n"$parentContextName))
  56.         ;
  57.     }
  58. }