Skip to content

Commit

Permalink
Fixes #217: use array_key_exists() in pick() for arrays (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
lstrojny authored Mar 7, 2021
1 parent df44e36 commit 300fac0
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Functional/Pick.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
* @param ArrayAccess|array $collection
* @param mixed $index
* @param mixed $default
* @param callable $callback Custom function to check if index exists, default function is "isset"
* @param callable|null $callback Custom function to check if index exists
* @return mixed
* @no-named-arguments
*/
Expand All @@ -29,7 +29,7 @@ function pick($collection, $index, $default = null, callable $callback = null)
InvalidArgumentException::assertArrayAccess($collection, __FUNCTION__, 1);

if ($callback === null) {
if (!isset($collection[$index])) {
if (!isset($collection[$index]) && (!\is_array($collection) || !\array_key_exists($index, $collection))) {
return $default;
}
} else {
Expand Down
4 changes: 4 additions & 0 deletions tests/Functional/PickTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ public function testDefaultValue(): void
pick($this->array_1, 'one', 5),
'Index does exists, should return the corresponding value'
);

self::assertNull(pick($this->array_1, 'null-index', 'default'), 'Will handle null correctly');
}

public function testCustomCallback(): void
Expand All @@ -93,8 +95,10 @@ public function testArrayAccess(): void
$object = new ArrayObject();

$object['test'] = 5;
$object['null'] = null;

self::assertSame(5, pick($object, 'test'), 'Key exists');
self::assertNull(pick($object, 'null'), 'Key exists');
self::assertSame(10, pick($object, 'dummy', 10), 'Key does not exists');
}
}

0 comments on commit 300fac0

Please sign in to comment.