Add StringCastUnary

This commit is contained in:
Fabien Potencier
2024-09-11 16:28:41 +02:00
parent b2e66717a2
commit bfafa5b613
3 changed files with 25 additions and 11 deletions
+2 -1
View File
@@ -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) {
+1 -10
View File
@@ -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)
@@ -0,0 +1,22 @@
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
final class StringCastUnary extends AbstractUnary
{
public function operator(Compiler $compiler): Compiler
{
return $compiler->raw('(string)');
}
}