Completed
Push — master ( c4c478...afd2dc )
by Daniel
10s
created

CollectionsAgent::findMany()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Bridge\ObjectAgent\Doctrine\Collections;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\Common\Collections\Criteria;
9
use Psi\Component\ObjectAgent\AgentInterface;
10
use Psi\Component\ObjectAgent\Capabilities;
11
use Psi\Component\ObjectAgent\Exception\BadMethodCallException;
12
use Psi\Component\ObjectAgent\Exception\ObjectNotFoundException;
13
use Psi\Component\ObjectAgent\Query\Comparison;
14
use Psi\Component\ObjectAgent\Query\Query;
15
16
class CollectionsAgent implements AgentInterface
17
{
18
    private $store;
19
20
    public function __construct(Store $store)
21
    {
22
        $this->store = $store;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function supports(string $classFqn): bool
29
    {
30
        return $this->store->hasCollection($classFqn);
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 View Code Duplication
    public function getCapabilities(): Capabilities
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
    {
38
        return Capabilities::create([
39
            'can_set_parent' => false,
40
            'can_query_count' => true,
41
            'supported_comparators' => [
42
                Comparison::EQUALS,
43
                Comparison::NOT_EQUALS,
44
                Comparison::LESS_THAN,
45
                Comparison::LESS_THAN_EQUAL,
46
                Comparison::GREATER_THAN,
47
                Comparison::GREATER_THAN_EQUAL,
48
                Comparison::IN,
49
                Comparison::NOT_IN,
50
                Comparison::CONTAINS,
51
                Comparison::NULL,
52
            ],
53
        ]);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 View Code Duplication
    public function find($identifier, string $classFqn = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
60
    {
61
        if (null === $classFqn) {
62
            throw BadMethodCallException::classArgumentIsMandatory(__CLASS__);
63
        }
64
65
        $object = $this->store->find($classFqn, $identifier);
66
67
        if (null === $object) {
68
            throw ObjectNotFoundException::forClassAndIdentifier($classFqn, $identifier);
69
        }
70
71
        return $object;
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function findMany(array $identifiers, string $classFqn = null)
78
    {
79
        $collection = [];
80
        foreach ($identifiers as $identifier) {
81
            $collection[] = $this->find($identifier, $classFqn);
82
        }
83
84
        return new ArrayCollection($collection);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Doctrine\Com...ollection($collection); (Doctrine\Common\Collections\ArrayCollection) is incompatible with the return type declared by the interface Psi\Component\ObjectAgent\AgentInterface::findMany of type object[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function persist($object)
91
    {
92
        // do nothing ...
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function flush()
99
    {
100
        // do nothing ...
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function remove($object)
107
    {
108
        $this->store->remove($object);
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function query(Query $query): \Traversable
115
    {
116
        return $this->doQuery(
117
            $query,
118
            $query->getFirstResult(),
119
            $query->getMaxResults()
120
        );
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function queryCount(Query $query): int
127
    {
128
        return count($this->doQuery($query, 0));
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function getIdentifier($object)
135
    {
136
        foreach ($this->store->getCollection(get_class($object)) as $identifier => $element) {
137
            if ($element === $object) {
138
                return $identifier;
139
            }
140
        }
141
142
        throw new \RuntimeException(sprintf(
143
            'Could not find identifier for object of class "%s"',
144
            get_class($object)
145
        ));
146
    }
147
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function setParent($object, $parent)
152
    {
153
        throw BadMethodCallException::setParentNotSupported(__CLASS__);
154
    }
155
156
    private function doQuery(Query $query, int $firstResult = null, int $maxResults = null)
157
    {
158
        $collection = $this->store->getCollection($query->getClassFqn());
159
160
        $doctrineExpression = null;
161
        if ($query->hasExpression()) {
162
            $expressionBuilder = Criteria::expr();
163
            $visitor = new CollectionsVisitor($expressionBuilder);
164
            $doctrineExpression = $visitor->dispatch($query->getExpression());
165
        }
166
167
        $criteria = new Criteria(
168
            $doctrineExpression,
169
            $query->getOrderings(),
170
            $firstResult,
171
            $maxResults
172
        );
173
174
        return $collection->matching($criteria);
175
    }
176
}
177