From 7577986980b9e80473e3e0f3d00e01a55e1087f5 Mon Sep 17 00:00:00 2001 From: Oliver Vogel Date: Sat, 30 Sep 2023 16:48:34 +0200 Subject: [PATCH] Add filter method to Collection --- src/Collection.php | 15 +++++++++++++++ tests/CollectionTest.php | 10 ++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/Collection.php b/src/Collection.php index 5434f83bc..76e35b139 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -134,6 +134,21 @@ public function map(callable $callback): self return new self($items); } + /** + * Run callback on each item of the collection an remove it if it does not return true + * + * @param callable $callback + * @return Collection + */ + public function filter(callable $callback): self + { + $items = array_filter($this->items, function ($item) use ($callback) { + return $callback($item); + }); + + return new self($items); + } + public function pushEach(array $data, ?callable $callback = null): CollectionInterface { if (! is_iterable($data)) { diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index 9703486ef..67488a62e 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -45,6 +45,16 @@ public function testCount() $this->assertEquals(3, count($collection)); } + public function testFilter() + { + $collection = new Collection(['foo', 'bar', 'baz']); + $this->assertEquals(3, $collection->count()); + $collection = $collection->filter(function ($text) { + return substr($text, 0, 1) == 'b'; + }); + $this->assertEquals(2, $collection->count()); + } + public function testFirstLast() { $collection = new Collection(['foo', 'bar', 'baz']);