Completed
Pull Request — master (#1623)
by Andreas
09:29
created

Expr::includesReferenceTo()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 37
Code Lines 23

Duplication

Lines 27
Ratio 72.97 %

Code Coverage

Tests 16
CRAP Score 8.512

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 27
loc 37
ccs 16
cts 20
cp 0.8
rs 5.3846
cc 8
eloc 23
nc 13
nop 1
crap 8.512
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 242
    public function __construct(DocumentManager $dm)
52
    {
53 242
        $this->dm = $dm;
54 242
    }
55
56
    /**
57
     * Sets ClassMetadata for document being queried.
58
     *
59
     * @param ClassMetadata $class
60
     */
61 240
    public function setClassMetadata(ClassMetadata $class)
62
    {
63 240
        $this->class = $class;
64 240
    }
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 14
    public function references($document)
73
    {
74 14
        if ($this->currentField) {
75 14
            $mapping = $this->getReferenceMapping();
76 12
            $dbRef = $this->dm->createReference($document, $mapping);
77 12
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
78
79 12 View Code Duplication
            if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
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...
80 5
                $this->query[$mapping['name']] = $dbRef;
81
            } else {
82 9
                if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_REF) {
83
                    $keys = ['id' => true];
84
                } else {
85 9
                    $keys = ['$ref' => true, '$id' => true, '$db' => true];
86
87 9
                    if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
88 3
                        unset($keys['$db']);
89
                    }
90
91 9
                    if (isset($mapping['targetDocument'])) {
92 5
                        unset($keys['$ref'], $keys['$db']);
93
                    }
94
                }
95
96 9
                foreach ($keys as $key => $value) {
97 12
                    $this->query[$mapping['name'] . '.' . $key] = $dbRef[$key];
98
                }
99
            }
100 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...
101
            @trigger_error('Calling ' . __METHOD__ . ' without a current field set will no longer be possible in ODM 2.0.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
102
103
            $dbRef = $this->dm->createReference($document);
0 ignored issues
show
Bug introduced by
The call to createReference() misses a required argument $referenceMapping.

This check looks for function calls that miss required arguments.

Loading history...
104
            $this->query = $dbRef;
105
        }
106
107 12
        return $this;
108
    }
109
110
    /**
111
     * Checks that the current field includes a reference to the supplied document.
112
     *
113
     * @param object $document
114
     * @return Expr
115
     */
116 7
    public function includesReferenceTo($document)
117
    {
118 7
        if ($this->currentField) {
119 7
            $mapping = $this->getReferenceMapping();
120 5
            $dbRef = $this->dm->createReference($document, $mapping);
121 5
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
122
123 5 View Code Duplication
            if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
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
                $this->query[$mapping['name']] = $dbRef;
125
            } else {
126 4
                if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_REF) {
127
                    $keys = ['id' => true];
128
                } else {
129 4
                    $keys = ['$ref' => true, '$id' => true, '$db' => true];
130
131 4
                    if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
132 2
                        unset($keys['$db']);
133
                    }
134
135 4
                    if (isset($mapping['targetDocument'])) {
136 2
                        unset($keys['$ref'], $keys['$db']);
137
                    }
138
                }
139
140 4
                foreach ($keys as $key => $value) {
141 5
                    $this->query[$mapping['name']]['$elemMatch'][$key] = $dbRef[$key];
142
                }
143
            }
144 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...
145
            @trigger_error('Calling ' . __METHOD__ . ' without a current field set will no longer be possible in ODM 2.0.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
146
147
            $dbRef = $this->dm->createReference($document);
0 ignored issues
show
Bug introduced by
The call to createReference() misses a required argument $referenceMapping.

This check looks for function calls that miss required arguments.

Loading history...
148
            $this->query['$elemMatch'] = $dbRef;
149
        }
150
151 5
        return $this;
152
    }
153
154
    /**
155
     * Gets prepared query part of expression.
156
     *
157
     * @return array
158
     */
159 228
    public function getQuery()
160
    {
161 228
        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...
162 228
            ->getDocumentPersister($this->class->name)
163 228
            ->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...
164
    }
165
166
    /**
167
     * Gets prepared newObj part of expression.
168
     *
169
     * @return array
170
     */
171 203
    public function getNewObj()
172
    {
173 203
        return $this->dm->getUnitOfWork()
174 203
            ->getDocumentPersister($this->class->name)
175 203
            ->prepareQueryOrNewObj($this->newObj, true);
176
    }
177
178
    /**
179
     * Gets reference mapping for current field from current class or its descendants.
180
     *
181
     * @return array
182
     * @throws MappingException
183
     */
184 21
    private function getReferenceMapping()
185
    {
186 21
        $mapping = null;
187
        try {
188 21
            $mapping = $this->class->getFieldMapping($this->currentField);
189 6
        } catch (MappingException $e) {
190 6
            if (empty($this->class->discriminatorMap)) {
191
                throw $e;
192
            }
193 6
            $foundIn = null;
194 6
            foreach ($this->class->discriminatorMap as $child) {
195 6
                $childClass = $this->dm->getClassMetadata($child);
196 6
                if ($childClass->hasAssociation($this->currentField)) {
197 4
                    if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
198 2
                        throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
199
                    }
200 4
                    $mapping = $childClass->getFieldMapping($this->currentField);
201 6
                    $foundIn = $childClass;
202
                }
203
            }
204 4
            if ($mapping === null) {
205 2
                throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
206
            }
207
        }
208 17
        return $mapping;
209
    }
210
}
211