Fix wrong array index (again)

This commit is contained in:
Fabien Potencier
2025-03-21 09:39:08 +01:00
parent 77a6da9cc7
commit 09f9a22310
3 changed files with 16 additions and 11 deletions
+1
View File
@@ -1,5 +1,6 @@
# 3.21.0 (2025-XX-XX)
* Fix wrong array index
* Deprecate `Template::loadTemplate()`
* Fix testing and expression when it evaluates to an instance of `Markup`
* Add `ReturnPrimitiveTypeInterface` (and sub-interfaces for number, boolean, string, and array)
+10 -11
View File
@@ -78,33 +78,32 @@ class ArrayExpression extends AbstractExpression implements SupportDefinedTestIn
}
$compiler->raw('[');
$first = true;
$nextIndex = 0;
foreach ($this->getKeyValuePairs() as $pair) {
if (!$first) {
$isSequence = true;
foreach ($this->getKeyValuePairs() as $i => $pair) {
if (0 !== $i) {
$compiler->raw(', ');
}
$first = false;
$key = null;
if ($pair['key'] instanceof ContextVariable) {
$pair['key'] = new StringCastUnary($pair['key'], $pair['key']->getTemplateLine());
}
if ($pair['key'] instanceof TempNameExpression) {
} elseif ($pair['key'] instanceof TempNameExpression) {
$key = $pair['key']->getAttribute('name');
$pair['key'] = new ConstantExpression($key, $pair['key']->getTemplateLine());
}
if ($pair['key'] instanceof ConstantExpression) {
} elseif ($pair['key'] instanceof ConstantExpression) {
$key = $pair['key']->getAttribute('value');
}
if ($nextIndex !== $key && !$pair['value'] instanceof SpreadUnary) {
if ($key !== $i) {
$isSequence = false;
}
if (!$isSequence && !$pair['value'] instanceof SpreadUnary) {
$compiler
->subcompile($pair['key'])
->raw(' => ')
;
}
++$nextIndex;
$compiler->subcompile($pair['value']);
}
+5
View File
@@ -55,6 +55,9 @@ Twig supports array notation
{% set trad = {194:'ABC',141:'DEF',100:'GHI',170:'JKL',110:'MNO',111:'PQR'} %}
{% set trad2 = {'194':'ABC','141':'DEF','100':'GHI','170':'JKL','110':'MNO','111':'PQR'} %}
{{ trad == trad2 ? 'OK' : 'KO' }}
{% set trad = {11: 'ABC', 2: 'DEF', 4: 'GHI', 3: 'JKL'} %}
{% set trad2 = {'11': 'ABC', '2': 'DEF', '4': 'GHI', '3': 'JKL'} %}
{{ trad == trad2 ? 'OK' : 'KO' }}
{# indexes are kept #}
{{ { 1: "first", 0: "second" } == { '1': "first", '0': "second" } ? 'OK' : 'KO' }}
@@ -104,6 +107,7 @@ ok
ok
ok
OK
OK
OK
@@ -151,6 +155,7 @@ ok
ok
ok
OK
OK
OK