Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 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 | |
| 12 | namespace Twig\Node; |
| 13 | |
| 14 | use Twig\Compiler; |
| 15 | |
| 16 | /** |
| 17 | * Represents a nested "with" scope. |
| 18 | * |
| 19 | * @author Fabien Potencier <fabien@symfony.com> |
| 20 | */ |
| 21 | class 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): void |
| 34 | { |
| 35 | $compiler->addDebugInfo($this); |
| 36 | |
| 37 | $parentContextName = $compiler->getVarName(); |
| 38 | |
| 39 | $compiler->write(sprintf("\$%s = \$context;\n", $parentContextName)); |
| 40 | |
| 41 | if ($this->hasNode('variables')) { |
| 42 | $node = $this->getNode('variables'); |
| 43 | $varsName = $compiler->getVarName(); |
| 44 | $compiler |
| 45 | ->write(sprintf('$%s = ', $varsName)) |
| 46 | ->subcompile($node) |
| 47 | ->raw(";\n") |
| 48 | ->write(sprintf("if (!twig_test_iterable(\$%s)) {\n", $varsName)) |
| 49 | ->indent() |
| 50 | ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.', ") |
| 51 | ->repr($node->getTemplateLine()) |
| 52 | ->raw(", \$this->getSourceContext());\n") |
| 53 | ->outdent() |
| 54 | ->write("}\n") |
| 55 | ->write(sprintf("\$%s = twig_to_array(\$%s);\n", $varsName, $varsName)) |
| 56 | ; |
| 57 | |
| 58 | if ($this->getAttribute('only')) { |
| 59 | $compiler->write("\$context = [];\n"); |
| 60 | } |
| 61 | |
| 62 | $compiler->write(sprintf("\$context = \$this->env->mergeGlobals(array_merge(\$context, \$%s));\n", $varsName)); |
| 63 | } |
| 64 | |
| 65 | $compiler |
| 66 | ->subcompile($this->getNode('body')) |
| 67 | ->write(sprintf("\$context = \$%s;\n", $parentContextName)) |
| 68 | ; |
| 69 | } |
| 70 | } |