diff --git a/src/Node/Expression/ArrayExpression.php b/src/Node/Expression/ArrayExpression.php index 9b6c55c29..6c6efee13 100644 --- a/src/Node/Expression/ArrayExpression.php +++ b/src/Node/Expression/ArrayExpression.php @@ -12,6 +12,7 @@ namespace Twig\Node\Expression; use Twig\Compiler; +use Twig\Node\Expression\Unary\StringCastUnary; class ArrayExpression extends AbstractExpression { @@ -99,7 +100,7 @@ class ArrayExpression extends AbstractExpression } else { $key = $pair['key'] instanceof ConstantExpression ? $pair['key']->getAttribute('value') : null; if ($pair['key'] instanceof NameExpression) { - $pair['key']->setAttribute('stringify', true); + $pair['key'] = new StringCastUnary($pair['key'], $pair['key']->getTemplateLine()); } if ($nextIndex !== $key) { diff --git a/src/Node/Expression/NameExpression.php b/src/Node/Expression/NameExpression.php index a3f42cd0c..12a9bb71c 100644 --- a/src/Node/Expression/NameExpression.php +++ b/src/Node/Expression/NameExpression.php @@ -24,7 +24,7 @@ class NameExpression extends AbstractExpression public function __construct(string $name, int $lineno) { - parent::__construct([], ['name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false, 'stringify' => false], $lineno); + parent::__construct([], ['name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false], $lineno); } public function compile(Compiler $compiler): void @@ -54,9 +54,6 @@ class NameExpression extends AbstractExpression } elseif (isset($this->specialVars[$name])) { $compiler->raw($this->specialVars[$name]); } elseif ($this->getAttribute('always_defined')) { - if ($this->getAttribute('stringify')) { - $compiler->raw(' (string)'); - } $compiler ->raw('$context[') ->string($name) @@ -64,9 +61,6 @@ class NameExpression extends AbstractExpression ; } else { if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) { - if ($this->getAttribute('stringify')) { - $compiler->raw(' (string)'); - } $compiler ->raw('($context[') ->string($name) @@ -80,9 +74,6 @@ class NameExpression extends AbstractExpression ->string($name) ->raw(', $context) ?') ; - if ($this->getAttribute('stringify')) { - $compiler->raw(' (string)'); - } $compiler ->raw(' $context[') ->string($name) diff --git a/src/Node/Expression/Unary/StringCastUnary.php b/src/Node/Expression/Unary/StringCastUnary.php new file mode 100644 index 000000000..87ea17ca8 --- /dev/null +++ b/src/Node/Expression/Unary/StringCastUnary.php @@ -0,0 +1,22 @@ +raw('(string)'); + } +}