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; 15use Twig\Node\Expression\ConstantExpression; 16 17/** 18 * Represents a set node. 19 * 20 * @author Fabien Potencier <fabien@symfony.com> 21 */ 22class SetNode extends Node implements NodeCaptureInterface 23{ 24 public function __construct(bool $capture, Node $names, Node $values, int $lineno, string $tag = null) 25 { 26 parent::__construct(['names' => $names, 'values' => $values], ['capture' => $capture, 'safe' => false], $lineno, $tag); 27 28 /* 29 * Optimizes the node when capture is used for a large block of text. 30 * 31 * {% set foo %}foo{% endset %} is compiled to $context['foo'] = new Twig\Markup("foo"); 32 */ 33 if ($this->getAttribute('capture')) { 34 $this->setAttribute('safe', true); 35 36 $values = $this->getNode('values'); 37 if ($values instanceof TextNode) { 38 $this->setNode('values', new ConstantExpression($values->getAttribute('data'), $values->getTemplateLine())); 39 $this->setAttribute('capture', false); 40 } 41 } 42 } 43 44 public function compile(Compiler $compiler) 45 { 46 $compiler->addDebugInfo($this); 47 48 if (\count($this->getNode('names')) > 1) { 49 $compiler->write('list('); 50 foreach ($this->getNode('names') as $idx => $node) { 51 if ($idx) { 52 $compiler->raw(', '); 53 } 54 55 $compiler->subcompile($node); 56 } 57 $compiler->raw(')'); 58 } else { 59 if ($this->getAttribute('capture')) { 60 if ($compiler->getEnvironment()->isDebug()) { 61 $compiler->write("ob_start();\n"); 62 } else { 63 $compiler->write("ob_start(function () { return ''; });\n"); 64 } 65 $compiler 66 ->subcompile($this->getNode('values')) 67 ; 68 } 69 70 $compiler->subcompile($this->getNode('names'), false); 71 72 if ($this->getAttribute('capture')) { 73 $compiler->raw(" = ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset())"); 74 } 75 } 76 77 if (!$this->getAttribute('capture')) { 78 $compiler->raw(' = '); 79 80 if (\count($this->getNode('names')) > 1) { 81 $compiler->write('['); 82 foreach ($this->getNode('values') as $idx => $value) { 83 if ($idx) { 84 $compiler->raw(', '); 85 } 86 87 $compiler->subcompile($value); 88 } 89 $compiler->raw(']'); 90 } else { 91 if ($this->getAttribute('safe')) { 92 $compiler 93 ->raw("('' === \$tmp = ") 94 ->subcompile($this->getNode('values')) 95 ->raw(") ? '' : new Markup(\$tmp, \$this->env->getCharset())") 96 ; 97 } else { 98 $compiler->subcompile($this->getNode('values')); 99 } 100 } 101 } 102 103 $compiler->raw(";\n"); 104 } 105} 106 107class_alias('Twig\Node\SetNode', 'Twig_Node_Set'); 108