Completed
Push — master ( e8e4b5...2e598e )
by Daniel
8s
created

PhpcrOdmAgent::persist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Bridge\ObjectAgent\Doctrine\PhpcrOdm;
6
7
use Doctrine\Common\Persistence\Mapping\MappingException;
8
use Doctrine\Common\Util\ClassUtils;
9
use Doctrine\ODM\PHPCR\DocumentManagerInterface;
10
use Psi\Component\ObjectAgent\AgentInterface;
11
use Psi\Component\ObjectAgent\Capabilities;
12
use Psi\Component\ObjectAgent\Exception\BadMethodCallException;
13
use Psi\Component\ObjectAgent\Exception\ObjectNotFoundException;
14
use Psi\Component\ObjectAgent\Query\Comparison;
15
use Psi\Component\ObjectAgent\Query\Query;
16
17
class PhpcrOdmAgent implements AgentInterface
18
{
19
    private $documentManager;
20
21
    public function __construct(
22
        DocumentManagerInterface $documentManager
23
    ) {
24
        $this->documentManager = $documentManager;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function find($identifier, string $class = null)
31
    {
32
        $object = $this->documentManager->find($class, $identifier);
33
34
        if (null === $object) {
35
            throw ObjectNotFoundException::forClassAndIdentifier($class, $identifier);
36
        }
37
38
        return $object;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function findMany(array $identifiers, string $class = null)
45
    {
46
        return $this->documentManager->findMany($class, $identifiers);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->documentMa...($class, $identifiers); (Doctrine\Common\Collections\Collection) 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...
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function getCapabilities(): Capabilities
53
    {
54
        return Capabilities::create([
55
            'can_set_parent' => true,
56
            'supported_comparators' => [
57
                Comparison::EQUALS,
58
                Comparison::NOT_EQUALS,
59
                Comparison::LESS_THAN,
60
                Comparison::LESS_THAN_EQUAL,
61
                Comparison::GREATER_THAN,
62
                Comparison::GREATER_THAN_EQUAL,
63
                Comparison::IN,
64
                Comparison::NOT_IN,
65
                Comparison::CONTAINS,
66
                Comparison::NOT_CONTAINS,
67
                Comparison::NULL,
68
                Comparison::NOT_NULL,
69
            ],
70
        ]);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function persist($object)
77
    {
78
        $this->documentManager->persist($object);
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function remove($object)
85
    {
86
        $this->documentManager->remove($object);
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function flush()
93
    {
94
        $this->documentManager->flush();
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function getCanonicalClassFqn(string $classFqn): string
101
    {
102
        return ClassUtils::getRealClass($classFqn);
103
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108 View Code Duplication
    public function getIdentifier($object)
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...
109
    {
110
        $objectFqn = ClassUtils::getRealClass(get_class($object));
111
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
112
        $uuidFieldName = $metadata->getUuidFieldName();
113
114
        if (!$uuidFieldName) {
115
            throw new \RuntimeException(sprintf(
116
                'Document "%s" does not have a UUID-mapped property. All '.
117
                'PHPCR-ODM documents must have a mapped UUID proprety.',
118
                $objectFqn
119
            ));
120
        }
121
122
        $node = $this->documentManager->getNodeForDocument($object);
123
124
        return $node->getIdentifier();
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130 View Code Duplication
    public function setParent($object, $parent)
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...
131
    {
132
        $objectFqn = ClassUtils::getRealClass(get_class($object));
133
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
134
        $parentField = $metadata->parentMapping;
0 ignored issues
show
Bug introduced by
Accessing parentMapping on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
135
136
        if (!$parentField) {
137
            throw new \RuntimeException(sprintf(
138
                'Document "%s" does not have a ParentDocument mapping All '.
139
                'PHPCR-ODM documents must have a mapped parent proprety.',
140
                $objectFqn
141
            ));
142
        }
143
144
        $metadata->setFieldValue($object, $parentField, $parent);
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 View Code Duplication
    public function supports(string $class): bool
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...
151
    {
152
        $metadataFactory = $this->documentManager->getMetadataFactory();
153
154
        $supports = false;
155
        try {
156
            $metadataFactory->getMetadataFor(ClassUtils::getRealClass($class));
157
            $supports = true;
158
        } catch (MappingException $exception) {
159
            // no metadata - class is not known to phpcr-odm
160
        }
161
162
        return $supports;
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function query(Query $query): \Traversable
169
    {
170
        $sourceAlias = 'a';
171
        $queryBuilder = $this->documentManager->getRepository($query->getClassFqn())->createQueryBuilder($sourceAlias);
172
173
        if ($query->hasExpression()) {
174
            $visitor = new ExpressionVisitor(
175
                $queryBuilder,
176
                $sourceAlias
177
            );
178
179
            $visitor->dispatch($query->getExpression());
180
        }
181
182
        $orderBy = $queryBuilder->orderBy();
183
        foreach ($query->getOrderings() as $field => $order) {
184
            $order = strtolower($order);
185
            $orderBy->{$order}()->field($sourceAlias . '.' .  $field);
186
        }
187
188
        if (null !== $query->getFirstResult()) {
189
            $queryBuilder->setFirstResult($query->getFirstResult());
190
        }
191
192
        if (null !== $query->getMaxResults()) {
193
            $queryBuilder->setMaxResults($query->getMaxResults());
194
        }
195
196
        return $queryBuilder->getQuery()->execute();
197
    }
198
199
    /**
200
     * {@inheritdoc}
201
     */
202
    public function queryCount(Query $query): int
203
    {
204
        throw BadMethodCallException::queryCountNotSupported(__CLASS__);
205
    }
206
207
    /**
208
     * Return the document mangaer instance (for use in events).
209
     */
210
    public function getDocumentManager(): DocumentManagerInterface
211
    {
212
        return $this->documentManager;
213
    }
214
}
215