Skip to content

Commit

Permalink
bug #4496 Fix ArrayAccess with objects as keys (gharlan)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.x branch.

Discussion
----------

Fix ArrayAccess with objects as keys

fixes #4476
The bug was introduced in 3.15 via #4425 (comment)

Commits
-------

32a75b7 Fix ArrayAccess with objects as keys
  • Loading branch information
fabpot committed Dec 10, 2024
2 parents 57bf519 + 32a75b7 commit d8a798c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Extension/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -1644,7 +1644,7 @@ public static function getAttribute(Environment $env, Source $source, $object, $

// array
if (Template::METHOD_CALL !== $type) {
$arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item = (string) $item;
$arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item;

if ($sandboxed && $object instanceof \ArrayAccess && !\in_array($object::class, self::ARRAY_LIKE_CLASSES, true)) {
try {
Expand Down
17 changes: 15 additions & 2 deletions tests/Fixtures/expressions/array.test
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,19 @@ Twig supports array notation
{# ArrayAccess #}
{{ array_access['a'] }}

{# ObjectStorage #}
{{ object_storage[object] }}
{{ object_storage[object_storage]|default('bar') }}

{# array that does not exist #}
{{ does_not_exist[0]|default('ok') }}
{{ does_not_exist[0].does_not_exist_either|default('ok') }}
{{ does_not_exist[0]['does_not_exist_either']|default('ok') }}
--DATA--
return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['a' => 'b'])]
$objectStorage = new SplObjectStorage();
$object = new stdClass();
$objectStorage[$object] = 'foo';
return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['a' => 'b']), 'object_storage' => $objectStorage, 'object' => $object]
--EXPECT--
1,2
foo,bar
Expand All @@ -71,11 +78,14 @@ a,b,c,d,e

b

foo
bar

ok
ok
ok
--DATA--
return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['a' => 'b'])]
return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['a' => 'b']), 'object' => new stdClass()]
--CONFIG--
return ['strict_variables' => false]
--EXPECT--
Expand All @@ -101,6 +111,9 @@ a,b,c,d,e

b


bar

ok
ok
ok

0 comments on commit d8a798c

Please sign in to comment.