Completed
Pull Request — master (#1333)
by Maciej
09:34
created

Expr::getReferenceMapping()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8.0093

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 26
ccs 18
cts 19
cp 0.9474
rs 5.3846
cc 8
eloc 18
nc 5
nop 0
crap 8.0093
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\MappingException;
25
26
/**
27
 * Query expression builder for ODM.
28
 *
29
 * @since       1.0
30
 * @author      Jonathan H. Wage <[email protected]>
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 217
    public function __construct(DocumentManager $dm)
49
    {
50 217
        $this->dm = $dm;
51 217
    }
52
53 215
    public function setClassMetadata(ClassMetadata $class)
54
    {
55 215
        $this->class = $class;
56 215
    }
57
58
    /**
59
     * Checks that the value of the current field is a reference to the supplied document.
60
     */
61 10
    public function references($document)
62
    {
63 10
        if ($this->currentField) {
64 10
            $mapping = $this->getReferenceMapping();
65 8
            $dbRef = $this->dm->createDBRef($document, $mapping);
66
67 8
            if (isset($mapping['simple']) && $mapping['simple']) {
68 4
                $this->query[$mapping['name']] = $dbRef;
69 4 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...
70 6
                $keys = array('ref' => true, 'id' => true, 'db' => true);
71
72 6
                if (isset($mapping['targetDocument'])) {
73 4
                    unset($keys['ref'], $keys['db']);
74 4
                }
75
76 6
                foreach ($keys as $key => $value) {
77 6
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
78 6
                }
79
            }
80 8
        } else {
81
            $dbRef = $this->dm->createDBRef($document);
82
            $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...
83
        }
84
85 8
        return $this;
86
    }
87
88
    /**
89
     * Checks that the current field includes a reference to the supplied document.
90
     */
91 5
    public function includesReferenceTo($document)
92
    {
93 5
        if ($this->currentField) {
94 5
            $mapping = $this->getReferenceMapping();
95 3
            $dbRef = $this->dm->createDBRef($document, $mapping);
96
97 3
            if (isset($mapping['simple']) && $mapping['simple']) {
98 2
                $this->query[$mapping['name']]['$elemMatch'] = $dbRef;
99 2 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...
100 3
                $keys = array('ref' => true, 'id' => true, 'db' => true);
101
102 3
                if (isset($mapping['targetDocument'])) {
103 2
                    unset($keys['ref'], $keys['db']);
104 2
                }
105
106 3
                foreach ($keys as $key => $value) {
107 3
                    $this->query[$this->currentField]['$elemMatch']['$' . $key] = $dbRef['$' . $key];
108 3
                }
109
            }
110 3
        } else {
111
            $dbRef = $this->dm->createDBRef($document);
112
            $this->query['$elemMatch'] = $dbRef;
113
        }
114
115 3
        return $this;
116
    }
117
118 203
    public function getQuery()
119
    {
120 203
        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...
121 203
            ->getDocumentPersister($this->class->name)
122 203
            ->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...
123
    }
124
125 186
    public function getNewObj()
126
    {
127 186
        return $this->dm->getUnitOfWork()
128 186
            ->getDocumentPersister($this->class->name)
129 186
            ->prepareQueryOrNewObj($this->newObj);
130
    }
131
132
    /**
133
     * Gets reference mapping for current field from current class or its descendants.
134
     *
135
     * @return array
136
     * @throws MappingException
137
     */
138 15
    private function getReferenceMapping()
139
    {
140 15
        $mapping = null;
141
        try {
142 15
            $mapping = $this->class->getFieldMapping($this->currentField);
143 15
        } catch (MappingException $e) {
144 6
            if (empty($this->class->discriminatorMap)) {
145
                throw $e;
146
            }
147 6
            $foundIn = null;
148 6
            foreach ($this->class->discriminatorMap as $child) {
149 6
                $childClass = $this->dm->getClassMetadata($child);
150 6
                if ($childClass->hasAssociation($this->currentField)) {
151 4
                    if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
152 2
                        throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
153
                    }
154 4
                    $mapping = $childClass->getFieldMapping($this->currentField);
155 4
                    $foundIn = $childClass;
156 4
                }
157 6
            }
158 4
            if ($mapping === null) {
159 2
                throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
160
            }
161
        }
162 11
        return $mapping;
163
    }
164
}
165