1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Psi\Bridge\ObjectAgent\Doctrine\Collections; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
8
|
|
|
|
9
|
|
|
final class Store |
10
|
|
|
{ |
11
|
|
|
private $collections; |
12
|
|
|
|
13
|
|
|
public function __construct(array $collections) |
14
|
|
|
{ |
15
|
|
|
foreach ($collections as $classFqn => $collection) { |
16
|
|
|
$this->addCollection($classFqn, $collection); |
17
|
|
|
} |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function addCollection($classFqn, array $collection) |
21
|
|
|
{ |
22
|
|
|
array_map(function ($object) use ($classFqn) { |
23
|
|
|
if (get_class($object) !== $classFqn) { |
24
|
|
|
throw new \InvalidArgumentException(sprintf( |
25
|
|
|
'All objects in collection must be of class "%s", got "%s"', |
26
|
|
|
$classFqn, get_class($object) |
27
|
|
|
)); |
28
|
|
|
} |
29
|
|
|
}, $collection); |
30
|
|
|
|
31
|
|
|
$this->collections[$classFqn] = new ArrayCollection($collection); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getCollection(string $classFqn): ArrayCollection |
35
|
|
|
{ |
36
|
|
|
if (false === isset($this->collections[$classFqn])) { |
37
|
|
|
throw new \InvalidArgumentException(sprintf( |
38
|
|
|
'No collections available of class "%s"', |
39
|
|
|
$classFqn |
40
|
|
|
)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $this->collections[$classFqn]; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function hasCollection(string $classFqn) |
47
|
|
|
{ |
48
|
|
|
return isset($this->collections[$classFqn]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function find($classFqn, $identifier) |
52
|
|
|
{ |
53
|
|
|
$collection = $this->getCollection($classFqn); |
54
|
|
|
|
55
|
|
|
if (false === isset($collection[$identifier])) { |
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $collection[$identifier]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function remove($object) |
63
|
|
|
{ |
64
|
|
|
$classFqn = get_class($object); |
65
|
|
|
$collection = $this->getCollection($classFqn); |
66
|
|
|
$collection->removeElement($object); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function getOrCreateCollection($classFqn): ArrayCollection |
70
|
|
|
{ |
71
|
|
|
if (!$this->hasCollection($classFqn)) { |
72
|
|
|
$this->collections[$classFqn] = new ArrayCollection(); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $this->getCollection($classFqn); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|