Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
}
}