Passed
Pull Request — 1.0.0 (#4)
by
unknown
15:47 queued 06:18
created

StringCollection::rewind()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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