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

PhpcrOdmAgent::setParent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
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 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...
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 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...
101
    {
102
        $objectFqn = ClassUtils::getRealClass(get_class($object));
103
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
104
        $uuidFieldName = $metadata->getUuidFieldName();
105
106
        if (!$uuidFieldName) {
107
            throw new \RuntimeException(sprintf(
108
                'Document "%s" does not have a UUID-mapped property. All '.
109
                'PHPCR-ODM documents must have a mapped UUID proprety.',
110
                $objectFqn
111
            ));
112
        }
113
114
        $node = $this->documentManager->getNodeForDocument($object);
115
116
        return $node->getIdentifier();
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 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...
123
    {
124
        $objectFqn = ClassUtils::getRealClass(get_class($object));
125
        $metadata = $this->documentManager->getClassMetadata($objectFqn);
126
        $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...
127
128
        if (!$parentField) {
129
            throw new \RuntimeException(sprintf(
130
                'Document "%s" does not have a ParentDocument mapping All '.
131
                'PHPCR-ODM documents must have a mapped parent proprety.',
132
                $objectFqn
133
            ));
134
        }
135
136
        $metadata->setFieldValue($object, $parentField, $parent);
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142 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...
143
    {
144
        $metadataFactory = $this->documentManager->getMetadataFactory();
145
146
        $supports = false;
147
        try {
148
            $metadataFactory->getMetadataFor(ClassUtils::getRealClass($class));
149
            $supports = true;
150
        } catch (MappingException $exception) {
151
            // no metadata - class is not known to phpcr-odm
152
        }
153
154
        return $supports;
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function query(Query $query): \Traversable
161
    {
162
        $sourceAlias = 'a';
163
        $queryBuilder = $this->documentManager->getRepository($query->getClassFqn())->createQueryBuilder($sourceAlias);
164
165
        if ($query->hasExpression()) {
166
            $visitor = new ExpressionVisitor(
167
                $queryBuilder,
168
                $sourceAlias
169
            );
170
171
            $visitor->dispatch($query->getExpression());
172
        }
173
174
        $orderBy = $queryBuilder->orderBy();
175
        foreach ($query->getOrderings() as $field => $order) {
176
            $order = strtolower($order);
177
            $orderBy->{$order}()->field($sourceAlias . '.' .  $field);
178
        }
179
180
        if (null !== $query->getFirstResult()) {
181
            $queryBuilder->setFirstResult($query->getFirstResult());
182
        }
183
184
        if (null !== $query->getMaxResults()) {
185
            $queryBuilder->setMaxResults($query->getMaxResults());
186
        }
187
188
        return $queryBuilder->getQuery()->execute();
189
    }
190
191
    /**
192
     * {@inheritdoc}
193
     */
194
    public function queryCount(Query $query): int
195
    {
196
        throw BadMethodCallException::queryCountNotSupported(__CLASS__);
197
    }
198
199
    /**
200
     * Return the document mangaer instance (for use in events).
201
     */
202
    public function getDocumentManager(): DocumentManagerInterface
203
    {
204
        return $this->documentManager;
205
    }
206
}
207