Skip to content

Commit

Permalink
If an object implements \ArrayAccess, check both array value and prop…
Browse files Browse the repository at this point in the history
…erty
  • Loading branch information
shish committed Feb 26, 2024
1 parent ac44145 commit f2a1729
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Utils/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,16 @@ public static function suggestionList(string $input, array $options): array
*/
public static function extractKey($objectLikeValue, string $key)
{
if (\is_array($objectLikeValue) || $objectLikeValue instanceof \ArrayAccess) {
if (\is_array($objectLikeValue)) {
return $objectLikeValue[$key] ?? null;
}

if ($objectLikeValue instanceof \ArrayAccess) {
return $objectLikeValue[$key]
?? $objectLikeValue->{$key} // @phpstan-ignore-line Variable property access on ArrayAccess is fine here, we do the same for arbitrary objects
?? null;
}

if (\is_object($objectLikeValue)) {
return $objectLikeValue->{$key} ?? null;
}
Expand Down
5 changes: 5 additions & 0 deletions tests/Executor/ExecutorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,7 @@ public function testDefaultResolverGrabsValuesOffOfCommonPhpDataStructures(): vo
'name' => 'ArrayAccess',
'fields' => [
'set' => Type::int(),
'setProperty' => Type::int(),
'unsetNull' => Type::int(),
'unsetThrow' => Type::int(),
],
Expand Down Expand Up @@ -1151,6 +1152,8 @@ public function testDefaultResolverGrabsValuesOffOfCommonPhpDataStructures(): vo
'arrayAccess' => [
'type' => $ArrayAccess,
'resolve' => static fn (): \ArrayAccess => new class() implements \ArrayAccess {
public ?int $setProperty = 1;

/** @param mixed $offset */
#[\ReturnTypeWillChange]
public function offsetExists($offset): bool
Expand Down Expand Up @@ -1244,6 +1247,7 @@ public function __get(string $name): ?int
}
arrayAccess {
set
setProperty
unsetNull
unsetThrow
}
Expand Down Expand Up @@ -1271,6 +1275,7 @@ public function __get(string $name): ?int
],
'arrayAccess' => [
'set' => 1,
'setProperty' => 1,
'unsetNull' => null,
'unsetThrow' => null,
],
Expand Down

0 comments on commit f2a1729

Please sign in to comment.