1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Oxidmod\TypedCollections\SimpleCollection; |
6
|
|
|
|
7
|
|
|
abstract class AbstractCollection implements \Countable, \IteratorAggregate, \ArrayAccess |
8
|
|
|
{ |
9
|
|
|
private \Closure $typeChecker; |
10
|
|
|
|
11
|
|
|
protected array $items = []; |
12
|
|
|
|
13
|
|
|
public function __construct(\Closure $typeChecker, array $items = []) |
14
|
|
|
{ |
15
|
|
|
$this->typeChecker = $typeChecker; |
16
|
|
|
|
17
|
|
|
foreach ($items as $k => $v) { |
18
|
|
|
$this->assertType($v); |
19
|
|
|
$this->items[$k] = $v; |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getIterator(): \Traversable |
24
|
|
|
{ |
25
|
|
|
return new \ArrayIterator($this->items); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function offsetExists($offset): bool |
29
|
|
|
{ |
30
|
|
|
return array_key_exists($offset, $this->items); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function offsetSet($offset, $value): void |
34
|
|
|
{ |
35
|
|
|
$this->assertType($value); |
36
|
|
|
|
37
|
|
|
null === $offset ? $this->items[] = $value : $this->items[$offset] = $value; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function offsetUnset($offset): void |
41
|
|
|
{ |
42
|
|
|
if (array_key_exists($offset, $this->items)) { |
43
|
|
|
unset($this->items[$offset]); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function count(): int |
48
|
|
|
{ |
49
|
|
|
return count($this->items); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function assertType($value): void |
53
|
|
|
{ |
54
|
|
|
if (!$this->typeChecker->call($this, $value)) { |
55
|
|
|
throw new \InvalidArgumentException( |
56
|
|
|
sprintf('Value of type "%s" is not allowed for "%s"', $this->getValueType($value), static::class) |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function getValueType($value): string |
62
|
|
|
{ |
63
|
|
|
if (is_object($value)) { |
64
|
|
|
return get_class($value); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return gettype($value); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|