diff --git a/README.md b/README.md index f372d5b..f59b939 100644 --- a/README.md +++ b/README.md @@ -396,7 +396,7 @@ $limit = 2; $transform = fn ($datum): string => trim($datum); $newArray = Collector::setUp($data) - ->when($when) + ->when($when) // optional, can just transform without filtering ->withLimit(2) // optional to only collect some data provided by limit config ->withTransform($transform) ->getResults(); diff --git a/src/Collector.php b/src/Collector.php index 1376203..46d2106 100644 --- a/src/Collector.php +++ b/src/Collector.php @@ -7,15 +7,17 @@ use Traversable; use Webmozart\Assert\Assert; +use function is_callable; + final class Collector { /** @var array|Traversable */ private iterable $data = []; - /** @var callable(mixed $datum, int|string|null $key=): bool|null */ + /** @var null|callable(mixed $datum, int|string|null $key=): bool */ private $when; - /** @var callable(mixed $datum, int|string|null $key=): mixed */ + /** @var null|callable(mixed $datum, int|string|null $key=): mixed */ private $transform; private ?int $limit = null; @@ -62,20 +64,26 @@ public function withTransform(callable $transform): self */ public function getResults(): array { - // ensure when property is set early via ->when() and ->withTransform() method - Assert::isCallable($this->when); + // ensure transform property is set early ->withTransform() method Assert::isCallable($this->transform); - $count = 0; - $collectedData = []; + $count = 0; + $collectedData = []; + $isCallableWhen = is_callable($this->when); foreach ($this->data as $key => $datum) { - $isFound = ($this->when)($datum, $key); - - Assert::boolean($isFound); - - if (! $isFound) { - continue; + if ($isCallableWhen) { + /** + * @var callable(mixed $datum, int|string|null $key=): bool $when + */ + $when = $this->when; + $isFound = ($when)($datum, $key); + + Assert::boolean($isFound); + + if (! $isFound) { + continue; + } } $collectedData[] = ($this->transform)($datum, $key); diff --git a/tests/CollectorTest.php b/tests/CollectorTest.php index 6b1b82d..af4a551 100644 --- a/tests/CollectorTest.php +++ b/tests/CollectorTest.php @@ -13,6 +13,21 @@ final class CollectorTest extends TestCase { + public function testWithoutWhen(): void + { + $data = [ + ' a ', + ' b ', + ' c ', + ]; + + $results = Collector::setUp($data) + ->withTransform(fn (string $datum): string => trim($datum)) + ->getResults(); + + $this->assertSame(['a', 'b', 'c'], $results); + } + public function testWithoutLimit(): void { $data = [