diff --git a/src/Node/SetNode.php b/src/Node/SetNode.php index 67725104ece..288911a5c22 100644 --- a/src/Node/SetNode.php +++ b/src/Node/SetNode.php @@ -33,9 +33,15 @@ public function __construct(bool $capture, Node $names, Node $values, int $linen $safe = false; if ($capture) { $safe = true; - if ($values instanceof TextNode) { + if (Node::class === get_class($values) && !count($values)) { + $values = new ConstantExpression('', $values->getTemplateLine()); + $capture = false; + } elseif ($values instanceof TextNode) { $values = new ConstantExpression($values->getAttribute('data'), $values->getTemplateLine()); $capture = false; + } elseif ($values instanceof PrintNode && $values->getNode('expr') instanceof ConstantExpression) { + $values = $values->getNode('expr'); + $capture = false; } else { $values = new CaptureNode($values, $values->getTemplateLine()); } @@ -78,11 +84,23 @@ public function compile(Compiler $compiler): void $compiler->raw(']'); } else { if ($this->getAttribute('safe')) { - $compiler - ->raw("('' === \$tmp = ") - ->subcompile($this->getNode('values')) - ->raw(") ? '' : new Markup(\$tmp, \$this->env->getCharset())") - ; + if ($this->getNode('values') instanceof ConstantExpression) { + if ('' === $this->getNode('values')->getAttribute('value')) { + $compiler->raw('""'); + } else { + $compiler + ->raw('new Markup(') + ->subcompile($this->getNode('values')) + ->raw(', $this->env->getCharset())') + ; + } + } else { + $compiler + ->raw("('' === \$tmp = ") + ->subcompile($this->getNode('values')) + ->raw(") ? '' : new Markup(\$tmp, \$this->env->getCharset())") + ; + } } else { $compiler->subcompile($this->getNode('values')); } diff --git a/tests/Node/SetTest.php b/tests/Node/SetTest.php index dd2dca2bc0d..06f0407dd2b 100644 --- a/tests/Node/SetTest.php +++ b/tests/Node/SetTest.php @@ -77,7 +77,25 @@ public static function provideTests(): iterable $node = new SetNode(true, $names, $values, 1); $tests[] = [$node, <<env->getCharset()); +\$context["foo"] = new Markup("foo", \$this->env->getCharset()); +EOF + ]; + + $names = new Node([new AssignNameExpression('foo', 1)], [], 1); + $values = new TextNode('', 1); + $node = new SetNode(true, $names, $values, 1); + $tests[] = [$node, <<env->getCharset()); EOF ];