|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace ArrayLookup; |
| 6 | + |
| 7 | +use Traversable; |
| 8 | +use Webmozart\Assert\Assert; |
| 9 | + |
| 10 | +final class Collector |
| 11 | +{ |
| 12 | + /** |
| 13 | + * @var array<int|string, mixed>|Traversable<int|string, mixed> |
| 14 | + */ |
| 15 | + private static iterable $data = []; |
| 16 | + |
| 17 | + /** |
| 18 | + * @var callable(mixed $datum, int|string|null $key=): bool|null |
| 19 | + */ |
| 20 | + private $when; |
| 21 | + |
| 22 | + /** |
| 23 | + * @var callable(mixed $datum, int|string|null $key=): mixed |
| 24 | + */ |
| 25 | + private $transform; |
| 26 | + |
| 27 | + private ?int $limit = null; |
| 28 | + |
| 29 | + /** |
| 30 | + * @param array<int|string, mixed>|Traversable<int|string, mixed> $data |
| 31 | + */ |
| 32 | + public static function setUp(iterable $data): self |
| 33 | + { |
| 34 | + $self = new self(); |
| 35 | + $self->$data = $data; |
| 36 | + |
| 37 | + return $self; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * @param callable(mixed $datum, int|string|null $key=): bool $filter |
| 42 | + */ |
| 43 | + public function when(callable $filter): self |
| 44 | + { |
| 45 | + $this->when = $filter; |
| 46 | + return $this; |
| 47 | + } |
| 48 | + |
| 49 | + public function withLimit(int $limit): self |
| 50 | + { |
| 51 | + Assert::positiveInteger($limit); |
| 52 | + $this->limit = $limit; |
| 53 | + |
| 54 | + return $this; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @param callable(mixed $datum, int|string|null $key=): mixed $transform |
| 59 | + */ |
| 60 | + public function withTransform(callable $transform): self |
| 61 | + { |
| 62 | + $this->transform = $transform; |
| 63 | + return $this; |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @return mixed[] |
| 68 | + */ |
| 69 | + public function getResults(): array |
| 70 | + { |
| 71 | + // ensure when property is set early via ->when() and ->withTransform() method |
| 72 | + Assert::isCallable($this->when); |
| 73 | + Assert::isCallable($this->transform); |
| 74 | + |
| 75 | + $count = 0; |
| 76 | + $collectedData = []; |
| 77 | + |
| 78 | + foreach ($this->data as $key => $datum) { |
| 79 | + $isFound = ($this->when)($datum, $key); |
| 80 | + |
| 81 | + Assert::boolean($isFound); |
| 82 | + |
| 83 | + if (! $isFound) { |
| 84 | + continue; |
| 85 | + } |
| 86 | + |
| 87 | + $collectedData[] = ($this->transform)($datum, $key); |
| 88 | + |
| 89 | + ++$count; |
| 90 | + |
| 91 | + if ($this->limit === $count) { |
| 92 | + break; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return $collectedData; |
| 97 | + } |
| 98 | +} |
0 commit comments