Store   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 1
dl 0
loc 69
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A addCollection() 0 13 2
A getCollection() 0 11 2
A hasCollection() 0 4 1
A find() 0 10 2
A getOrCreateCollection() 0 8 2
A remove() 0 6 1
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