Completed
Pull Request — master (#1410)
by Piotr
09:50
created

Expr   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 167
Duplicated Lines 20.96 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 92.31%

Importance

Changes 6
Bugs 0 Features 2
Metric Value
wmc 26
c 6
b 0
f 2
lcom 1
cbo 6
dl 35
loc 167
ccs 60
cts 65
cp 0.9231
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setClassMetadata() 0 4 1
A getQuery() 0 6 1
A getNewObj() 0 6 1
C getReferenceMapping() 0 26 8
C references() 17 31 7
C includesReferenceTo() 18 31 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 223
    public function __construct(DocumentManager $dm)
52
    {
53 223
        $this->dm = $dm;
54 223
    }
55
56
    /**
57
     * Sets ClassMetadata for document being queried.
58
     *
59
     * @param ClassMetadata $class
60
     */
61 221
    public function setClassMetadata(ClassMetadata $class)
62
    {
63 221
        $this->class = $class;
64 221
    }
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 13
    public function references($document)
73
    {
74 13
        if ($this->currentField) {
75 13
            $mapping = $this->getReferenceMapping();
76 11
            $dbRef = $this->dm->createDBRef($document, $mapping);
77 11
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
78
79 11 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 8
                $keys = array('ref' => true, 'id' => true, 'db' => true);
83
84 8
                if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
85 3
                    unset($keys['db']);
86
                }
87
88 8
                if (isset($mapping['targetDocument'])) {
89 4
                    unset($keys['ref'], $keys['db']);
90
                }
91
92 8
                foreach ($keys as $key => $value) {
93 11
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
94
                }
95
            }
96
        } else {
97
            $dbRef = $this->dm->createDBRef($document);
98
            $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...
99
        }
100
101 11
        return $this;
102
    }
103
104
    /**
105
     * Checks that the current field includes a reference to the supplied document.
106
     *
107
     * @param object $document
108
     * @return Expr
109
     */
110 7
    public function includesReferenceTo($document)
111
    {
112 7
        if ($this->currentField) {
113 7
            $mapping = $this->getReferenceMapping();
114 5
            $dbRef = $this->dm->createDBRef($document, $mapping);
115 5
            $storeAs = array_key_exists('storeAs', $mapping) ? $mapping['storeAs'] : null;
116
117 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...
118 3
                $this->query[$mapping['name']] = $dbRef;
119
            } else {
120 4
                $keys = array('ref' => true, 'id' => true, 'db' => true);
121
122 4
                if ($storeAs === ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF) {
123 2
                    unset($keys['db']);
124
                }
125
126 4
                if (isset($mapping['targetDocument'])) {
127 2
                    unset($keys['ref'], $keys['db']);
128
                }
129
130 4
                foreach ($keys as $key => $value) {
131 5
                    $this->query[$this->currentField]['$elemMatch']['$' . $key] = $dbRef['$' . $key];
132
                }
133
            }
134
        } else {
135
            $dbRef = $this->dm->createDBRef($document);
136
            $this->query['$elemMatch'] = $dbRef;
137
        }
138
139 5
        return $this;
140
    }
141
142
    /**
143
     * Gets prepared query part of expression.
144
     *
145
     * @return array
146
     */
147 209
    public function getQuery()
148
    {
149 209
        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...
150 209
            ->getDocumentPersister($this->class->name)
151 209
            ->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...
152
    }
153
154
    /**
155
     * Gets prepared newObj part of expression.
156
     *
157
     * @return array
158
     */
159 191
    public function getNewObj()
160
    {
161 191
        return $this->dm->getUnitOfWork()
162 191
            ->getDocumentPersister($this->class->name)
163 191
            ->prepareQueryOrNewObj($this->newObj);
164
    }
165
166
    /**
167
     * Gets reference mapping for current field from current class or its descendants.
168
     *
169
     * @return array
170
     * @throws MappingException
171
     */
172 20
    private function getReferenceMapping()
173
    {
174 20
        $mapping = null;
175
        try {
176 20
            $mapping = $this->class->getFieldMapping($this->currentField);
177 6
        } catch (MappingException $e) {
178 6
            if (empty($this->class->discriminatorMap)) {
179
                throw $e;
180
            }
181 6
            $foundIn = null;
182 6
            foreach ($this->class->discriminatorMap as $child) {
183 6
                $childClass = $this->dm->getClassMetadata($child);
184 6
                if ($childClass->hasAssociation($this->currentField)) {
185 4
                    if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
186 2
                        throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
187
                    }
188 4
                    $mapping = $childClass->getFieldMapping($this->currentField);
189 6
                    $foundIn = $childClass;
190
                }
191
            }
192 4
            if ($mapping === null) {
193 2
                throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
194
            }
195
        }
196 16
        return $mapping;
197
    }
198
}
199