|
7 | 7 | use Traversable;
|
8 | 8 | use Webmozart\Assert\Assert;
|
9 | 9 |
|
| 10 | +use function is_callable; |
| 11 | + |
10 | 12 | final class Collector
|
11 | 13 | {
|
12 | 14 | /** @var array<int|string, mixed>|Traversable<int|string, mixed> */
|
13 | 15 | private iterable $data = [];
|
14 | 16 |
|
15 |
| - /** @var callable(mixed $datum, int|string|null $key=): bool|null */ |
| 17 | + /** @var null|callable(mixed $datum, int|string|null $key=): bool */ |
16 | 18 | private $when;
|
17 | 19 |
|
18 |
| - /** @var callable(mixed $datum, int|string|null $key=): mixed */ |
| 20 | + /** @var null|callable(mixed $datum, int|string|null $key=): mixed */ |
19 | 21 | private $transform;
|
20 | 22 |
|
21 | 23 | private ?int $limit = null;
|
@@ -62,20 +64,26 @@ public function withTransform(callable $transform): self
|
62 | 64 | */
|
63 | 65 | public function getResults(): array
|
64 | 66 | {
|
65 |
| - // ensure when property is set early via ->when() and ->withTransform() method |
66 |
| - Assert::isCallable($this->when); |
| 67 | + // ensure transform property is set early ->withTransform() method |
67 | 68 | Assert::isCallable($this->transform);
|
68 | 69 |
|
69 |
| - $count = 0; |
70 |
| - $collectedData = []; |
| 70 | + $count = 0; |
| 71 | + $collectedData = []; |
| 72 | + $isCallableWhen = is_callable($this->when); |
71 | 73 |
|
72 | 74 | foreach ($this->data as $key => $datum) {
|
73 |
| - $isFound = ($this->when)($datum, $key); |
74 |
| - |
75 |
| - Assert::boolean($isFound); |
76 |
| - |
77 |
| - if (! $isFound) { |
78 |
| - continue; |
| 75 | + if ($isCallableWhen) { |
| 76 | + /** |
| 77 | + * @var callable(mixed $datum, int|string|null $key=): bool $when |
| 78 | + */ |
| 79 | + $when = $this->when; |
| 80 | + $isFound = ($when)($datum, $key); |
| 81 | + |
| 82 | + Assert::boolean($isFound); |
| 83 | + |
| 84 | + if (! $isFound) { |
| 85 | + continue; |
| 86 | + } |
79 | 87 | }
|
80 | 88 |
|
81 | 89 | $collectedData[] = ($this->transform)($datum, $key);
|
|
0 commit comments