Passed
Push — master ( dc3f23...55d9e9 )
by Paweł
02:57
created

Collection::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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 new \InvalidArgumentException(
46 1
                    sprintf('The object %s is not an instance of %s', get_class($item), $type),
47
                );
48
            }
49
        }
50
    }
51
}