|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Shoman4eg\Nalog\Model; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* @author Artem Dubinin <[email protected]> |
|
8
|
|
|
* |
|
9
|
|
|
* @template T |
|
10
|
|
|
* |
|
11
|
|
|
* @template-implements \ArrayAccess<int, T> |
|
12
|
|
|
* @template-implements \Iterator<int, T> |
|
13
|
|
|
*/ |
|
14
|
|
|
abstract class AbstractCollection implements \ArrayAccess, \Countable, \Iterator |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var array<int, T> */ |
|
17
|
|
|
private array $items = []; |
|
18
|
|
|
|
|
19
|
|
|
private int $key; |
|
20
|
|
|
private int $count; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @return null|T |
|
24
|
|
|
*/ |
|
25
|
|
|
public function current() |
|
26
|
|
|
{ |
|
27
|
|
|
return $this->offsetGet($this->key); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function next(): void |
|
31
|
|
|
{ |
|
32
|
|
|
++$this->key; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function key(): ?int |
|
36
|
|
|
{ |
|
37
|
|
|
if (!$this->valid()) { |
|
38
|
|
|
return null; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $this->key; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function valid(): bool |
|
45
|
|
|
{ |
|
46
|
|
|
return $this->key < $this->count; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public function rewind(): void |
|
50
|
|
|
{ |
|
51
|
|
|
$this->key = 0; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function offsetExists($offset): bool |
|
55
|
|
|
{ |
|
56
|
|
|
return isset($this->items[$offset]); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param int $offset |
|
61
|
|
|
* |
|
62
|
|
|
* @return T |
|
63
|
|
|
*/ |
|
64
|
|
|
public function offsetGet($offset) |
|
65
|
|
|
{ |
|
66
|
|
|
if (!$this->offsetExists($offset)) { |
|
67
|
|
|
throw new \RuntimeException(sprintf('Key "%s" does not exist in collection', $offset)); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $this->items[$offset]; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function offsetSet($offset, $value): void |
|
74
|
|
|
{ |
|
75
|
|
|
throw new \RuntimeException('Cannot set value on READ ONLY collection'); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
public function offsetUnset($offset): void |
|
79
|
|
|
{ |
|
80
|
|
|
throw new \RuntimeException('Cannot unset value on READ ONLY collection'); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
public function count(): int |
|
84
|
|
|
{ |
|
85
|
|
|
return $this->count; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
protected function setItems(array $items): void |
|
89
|
|
|
{ |
|
90
|
|
|
if ($this->items !== []) { |
|
91
|
|
|
throw new \LogicException('AbstractCollection::setItems can only be called once.'); |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
$this->items = array_values($items); |
|
95
|
|
|
$this->count = count($items); |
|
96
|
|
|
$this->key = 0; |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|