Skip to content

Commit 903dfc5

Browse files
authored
Merge pull request #35 from transprime-research/feat-add-array-search-with-closure-search-using-key-and-value
feat: Fix issues with search result overriding last result
2 parents 8a71226 + a3ffd1e commit 903dfc5

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/Traits/ArrayPrefix.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,10 @@ public function walkRecursive(callable $callable, $arg = null)
8888
public function search($needle, bool $strict = true, $default = null)
8989
{
9090
if ($needle instanceof \Closure) {
91-
return $this->filter(fn($value, $key) => $needle($value, $key))
92-
->keys()
91+
return $this
92+
->copy()
93+
->filter(fn($value, $key) => $needle($value, $key))
94+
->keys(false)
9395
->when($this->getWorkableItem(), new self([$default]))
9496
->offsetGet(0);
9597
}

tests/ArrayPrefixTraitTest.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,8 +289,23 @@ public function testSearch(): void
289289
$this->assertEquals(
290290
2,
291291
arrayed($data)->search(
292-
fn($value, $key) => $value === 'c' && $key = 2,
292+
fn($value, $key) => $value === 'c' && $key == 2,
293293
),
294294
);
295+
296+
// Ensure initial result is not overwritten.
297+
$arrayed = arrayed($data);
298+
299+
$searchResult = $arrayed->search(fn($value, $key) => $value === 'c' && $key === 2);
300+
301+
$this->assertEquals(
302+
2,
303+
$searchResult,
304+
);
305+
306+
$this->assertEquals(
307+
['a', 'b', 'c', 'd'],
308+
$arrayed->result(),
309+
);
295310
}
296311
}

0 commit comments

Comments
 (0)