|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vox\Webservice; |
|
4
|
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
|
6
|
|
|
use Metadata\MetadataFactoryInterface; |
|
7
|
|
|
use BadMethodCallException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* A object storage using an id hashmap pattern |
|
11
|
|
|
* |
|
12
|
|
|
* @author Jhonatan Teixeira <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class ObjectStorage implements ObjectStorageInterface |
|
15
|
|
|
{ |
|
16
|
|
|
use MetadataTrait; |
|
17
|
|
|
|
|
18
|
|
|
private $storage = []; |
|
19
|
|
|
|
|
20
|
20 |
|
public function __construct(MetadataFactoryInterface $metadataFactory) |
|
21
|
|
|
{ |
|
22
|
20 |
|
$this->metadataFactory = $metadataFactory; |
|
23
|
20 |
|
} |
|
24
|
|
|
|
|
25
|
11 |
|
public function contains($object): bool |
|
26
|
|
|
{ |
|
27
|
11 |
|
return isset($this->storage[get_class($object)][$this->getIdValue($object)]); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
11 |
|
public function attach($object) |
|
31
|
|
|
{ |
|
32
|
11 |
|
$className = get_class($object); |
|
33
|
11 |
|
$id = $this->getIdValue($object); |
|
34
|
|
|
|
|
35
|
11 |
|
if (!$id) { |
|
36
|
|
|
throw new InvalidArgumentException('object has no id value'); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
11 |
|
$this->storage[$className][$id] = $object; |
|
40
|
11 |
|
} |
|
41
|
|
|
|
|
42
|
7 |
|
public function detach($object) |
|
43
|
|
|
{ |
|
44
|
7 |
|
unset($this->storage[get_class($object)][$this->getIdValue($object)]); |
|
45
|
7 |
|
} |
|
46
|
|
|
|
|
47
|
9 |
|
public function getIterator() |
|
48
|
|
|
{ |
|
49
|
9 |
|
$items = []; |
|
50
|
|
|
|
|
51
|
9 |
|
foreach ($this->storage as $transferData) { |
|
52
|
7 |
|
foreach ($transferData as $item) { |
|
53
|
7 |
|
$items[] = $item; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
9 |
|
return new \ArrayIterator($items); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
6 |
|
public function isEquals($object): bool |
|
61
|
|
|
{ |
|
62
|
6 |
|
return $object == $this->storage[get_class($object)][$this->getIdValue($object)]; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param string $className |
|
67
|
|
|
* @param scalar $id |
|
68
|
|
|
* |
|
69
|
|
|
* @return object |
|
70
|
|
|
*/ |
|
71
|
5 |
|
public function fetchByParams(...$params) |
|
72
|
|
|
{ |
|
73
|
5 |
|
if (count($params) != 2) { |
|
74
|
|
|
throw new BadMethodCallException('this method needs two params, $className: string, $id: scalar'); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
5 |
|
$className = (string) $params[0]; |
|
78
|
5 |
|
$id = $params[1]; |
|
79
|
|
|
|
|
80
|
5 |
|
if (!is_scalar($id)) { |
|
81
|
|
|
throw new BadMethodCallException('$id must be scalar value'); |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
5 |
|
return $this->storage[$className][$id] ?? null; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|