Passed
Pull Request — main (#8)
by Alex
03:11 queued 01:35
created

AbstractCollection::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 1
eloc 3
c 2
b 0
f 2
nc 1
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
namespace StraTDeS\VO\Collection;
4
5
use ArrayAccess;
6
use Countable;
7
use InvalidArgumentException;
8
use Iterator;
9
10
abstract class AbstractCollection implements Countable, ArrayAccess, Iterator
11
{
12
    protected array $items;
13
    protected int $position;
14
15 30
    protected function __construct()
16
    {
17 30
        $this->items = [];
18 30
        $this->position = 0;
19 30
    }
20
21 30
    public static function create(): AbstractCollection
22
    {
23 30
        return new static();
24
    }
25
26 10
    public function items(): array
27
    {
28 10
        return $this->items;
29
    }
30
31 10
    public function count(): int
32
    {
33 10
        return count($this->items);
34
    }
35
36
    public function offsetExists($offset): bool
37
    {
38
        return isset($this->items[$offset]);
39
    }
40
41 20
    public function offsetGet($offset)
42
    {
43 20
        return $this->items[$offset];
44
    }
45
46 10
    public function offsetSet($offset, $value)
47
    {
48 10
        $this->checkValueIsValidForCollection($value);
49 10
        $this->items[$offset] = $value;
50 10
    }
51
52
    public function offsetUnset($offset)
53
    {
54
        unset($this->items[$offset]);
55
    }
56
57 30
    protected function checkValueIsValidForCollection($value): void
58
    {
59 30
        if (get_class($value) != $this->itemClass() && !is_subclass_of($value, $this->itemClass())) {
60 10
            throw new InvalidArgumentException("Provided value is not a valid {$this->itemClass()}");
61
        }
62 20
    }
63
64 10
    public function current()
65
    {
66 10
        return $this->items[$this->position];
67
    }
68
69 10
    public function next(): void
70
    {
71 10
        $this->position++;
72 10
    }
73
74 10
    public function key(): int
75
    {
76 10
        return $this->position;
77
    }
78
79 10
    public function valid(): bool
80
    {
81 10
        return isset($this->items[$this->position]);
82
    }
83
84 10
    public function rewind(): void
85
    {
86 10
        $this->position = 0;
87 10
    }
88
89 20
    public function add($item): AbstractCollection
90
    {
91 20
        $this->checkValueIsValidForCollection($item);
92
93 10
        $this->items[] = $item;
94
95 10
        return $this;
96
    }
97
98
    abstract protected function itemClass(): string;
99
}
100