From e3dc112e146876994cd0ec9ac602d24257a973ab Mon Sep 17 00:00:00 2001 From: Oluwatobi Omisakin Date: Tue, 30 Apr 2024 19:32:05 +0300 Subject: [PATCH] feat: Search with closure matching --- src/Arrayed.php | 2 +- src/Interfaces/ArrayedInterface.php | 2 +- src/Traits/ArrayPrefix.php | 8 ++++++++ tests/ArrayPrefixTraitTest.php | 16 ++++++++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Arrayed.php b/src/Arrayed.php index 2a7e8eb..8b8ecbd 100644 --- a/src/Arrayed.php +++ b/src/Arrayed.php @@ -54,7 +54,7 @@ public function map($callback, ...$_): ArrayedInterface return $this->setResult(array_map($callback, $this->getWorkableItem(), ...$_)); } - public function filter($callback = null, int $flag = 0): ArrayedInterface + public function filter(Closure $callback = null, int $flag = 0): ArrayedInterface { if ($callback) { return $this->setResult(array_filter($this->getWorkableItem(), $callback, $flag)); diff --git a/src/Interfaces/ArrayedInterface.php b/src/Interfaces/ArrayedInterface.php index 0930948..2af24d3 100644 --- a/src/Interfaces/ArrayedInterface.php +++ b/src/Interfaces/ArrayedInterface.php @@ -14,7 +14,7 @@ public static function on(...$values): ArrayedInterface; public function map($callback): ArrayedInterface; - public function filter($callback = null, int $flag = 0): ArrayedInterface; + public function filter(Closure $callback = null, int $flag = 0): ArrayedInterface; public function reduce($function, $initial = null): ArrayedInterface; diff --git a/src/Traits/ArrayPrefix.php b/src/Traits/ArrayPrefix.php index 7327930..6fb3d4d 100644 --- a/src/Traits/ArrayPrefix.php +++ b/src/Traits/ArrayPrefix.php @@ -87,6 +87,14 @@ public function walkRecursive(callable $callable, $arg = null) public function search($needle, bool $strict = true, $default = null) { + if ($needle instanceof \Closure) { + return $this->filter(fn($value) => $needle($value)) + ->keys() + ->when($this->getWorkableItem(), new self([$default])) + ->offsetGet(0); + } + + $result = array_search($needle, $this->getWorkableItem(), $strict); if ($result === false) { diff --git a/tests/ArrayPrefixTraitTest.php b/tests/ArrayPrefixTraitTest.php index 1a0451f..2139780 100644 --- a/tests/ArrayPrefixTraitTest.php +++ b/tests/ArrayPrefixTraitTest.php @@ -268,5 +268,21 @@ public function testSearch(): void false, arrayed($data)->search('z', true, false), ); + + // With callback. + $this->assertEquals( + 1, + arrayed($data)->search(fn($value) => $value === 'b'), + ); + + // Empty with default. + $this->assertEquals( + 'no', + arrayed([])->search( + fn($value) => $value === 'b', + true, + 'no', + ), + ); } }