Skip to content

Commit 9bfa4d8

Browse files
authored
Feat: Add support for filtering using key (#48)
1 parent fdfdc2e commit 9bfa4d8

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

src/IterableObject.php

+6-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
use function array_map;
1717
use function iterator_to_array;
1818

19+
use const ARRAY_FILTER_USE_BOTH;
20+
1921
/**
2022
* @internal
2123
*
@@ -40,7 +42,7 @@ public function __construct(iterable $iterable, bool $preserveKeys = true)
4042
}
4143

4244
/**
43-
* @param (callable(TValue):bool)|null $filter
45+
* @param (callable(TValue):bool)|(callable(TValue,TKey):bool)|null $filter
4446
*
4547
* @return self<TKey, TValue>
4648
*/
@@ -56,7 +58,9 @@ static function ($value): bool {
5658
return new self(new CallbackFilterIterator(new IteratorIterator($this->iterable), $filter));
5759
}
5860

59-
$filtered = $filter === null ? array_filter($this->iterable) : array_filter($this->iterable, $filter);
61+
$filtered = $filter === null
62+
? array_filter($this->iterable)
63+
: array_filter($this->iterable, $filter, ARRAY_FILTER_USE_BOTH);
6064

6165
return new self($filtered);
6266
}

src/iterable-functions.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ function iterable_to_traversable(iterable $iterable): Traversable
8787
/**
8888
* Filters an iterable.
8989
*
90-
* @param (callable(TValue):bool)|null $filter
90+
* @param (callable(TValue):bool)|(callable(TValue,TKey):bool)|null $filter
9191
*
9292
* @psalm-param iterable<TKey, TValue> $iterable
9393
* @psalm-return iterable<TKey, TValue>

tests/IterableFilterTest.php

+26
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace BenTools\IterableFunctions\Tests;
66

7+
use Generator;
78
use SplFixedArray;
89
use Traversable;
910

@@ -47,3 +48,28 @@ static function ($input): bool {
4748
assert($filtered instanceof Traversable);
4849
assertSame([1 => 'bar'], iterator_to_array($filtered));
4950
});
51+
52+
it('filters a Traversable object with a callback using key', function (): void {
53+
$iterable = (function (): Generator {
54+
yield 'foo' => 1;
55+
yield 'bar' => 1;
56+
})();
57+
$filter =
58+
static function (int $input, string $key): bool {
59+
return $key === 'bar';
60+
};
61+
$filtered = iterable_filter($iterable, $filter);
62+
assert($filtered instanceof Traversable);
63+
assertSame(['bar' => 1], iterator_to_array($filtered));
64+
});
65+
66+
it('filters an array with a callback using key', function (): void {
67+
$iterable = ['foo' => 1, 'bar' => 1];
68+
$filter =
69+
static function (int $input, string $key): bool {
70+
return $key === 'bar';
71+
};
72+
$filtered = iterable_filter($iterable, $filter);
73+
assert($filtered instanceof Traversable);
74+
assertSame(['bar' => 1], iterator_to_array($filtered));
75+
});

0 commit comments

Comments
 (0)