Skip to content

Commit

Permalink
Seq: Don't interpret function names as callables
Browse files Browse the repository at this point in the history
fixes #41
  • Loading branch information
nilmerg committed Jun 23, 2023
1 parent 9300f87 commit 7955529
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Seq.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace ipl\Stdlib;

use Closure;

/**
* Collection of utilities for traversables
*/
Expand Down Expand Up @@ -32,7 +34,7 @@ public static function contains($traversable, $needle, $caseSensitive = true)
*/
public static function find($traversable, $needle, $caseSensitive = true)
{
$usesCallback = is_callable($needle);
$usesCallback = $needle instanceof Closure;
if (! $usesCallback && $caseSensitive && is_array($traversable)) {
return [array_search($needle, $traversable, true), $needle];
}
Expand Down Expand Up @@ -82,7 +84,7 @@ public static function findKey($traversable, $needle, $caseSensitive = true)
*/
public static function findValue($traversable, $needle, $caseSensitive = true)
{
$usesCallback = is_callable($needle);
$usesCallback = $needle instanceof Closure;
if (! $usesCallback && $caseSensitive && is_array($traversable)) {
return isset($traversable[$needle]) ? $traversable[$needle] : null;
}
Expand Down
42 changes: 42 additions & 0 deletions tests/SeqTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,46 @@ public function testFindValueWithIterators()
Seq::findValue(new ArrayIterator(['foo' => 'bar', 'FOO' => 'BAR']), 'FOO', false)
);
}

public function testFindWithCallback()
{
$this->assertEquals(
[1, 'foo'],
Seq::find(
['bar', 'foo'],
function ($value) {
return $value !== 'bar';
},
false // Should have no effect
)
);
$this->assertEquals(
'foo',
Seq::findValue(
['bar', 'foo'],
function ($value) {
return $value !== 0;
},
false // Should have no effect
)
);
}

public function testFindWithFunctionName()
{
$this->assertEquals(
[1, 'sleep'],
Seq::find(
['awake', 'sleep'],
'sleep'
)
);
$this->assertEquals(
'sleep',
Seq::findValue(
['awake', 'sleep' => 'sleep'],
'sleep'
)
);
}
}

0 comments on commit 7955529

Please sign in to comment.