From a3ffd1ef86b50be935c0a354bb5a45b2ae088760 Mon Sep 17 00:00:00 2001 From: Oluwatobi Omisakin Date: Tue, 30 Apr 2024 20:02:12 +0300 Subject: [PATCH] feat: Fix issues with search result overriding last result --- src/Traits/ArrayPrefix.php | 6 ++++-- tests/ArrayPrefixTraitTest.php | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Traits/ArrayPrefix.php b/src/Traits/ArrayPrefix.php index 47dccf6..dfe8463 100644 --- a/src/Traits/ArrayPrefix.php +++ b/src/Traits/ArrayPrefix.php @@ -88,8 +88,10 @@ 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, $key) => $needle($value, $key)) - ->keys() + return $this + ->copy() + ->filter(fn($value, $key) => $needle($value, $key)) + ->keys(false) ->when($this->getWorkableItem(), new self([$default])) ->offsetGet(0); } diff --git a/tests/ArrayPrefixTraitTest.php b/tests/ArrayPrefixTraitTest.php index bdd409b..ce0fe8c 100644 --- a/tests/ArrayPrefixTraitTest.php +++ b/tests/ArrayPrefixTraitTest.php @@ -289,8 +289,23 @@ public function testSearch(): void $this->assertEquals( 2, arrayed($data)->search( - fn($value, $key) => $value === 'c' && $key = 2, + fn($value, $key) => $value === 'c' && $key == 2, ), ); + + // Ensure initial result is not overwritten. + $arrayed = arrayed($data); + + $searchResult = $arrayed->search(fn($value, $key) => $value === 'c' && $key === 2); + + $this->assertEquals( + 2, + $searchResult, + ); + + $this->assertEquals( + ['a', 'b', 'c', 'd'], + $arrayed->result(), + ); } }