Fix accessing arrays with stringable objects as key

This commit is contained in:
Nicolas Grekas
2025-10-24 14:15:21 +02:00
parent d26e8f2b74
commit 9ae75d315c
3 changed files with 29 additions and 4 deletions
+7 -3
View File
@@ -1694,7 +1694,7 @@ final class CoreExtension extends AbstractExtension
}
if (match (true) {
\is_array($object) => \array_key_exists($arrayItem, $object),
\is_array($object) => \array_key_exists($arrayItem = (string) $arrayItem, $object),
$object instanceof \ArrayAccess => $object->offsetExists($arrayItem),
default => false,
}) {
@@ -1715,9 +1715,13 @@ final class CoreExtension extends AbstractExtension
}
if ($object instanceof \ArrayAccess) {
$message = \sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, $object::class);
if (\is_object($arrayItem) || \is_array($arrayItem)) {
$message = \sprintf('Key of type "%s" does not exist in ArrayAccess-able object of class "%s".', get_debug_type($arrayItem), get_debug_type($object));
} else {
$message = \sprintf('Key "%s" does not exist in ArrayAccess-able object of class "%s".', $arrayItem, get_debug_type($object));
}
} elseif (\is_object($object)) {
$message = \sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, $object::class);
$message = \sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, get_debug_type($object));
} elseif (\is_array($object)) {
if (!$object) {
$message = \sprintf('Key "%s" does not exist as the sequence/mapping is empty.', $arrayItem);
@@ -0,0 +1,21 @@
--TEST--
#4701 Accessing arrays with stringable objects as key
--TEMPLATE--
{% set hash = {
'foo': 'FOO',
'bar': 'BAR',
} %}
{{ hash[key] }}
--DATA--
class MyObj {
public function __toString() {
return 'foo';
}
}
return [
'key' => new MyObj(),
];
--EXPECT--
FOO
+1 -1
View File
@@ -77,7 +77,7 @@ class TemplateTest extends TestCase
['{{ null["a"] }}', 'Impossible to access a key ("a") on a null variable in "%s" at line 1.'],
['{{ empty_array["a"] }}', 'Key "a" does not exist as the sequence/mapping is empty in "%s" at line 1.'],
['{{ array["a"] }}', 'Key "a" for sequence/mapping with keys "foo" does not exist in "%s" at line 1.'],
['{{ array_access["a"] }}', 'Key "a" in object with ArrayAccess of class "Twig\Tests\TemplateArrayAccessObject" does not exist in "%s" at line 1.'],
['{{ array_access["a"] }}', 'Key "a" does not exist in ArrayAccess-able object of class "Twig\Tests\TemplateArrayAccessObject" in "%s" at line 1.'],
['{{ string.a }}', 'Impossible to access an attribute ("a") on a string variable ("foo") in "%s" at line 1.'],
['{{ string.a() }}', 'Impossible to invoke a method ("a") on a string variable ("foo") in "%s" at line 1.'],
['{{ null.a }}', 'Impossible to access an attribute ("a") on a null variable in "%s" at line 1.'],