Completed
Pull Request — master (#1349)
by
unknown
09:55
created

Expr::includesReferenceTo()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 34
Code Lines 20

Duplication

Lines 17
Ratio 50 %

Code Coverage

Tests 15
CRAP Score 8.2964

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 17
loc 34
ccs 15
cts 18
cp 0.8333
rs 5.3846
cc 8
eloc 20
nc 6
nop 1
crap 8.2964
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ODM\MongoDB\Query;
21
22
use Doctrine\ODM\MongoDB\DocumentManager;
23
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
24
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
25
use Doctrine\ODM\MongoDB\Mapping\MappingException;
26
27
/**
28
 * Query expression builder for ODM.
29
 *
30
 * @since       1.0
31
 */
32
class Expr extends \Doctrine\MongoDB\Query\Expr
33
{
34
    /**
35
     * The DocumentManager instance for this query
36
     *
37
     * @var DocumentManager
38
     */
39
    private $dm;
40
41
    /**
42
     * The ClassMetadata instance for the document being queried
43
     *
44
     * @var ClassMetadata
45
     */
46
    private $class;
47
48
    /**
49
     * @param DocumentManager $dm
50
     */
51 218
    public function __construct(DocumentManager $dm)
52
    {
53 218
        $this->dm = $dm;
54 218
    }
55
56
    /**
57
     * Sets ClassMetadata for document being queried.
58
     *
59
     * @param ClassMetadata $class
60
     */
61 216
    public function setClassMetadata(ClassMetadata $class)
62
    {
63 216
        $this->class = $class;
64 216
    }
65
66
    /**
67
     * Checks that the value of the current field is a reference to the supplied document.
68
     *
69
     * @param object $document
70
     * @return Expr
71
     */
72 10
    public function references($document)
73
    {
74 10
        if ($this->currentField) {
75 10
            $mapping = $this->getReferenceMapping();
76 8
            $dbRef = $this->dm->createDBRef($document, $mapping);
77
78 8
            if (array_key_exists('storeAs', $mapping)
79 8
                && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
80
            ) {
81 4
                $this->query[$mapping['name']] = $dbRef;
82 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
83 6
                $keys = array('ref' => true, 'id' => true, 'db' => true);
84
85 6
                if (array_key_exists('storeAs', $mapping)
86 6
                    && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF
87
                ) {
88
                    unset($keys['db']);
89
                }
90
91 6
                if (isset($mapping['targetDocument'])) {
92 4
                    unset($keys['ref'], $keys['db']);
93
                }
94
95 6
                foreach ($keys as $key => $value) {
96 8
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
97
                }
98
            }
99
        } else {
100
            $dbRef = $this->dm->createDBRef($document);
101
            $this->query = $dbRef;
0 ignored issues
show
Documentation Bug introduced by
It seems like $dbRef of type array is incompatible with the declared type string of property $query.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
102
        }
103
104 8
        return $this;
105
    }
106
107
    /**
108
     * Checks that the current field includes a reference to the supplied document.
109
     *
110
     * @param object $document
111
     * @return Expr
112
     */
113 5
    public function includesReferenceTo($document)
114
    {
115 5
        if ($this->currentField) {
116 5
            $mapping = $this->getReferenceMapping();
117 3
            $dbRef = $this->dm->createDBRef($document, $mapping);
118
119 3
            if (array_key_exists('storeAs', $mapping)
120 3
                && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
121
            ) {
122 2
                $this->query[$mapping['name']]['$elemMatch'] = $dbRef;
123 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
124 3
                $keys = array('ref' => true, 'id' => true, 'db' => true);
125
126 3
                if (array_key_exists('storeAs', $mapping)
127 3
                    && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF
128
                ) {
129
                    unset($keys['db']);
130
                }
131
132 3
                if (isset($mapping['targetDocument'])) {
133 2
                    unset($keys['ref'], $keys['db']);
134
                }
135
136 3
                foreach ($keys as $key => $value) {
137 3
                    $this->query[$this->currentField]['$elemMatch']['$' . $key] = $dbRef['$' . $key];
138
                }
139
            }
140
        } else {
141
            $dbRef = $this->dm->createDBRef($document);
142
            $this->query['$elemMatch'] = $dbRef;
143
        }
144
145 3
        return $this;
146
    }
147
148
    /**
149
     * Gets prepared query part of expression.
150
     *
151
     * @return array
152
     */
153 204
    public function getQuery()
154
    {
155 204
        return $this->dm->getUnitOfWork()
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->dm->getUni...OrNewObj($this->query); (array) is incompatible with the return type of the parent method Doctrine\MongoDB\Query\Expr::getQuery of type string.

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...
156 204
            ->getDocumentPersister($this->class->name)
157 204
            ->prepareQueryOrNewObj($this->query);
0 ignored issues
show
Documentation introduced by
$this->query is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
158
    }
159
160
    /**
161
     * Gets prepared newObj part of expression.
162
     *
163
     * @return array
164
     */
165 187
    public function getNewObj()
166
    {
167 187
        return $this->dm->getUnitOfWork()
168 187
            ->getDocumentPersister($this->class->name)
169 187
            ->prepareQueryOrNewObj($this->newObj);
170
    }
171
172
    /**
173
     * Gets reference mapping for current field from current class or its descendants.
174
     *
175
     * @return array
176
     * @throws MappingException
177
     */
178 15
    private function getReferenceMapping()
179
    {
180 15
        $mapping = null;
181
        try {
182 15
            $mapping = $this->class->getFieldMapping($this->currentField);
183 6
        } catch (MappingException $e) {
184 6
            if (empty($this->class->discriminatorMap)) {
185
                throw $e;
186
            }
187 6
            $foundIn = null;
188 6
            foreach ($this->class->discriminatorMap as $child) {
189 6
                $childClass = $this->dm->getClassMetadata($child);
190 6
                if ($childClass->hasAssociation($this->currentField)) {
191 4
                    if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
192 2
                        throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
193
                    }
194 4
                    $mapping = $childClass->getFieldMapping($this->currentField);
195 6
                    $foundIn = $childClass;
196
                }
197
            }
198 4
            if ($mapping === null) {
199 2
                throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
200
            }
201
        }
202 11
        return $mapping;
203
    }
204
}
205