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 = null, $only = false, $lineno, $tag = null) 24 { 25 $nodes = ['body' => $body]; 26 if (null !== $variables) { 27 $nodes['variables'] = $variables; 28 } 29 30 parent::__construct($nodes, ['only' => (bool) $only], $lineno, $tag); 31 } 32 33 public function compile(Compiler $compiler) 34 { 35 $compiler->addDebugInfo($this); 36 37 if ($this->hasNode('variables')) { 38 $varsName = $compiler->getVarName(); 39 $compiler 40 ->write(sprintf('$%s = ', $varsName)) 41 ->subcompile($this->getNode('variables')) 42 ->raw(";\n") 43 ->write(sprintf("if (\$%s instanceof \\Traversable) {\n", $varsName)) 44 ->indent() 45 ->write(sprintf("\$%s = iterator_to_array(\$%s);\n", $varsName, $varsName)) 46 ->outdent() 47 ->write("}\n") 48 ->write(sprintf("if (!is_array(\$%s)) {\n", $varsName)) 49 ->indent() 50 ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.');\n") 51 ->outdent() 52 ->write("}\n") 53 ; 54 55 if ($this->getAttribute('only')) { 56 $compiler->write("\$context = ['_parent' => \$context];\n"); 57 } else { 58 $compiler->write("\$context['_parent'] = \$context;\n"); 59 } 60 61 $compiler->write(sprintf("\$context = array_merge(\$context, \$%s);\n", $varsName)); 62 } else { 63 $compiler->write("\$context['_parent'] = \$context;\n"); 64 } 65 66 $compiler 67 ->subcompile($this->getNode('body')) 68 ->write("\$context = \$context['_parent'];\n") 69 ; 70 } 71} 72 73class_alias('Twig\Node\WithNode', 'Twig_Node_With'); 74