Completed
Push — master ( 7bfeaf...efad7d )
by Andreas
09:38
created

Expr::getReferenceMapping()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8.013

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
ccs 16
cts 17
cp 0.9412
rs 5.3846
cc 8
eloc 18
nc 5
nop 0
crap 8.013
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 244
    public function __construct(DocumentManager $dm)
52
    {
53 244
        $this->dm = $dm;
54 244
    }
55
56
    /**
57
     * Sets ClassMetadata for document being queried.
58
     *
59
     * @param ClassMetadata $class
60
     */
61 242
    public function setClassMetadata(ClassMetadata $class)
62
    {
63 242
        $this->class = $class;
64 242
    }
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
            $reference = $this->dm->createReference($document, $mapping);
77 12
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
78
79 View Code Duplication
            switch ($storeAs) {
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 12
                case ClassMetadataInfo::REFERENCE_STORE_AS_ID:
81 5
                    $this->query[$mapping['name']] = $reference;
82 5
                    return $this;
83
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
84
85 9
                case ClassMetadataInfo::REFERENCE_STORE_AS_REF:
86
                    $keys = ['id' => true];
87
                    break;
88
89 9
                case ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF:
90 7
                case ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB:
91 9
                    $keys = ['$ref' => true, '$id' => true, '$db' => true];
92
93 9
                    if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
94 3
                        unset($keys['$db']);
95
                    }
96
97 9
                    if (isset($mapping['targetDocument'])) {
98 5
                        unset($keys['$ref'], $keys['$db']);
99
                    }
100 9
                    break;
101
102
                default:
103
                    throw new \InvalidArgumentException("Reference type {$storeAs} is invalid.");
104
            }
105
106 9 View Code Duplication
            foreach ($keys as $key => $value) {
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...
107 9
                $this->query[$mapping['name'] . '.' . $key] = $reference[$key];
108
            }
109 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...
110
            @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...
111
112
            $this->query = $this->dm->createDBRef($document);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->dm->createDBRef($document) 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...
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Doc...tManager::createDBRef() has been deprecated with message: Deprecated in favor of createReference; will be removed in 2.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
113
        }
114
115 9
        return $this;
116
    }
117
118
    /**
119
     * Checks that the current field includes a reference to the supplied document.
120
     *
121
     * @param object $document
122
     * @return Expr
123
     */
124 7
    public function includesReferenceTo($document)
125
    {
126 7
        if ($this->currentField) {
127 7
            $mapping = $this->getReferenceMapping();
128 5
            $reference = $this->dm->createReference($document, $mapping);
129 5
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
130
131 View Code Duplication
            switch ($storeAs) {
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...
132 5
                case ClassMetadataInfo::REFERENCE_STORE_AS_ID:
133 3
                    $this->query[$mapping['name']] = $reference;
134 3
                    return $this;
135
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
136
137 4
                case ClassMetadataInfo::REFERENCE_STORE_AS_REF:
138
                    $keys = ['id' => true];
139
                    break;
140
141 4
                case ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF:
142 3
                case ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB:
143 4
                    $keys = ['$ref' => true, '$id' => true, '$db' => true];
144
145 4
                    if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
146 2
                        unset($keys['$db']);
147
                    }
148
149 4
                    if (isset($mapping['targetDocument'])) {
150 2
                        unset($keys['$ref'], $keys['$db']);
151
                    }
152 4
                    break;
153
154
                default:
155
                    throw new \InvalidArgumentException("Reference type {$storeAs} is invalid.");
156
            }
157
158 4 View Code Duplication
            foreach ($keys as $key => $value) {
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...
159 4
                $this->query[$mapping['name']]['$elemMatch'][$key] = $reference[$key];
160
            }
161 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...
162
            @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...
163
164
            $this->query['$elemMatch'] = $this->dm->createDBRef($document);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Doc...tManager::createDBRef() has been deprecated with message: Deprecated in favor of createReference; will be removed in 2.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
165
        }
166
167 4
        return $this;
168
    }
169
170
    /**
171
     * Gets prepared query part of expression.
172
     *
173
     * @return array
174
     */
175 230
    public function getQuery()
176
    {
177 230
        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...
178 230
            ->getDocumentPersister($this->class->name)
179 230
            ->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...
180
    }
181
182
    /**
183
     * Gets prepared newObj part of expression.
184
     *
185
     * @return array
186
     */
187 205
    public function getNewObj()
188
    {
189 205
        return $this->dm->getUnitOfWork()
190 205
            ->getDocumentPersister($this->class->name)
191 205
            ->prepareQueryOrNewObj($this->newObj, true);
192
    }
193
194
    /**
195
     * Gets reference mapping for current field from current class or its descendants.
196
     *
197
     * @return array
198
     * @throws MappingException
199
     */
200 21
    private function getReferenceMapping()
201
    {
202 21
        $mapping = null;
203
        try {
204 21
            $mapping = $this->class->getFieldMapping($this->currentField);
205 6
        } catch (MappingException $e) {
206 6
            if (empty($this->class->discriminatorMap)) {
207
                throw $e;
208
            }
209 6
            $foundIn = null;
210 6
            foreach ($this->class->discriminatorMap as $child) {
211 6
                $childClass = $this->dm->getClassMetadata($child);
212 6
                if ($childClass->hasAssociation($this->currentField)) {
213 4
                    if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
214 2
                        throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
215
                    }
216 4
                    $mapping = $childClass->getFieldMapping($this->currentField);
217 6
                    $foundIn = $childClass;
218
                }
219
            }
220 4
            if ($mapping === null) {
221 2
                throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
222
            }
223
        }
224 17
        return $mapping;
225
    }
226
}
227