diff --git a/CHANGELOG b/CHANGELOG index 44ef08c23..f7b3040ce 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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) diff --git a/src/Node/Expression/ArrayExpression.php b/src/Node/Expression/ArrayExpression.php index 9678be26c..b6f8a6ba4 100644 --- a/src/Node/Expression/ArrayExpression.php +++ b/src/Node/Expression/ArrayExpression.php @@ -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']); } diff --git a/tests/Fixtures/expressions/array.test b/tests/Fixtures/expressions/array.test index ac1c8ca0e..72efbf9ee 100644 --- a/tests/Fixtures/expressions/array.test +++ b/tests/Fixtures/expressions/array.test @@ -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