From 20c6b455e17057570df2cb9e84b7da00a78628b1 Mon Sep 17 00:00:00 2001 From: Oluwatobi Omisakin Date: Tue, 30 Apr 2024 19:44:56 +0300 Subject: [PATCH] feat: Search with closure matching using key and value --- src/Arrayed.php | 2 +- src/Traits/ArrayPrefix.php | 2 +- tests/ArrayPrefixTraitTest.php | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Arrayed.php b/src/Arrayed.php index 8b8ecbd..7345719 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(Closure $callback = null, int $flag = 0): ArrayedInterface + public function filter(Closure $callback = null, int $flag = ARRAY_FILTER_USE_BOTH): ArrayedInterface { if ($callback) { return $this->setResult(array_filter($this->getWorkableItem(), $callback, $flag)); diff --git a/src/Traits/ArrayPrefix.php b/src/Traits/ArrayPrefix.php index 6fb3d4d..47dccf6 100644 --- a/src/Traits/ArrayPrefix.php +++ b/src/Traits/ArrayPrefix.php @@ -88,7 +88,7 @@ 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)) + return $this->filter(fn($value, $key) => $needle($value, $key)) ->keys() ->when($this->getWorkableItem(), new self([$default])) ->offsetGet(0); diff --git a/tests/ArrayPrefixTraitTest.php b/tests/ArrayPrefixTraitTest.php index 2139780..bdd409b 100644 --- a/tests/ArrayPrefixTraitTest.php +++ b/tests/ArrayPrefixTraitTest.php @@ -284,5 +284,13 @@ public function testSearch(): void 'no', ), ); + + // With key, value, in callback. + $this->assertEquals( + 2, + arrayed($data)->search( + fn($value, $key) => $value === 'c' && $key = 2, + ), + ); } }