Skip to content

Commit

Permalink
Feat: Add support for filtering using key (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod authored Mar 27, 2024
1 parent fdfdc2e commit 9bfa4d8
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/IterableObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use function array_map;
use function iterator_to_array;

use const ARRAY_FILTER_USE_BOTH;

/**
* @internal
*
Expand All @@ -40,7 +42,7 @@ public function __construct(iterable $iterable, bool $preserveKeys = true)
}

/**
* @param (callable(TValue):bool)|null $filter
* @param (callable(TValue):bool)|(callable(TValue,TKey):bool)|null $filter
*
* @return self<TKey, TValue>
*/
Expand All @@ -56,7 +58,9 @@ static function ($value): bool {
return new self(new CallbackFilterIterator(new IteratorIterator($this->iterable), $filter));
}

$filtered = $filter === null ? array_filter($this->iterable) : array_filter($this->iterable, $filter);
$filtered = $filter === null
? array_filter($this->iterable)
: array_filter($this->iterable, $filter, ARRAY_FILTER_USE_BOTH);

return new self($filtered);
}
Expand Down
2 changes: 1 addition & 1 deletion src/iterable-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ function iterable_to_traversable(iterable $iterable): Traversable
/**
* Filters an iterable.
*
* @param (callable(TValue):bool)|null $filter
* @param (callable(TValue):bool)|(callable(TValue,TKey):bool)|null $filter
*
* @psalm-param iterable<TKey, TValue> $iterable
* @psalm-return iterable<TKey, TValue>
Expand Down
26 changes: 26 additions & 0 deletions tests/IterableFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace BenTools\IterableFunctions\Tests;

use Generator;
use SplFixedArray;
use Traversable;

Expand Down Expand Up @@ -47,3 +48,28 @@ static function ($input): bool {
assert($filtered instanceof Traversable);
assertSame([1 => 'bar'], iterator_to_array($filtered));
});

it('filters a Traversable object with a callback using key', function (): void {
$iterable = (function (): Generator {
yield 'foo' => 1;
yield 'bar' => 1;
})();
$filter =
static function (int $input, string $key): bool {
return $key === 'bar';
};
$filtered = iterable_filter($iterable, $filter);
assert($filtered instanceof Traversable);
assertSame(['bar' => 1], iterator_to_array($filtered));
});

it('filters an array with a callback using key', function (): void {
$iterable = ['foo' => 1, 'bar' => 1];
$filter =
static function (int $input, string $key): bool {
return $key === 'bar';
};
$filtered = iterable_filter($iterable, $filter);
assert($filtered instanceof Traversable);
assertSame(['bar' => 1], iterator_to_array($filtered));
});

0 comments on commit 9bfa4d8

Please sign in to comment.