Repository navigation
Expand file tree
/
Copy pathBaseListCollection.php
More file actions
115 lines (97 loc) · 2.45 KB
/
Copy pathBaseListCollection.php
File metadata and controls
115 lines (97 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types=1);
namespace Inspirum\Arrayable;
use OutOfRangeException;
use function array_map;
use function array_values;
use function count;
use function is_int;
use function sprintf;
/**
* @template TItemKey of array-key
* @template TItemValue
* @template TValue of \Inspirum\Arrayable\Arrayable<TItemKey,TItemValue>
* @implements \Inspirum\Arrayable\ListCollection<TItemKey,TItemValue,TValue>
*/
abstract class BaseListCollection implements ListCollection
{
/**
* @use \Inspirum\Arrayable\CollectionItems<int,TValue>
*/
use CollectionItems;
/**
* @var array<int,TValue>
*/
protected array $items;
/**
* @param array<TValue> $items
*/
public function __construct(array $items = [])
{
$this->items = array_values($items);
}
/**
* @param int|null $offset
* @param TValue $value
*
* @throws \OutOfRangeException
*/
public function offsetSet(mixed $offset, mixed $value): void
{
if ($offset === null) {
$this->offsetAdd($value);
return;
}
if ($this->isOutOfRange($offset)) {
throw new OutOfRangeException(sprintf('List offset must be an integer between 0 and %d', count($this->items)));
}
$this->items[$offset] = $value;
}
/**
* @param TValue $value
*/
public function offsetAdd(mixed $value): void
{
$this->items[] = $value;
}
/**
* @param int $offset
*/
public function offsetUnset(mixed $offset): void
{
unset($this->items[$offset]);
$this->items = array_values($this->items);
}
/**
* @return list<TValue>
*/
public function getItems(): array
{
return array_values($this->items);
}
/**
* @return list<array<TItemKey,TItemValue>>
*/
public function __toArray(): array
{
return array_values(array_map(static fn (Arrayable $item): array => $item->__toArray(), $this->items));
}
/**
* @return list<array<TItemKey,TItemValue>>
*/
final public function toArray(): array
{
return $this->__toArray();
}
/**
* @return list<array<TItemKey,TItemValue>>
*/
final public function jsonSerialize(): array
{
return $this->__toArray();
}
private function isOutOfRange(mixed $offset): bool
{
return !is_int($offset) || $offset < 0 || $offset > count($this->items);
}
}