From 7955529f5482912333bb2de585b0639b6627a57a Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 20 Jun 2023 14:03:49 +0200 Subject: [PATCH] Seq: Don't interpret function names as callables fixes #41 --- src/Seq.php | 6 ++++-- tests/SeqTest.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/Seq.php b/src/Seq.php index 0f40c93..66bc781 100644 --- a/src/Seq.php +++ b/src/Seq.php @@ -2,6 +2,8 @@ namespace ipl\Stdlib; +use Closure; + /** * Collection of utilities for traversables */ @@ -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]; } @@ -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; } diff --git a/tests/SeqTest.php b/tests/SeqTest.php index 3028dd5..8f24fbf 100644 --- a/tests/SeqTest.php +++ b/tests/SeqTest.php @@ -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' + ) + ); + } }