diff --git a/spec/drupol/collection/CollectionSpec.php b/spec/drupol/collection/CollectionSpec.php index b46c790a3..ba3ed8e3b 100644 --- a/spec/drupol/collection/CollectionSpec.php +++ b/spec/drupol/collection/CollectionSpec.php @@ -408,8 +408,8 @@ public function it_can_filter_its_element(): void $this ->beConstructedThrough('with', [$input]); - $callable = static function ($item) { - return $item % 2; + $callable = static function ($value, $key, $iterator) { + return $value % 2; }; $this @@ -425,7 +425,7 @@ public function it_can_filter_its_element(): void $this ->filter() ->normalize() - ->shouldIterateAs([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + ->shouldIterateAs([]); } public function it_can_flatten(): void diff --git a/src/Operation/Filter.php b/src/Operation/Filter.php index 6a3237c6f..a52ed0722 100644 --- a/src/Operation/Filter.php +++ b/src/Operation/Filter.php @@ -4,8 +4,10 @@ namespace drupol\collection\Operation; +use CallbackFilterIterator; use Closure; use drupol\collection\Contract\Operation; +use drupol\collection\Iterator\IterableIterator; use Generator; /** @@ -35,19 +37,11 @@ public function on(iterable $collection): Closure { $callbacks = $this->callbacks; - if ([] === $callbacks) { - $callbacks[] = static function ($value) { - return $value; - }; - } - return static function () use ($callbacks, $collection): Generator { + $iterator = $collection; + foreach ($callbacks as $callback) { - foreach ($collection as $key => $value) { - if (true === (bool) $callback($value, $key)) { - yield $key => $value; - } - } + yield from $iterator = new CallbackFilterIterator(new IterableIterator($iterator), $callback); } }; }