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

Collection   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 77.78%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 13
c 1
b 0
f 0
dl 0
loc 40
ccs 14
cts 18
cp 0.7778
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A filter() 0 3 1
A getItems() 0 3 1
A getIterator() 0 3 1
A count() 0 3 1
A __construct() 0 4 2
A assertType() 0 8 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 new \InvalidArgumentException(
46 1
                    sprintf('The object %s is not an instance of %s', get_class($item), $type),
47
                );
48
            }
49
        }
50
    }
51
}