1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Daikon\DataStructures; |
4
|
|
|
|
5
|
|
|
use Ds\Map; |
6
|
|
|
|
7
|
|
|
trait TypedMapTrait |
8
|
|
|
{ |
9
|
|
|
private $compositeMap; |
10
|
|
|
|
11
|
|
|
private $itemFqcn; |
12
|
|
|
|
13
|
|
|
public function has(string $key): bool |
14
|
|
|
{ |
15
|
|
|
return $this->compositeMap->hasKey($key); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function get(string $key) |
19
|
|
|
{ |
20
|
|
|
return $this->compositeMap->get($key); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function set($key, $item): self |
24
|
|
|
{ |
25
|
|
|
$this->assertItemType($item); |
26
|
|
|
$copy = clone $this; |
27
|
|
|
$copy->compositeMap->put($key, $item); |
28
|
|
|
return $copy; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function count(): int |
32
|
|
|
{ |
33
|
|
|
return count($this->compositeMap); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function toArray(): array |
37
|
|
|
{ |
38
|
|
|
return $this->compositeMap->toArray(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function isEmpty(): bool |
42
|
|
|
{ |
43
|
|
|
return $this->compositeMap->isEmpty(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function getIterator(): \Iterator |
47
|
|
|
{ |
48
|
|
|
return $this->compositeMap->getIterator(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function getItemFqcn() |
52
|
|
|
{ |
53
|
|
|
return $this->itemFqcn; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function __get(string $key) |
57
|
|
|
{ |
58
|
|
|
return $this->get($key); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function init(array $items, string $itemFqcn) |
|
|
|
|
62
|
|
|
{ |
63
|
|
|
$this->itemFqcn = $itemFqcn; |
64
|
|
|
foreach ($items as $key => $item) { |
65
|
|
|
$this->assertItemKey($key); |
66
|
|
|
$this->assertItemType($item); |
67
|
|
|
} |
68
|
|
|
$this->compositeMap = new Map($items); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
View Code Duplication |
private function assertItemKey($key) |
|
|
|
|
72
|
|
|
{ |
73
|
|
|
if (!is_string($key)) { |
74
|
|
|
throw new \Exception(sprintf( |
75
|
|
|
'Invalid item-key given to %s. Expected string but was given %s', |
76
|
|
|
static::CLASS, |
77
|
|
|
is_object($key) ? get_class($key) : @gettype($key) |
78
|
|
|
)); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
View Code Duplication |
private function assertItemType($item) |
|
|
|
|
83
|
|
|
{ |
84
|
|
|
if (!is_a($item, $this->itemFqcn)) { |
85
|
|
|
throw new \Exception(sprintf( |
86
|
|
|
'Invalid item-type given to %s. Expected %s but was given %s', |
87
|
|
|
static::CLASS, |
88
|
|
|
$this->itemFqcn, |
89
|
|
|
is_object($item) ? get_class($item) : @gettype($item) |
90
|
|
|
)); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
public function __clone() |
95
|
|
|
{ |
96
|
|
|
$this->compositeMap = new Map($this->compositeMap->toArray()); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|