Skip to content

Commit

Permalink
Merge pull request #34 from transprime-research/feat-add-array-search…
Browse files Browse the repository at this point in the history
…-with-closure-search-using-key-and-value

feat: Search with closure matching using key and value
  • Loading branch information
omitobi authored Apr 30, 2024
2 parents 22d06d6 + 20c6b45 commit 8a71226
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Arrayed.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
2 changes: 1 addition & 1 deletion src/Traits/ArrayPrefix.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions tests/ArrayPrefixTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
);
}
}

0 comments on commit 8a71226

Please sign in to comment.