Completed
Pull Request — master (#1333)
by Maciej
10:44
created

Expr::includesReferenceTo()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 11
Ratio 42.31 %

Code Coverage

Tests 16
CRAP Score 6.0494
Metric Value
dl 11
loc 26
ccs 16
cts 18
cp 0.8889
rs 8.439
cc 6
eloc 16
nc 4
nop 1
crap 6.0494
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 214
    public function __construct(DocumentManager $dm)
49
    {
50 214
        $this->dm = $dm;
51 214
    }
52
53 212
    public function setClassMetadata(ClassMetadata $class)
54
    {
55 212
        $this->class = $class;
56 212
    }
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 = null;
65
            try {
66 10
                $mapping = $this->class->getFieldMapping($this->currentField);
67 10
            } catch (MappingException $e) {
68 3
                if (empty($this->class->discriminatorMap)) {
69
                    throw $e;
70
                }
71 3
                $foundIn = null;
72 3
                foreach ($this->class->discriminatorMap as $child) {
73 3
                    $childClass = $this->dm->getClassMetadata($child);
74 3
                    if ($childClass->hasAssociation($this->currentField)) {
75 2
                        if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
76 1
                            throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
77
                        }
78 2
                        $mapping = $childClass->getFieldMapping($this->currentField);
79 2
                        $foundIn = $childClass;
80 2
                    }
81 3
                }
82 2
                if ($mapping === null) {
83 1
                    throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
84
                }
85
            }
86 8
            $dbRef = $this->dm->createDBRef($document, $mapping);
87
88 8
            if (isset($mapping['simple']) && $mapping['simple']) {
89 4
                $this->query[$mapping['name']] = $dbRef;
90 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...
91 6
                $keys = array('ref' => true, 'id' => true, 'db' => true);
92
93 6
                if (isset($mapping['targetDocument'])) {
94 4
                    unset($keys['ref'], $keys['db']);
95 4
                }
96
97 6
                foreach ($keys as $key => $value) {
98 6
                    $this->query[$this->currentField . '.$' . $key] = $dbRef['$' . $key];
99 6
                }
100
            }
101 8
        } else {
102
            $dbRef = $this->dm->createDBRef($document);
103
            $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...
104
        }
105
106 8
        return $this;
107
    }
108
109
    /**
110
     * Checks that the current field includes a reference to the supplied document.
111
     */
112 2
    public function includesReferenceTo($document)
113
    {
114 2
        if ($this->currentField) {
115 2
            $mapping = $this->class->getFieldMapping($this->currentField);
116 2
            $dbRef = $this->dm->createDBRef($document, $mapping);
117
118 2
            if (isset($mapping['simple']) && $mapping['simple']) {
119 1
                $this->query[$mapping['name']]['$elemMatch'] = $dbRef;
120 1 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...
121 2
                $keys = array('ref' => true, 'id' => true, 'db' => true);
122
123 2
                if (isset($mapping['targetDocument'])) {
124 1
                    unset($keys['ref'], $keys['db']);
125 1
                }
126
127 2
                foreach ($keys as $key => $value) {
128 2
                    $this->query[$this->currentField]['$elemMatch']['$' . $key] = $dbRef['$' . $key];
129 2
                }
130
            }
131 2
        } else {
132
            $dbRef = $this->dm->createDBRef($document);
133
            $this->query['$elemMatch'] = $dbRef;
134
        }
135
136 2
        return $this;
137
    }
138
139 202
    public function getQuery()
140
    {
141 202
        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...
142 202
            ->getDocumentPersister($this->class->name)
143 202
            ->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...
144
    }
145
146 185
    public function getNewObj()
147
    {
148 185
        return $this->dm->getUnitOfWork()
149 185
            ->getDocumentPersister($this->class->name)
150 185
            ->prepareQueryOrNewObj($this->newObj);
151
    }
152
}
153