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