1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace AardsGerds\Game\Shared; |
||
6 | |||
7 | use function Lambdish\Phunctional\first; |
||
8 | use function Lambdish\Phunctional\all; |
||
9 | use function Lambdish\Phunctional\instance_of; |
||
10 | |||
11 | abstract class Collection implements \IteratorAggregate, \Countable |
||
12 | { |
||
13 | protected array $items; |
||
14 | |||
15 | 21 | final public function __construct(iterable $items) |
|
16 | { |
||
17 | 21 | $this->items = $items instanceof \Traversable ? iterator_to_array($items) : $items; |
|
18 | 21 | $this->assertType(); |
|
19 | 20 | } |
|
20 | |||
21 | 7 | public function getItems(): array |
|
22 | { |
||
23 | 7 | return $this->items; |
|
24 | } |
||
25 | |||
26 | 11 | public function count(): int |
|
27 | { |
||
28 | 11 | return count($this->items); |
|
29 | } |
||
30 | |||
31 | 6 | public function isEmpty(): bool |
|
32 | { |
||
33 | 6 | return count($this->items) < 1; |
|
34 | } |
||
35 | |||
36 | 6 | public function makeSureNotEmpty(): void |
|
37 | { |
||
38 | 6 | if ($this->isEmpty()) { |
|
39 | 1 | throw CollectionException::emptyCollection(); |
|
40 | } |
||
41 | 5 | } |
|
42 | |||
43 | 12 | public function filter(callable $filter): static |
|
44 | { |
||
45 | 12 | return new static(array_filter($this->items, $filter)); |
|
46 | } |
||
47 | |||
48 | 12 | public function getIterator(): \ArrayIterator |
|
49 | { |
||
50 | 12 | return new \ArrayIterator($this->items); |
|
51 | } |
||
52 | |||
53 | abstract protected function getType(): string; |
||
54 | |||
55 | 21 | private function assertType(): void |
|
56 | { |
||
57 | 21 | $type = $this->getType(); |
|
58 | |||
59 | 21 | if (!all(instance_of($type), $this->items)) { |
|
60 | 1 | throw CollectionException::invalidType(get_class(first($this->items)), $type); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
61 | } |
||
62 | 20 | } |
|
63 | } |
||
64 |