Passed
Push — master ( 947512...97c1fb )
by Paweł
03:48
created

Collection::assertType()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AardsGerds\Game\Shared;
6
7
abstract class Collection implements \IteratorAggregate, \Countable
8
{
9
    protected array $items;
10
11 4
    final public function __construct(iterable $items)
12
    {
13 4
        $this->items = $items instanceof \Traversable ? iterator_to_array($items) : $items;
14 4
        $this->assertType();
15 3
    }
16
17
    public function getItems(): array
18
    {
19
        return $this->items;
20
    }
21
22 1
    public function count(): int
23
    {
24 1
        return count($this->items);
25
    }
26
27
    public function filter(callable $filter): static
28
    {
29
        return new static(array_filter($this->items, $filter));
30
    }
31
32 2
    public function getIterator(): \ArrayIterator
33
    {
34 2
        return new \ArrayIterator($this->items);
35
    }
36
37
    abstract protected function getType(): string;
38
39 4
    private function assertType(): void
40
    {
41 4
        $type = $this->getType();
42
43 4
        foreach ($this->items as $item) {
44 4
            if (!$item instanceof $type) {
45 1
                throw CollectionException::invalidType(get_class($item), $type);
46
            }
47
        }
48 3
    }
49
}
50