Completed
Pull Request — master (#1448)
by Andreas
11:14 queued 05:13
created

Lookup::fromReference()   C

Complexity

Conditions 9
Paths 14

Size

Total Lines 49
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 49
ccs 0
cts 35
cp 0
rs 5.7446
cc 9
eloc 26
nc 14
nop 1
crap 90
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\Aggregation\Stage;
21
22
use Doctrine\MongoDB\Aggregation\Stage as BaseStage;
23
use Doctrine\ODM\MongoDB\Aggregation\Builder;
24
use Doctrine\ODM\MongoDB\DocumentManager;
25
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
26
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
27
use Doctrine\ODM\MongoDB\Mapping\MappingException;
28
use Doctrine\ODM\MongoDB\Query\Expr;
29
30
/**
31
 * Fluent interface for building aggregation pipelines.
32
 *
33
 * @author alcaeus <[email protected]>
34
 */
35
class Lookup extends BaseStage\Lookup
36
{
37
    /**
38
     * @var DocumentManager
39
     */
40
    private $dm;
41
42
    /**
43
     * @var ClassMetadata
44
     */
45
    private $class;
46
47
    /**
48
     * @var ClassMetadata
49
     */
50
    private $targetClass;
51
52
    /**
53
     * @param Builder $builder
54
     * @param string $from
55
     * @param DocumentManager $documentManager
56
     * @param ClassMetadata $class
57
     */
58
    public function __construct(Builder $builder, $from, DocumentManager $documentManager, ClassMetadata $class)
59
    {
60
        $this->dm = $documentManager;
61
        $this->class = $class;
62
        
63
        parent::__construct($builder, $from);
64
    }
65
66
    /**
67
     * @param string $from
68
     * @return $this
69
     */
70
    public function from($from)
71
    {
72
        // $from can either be
73
        // a) a field name indicating a reference to a different document. Currently, only REFERENCE_STORE_AS_ID is supported
74
        // b) a Class name
75
        // c) a collection name
76
        // In cases b) and c) the local and foreign fields need to be filled
77
        if ($this->class->hasReference($from)) {
78
            return $this->fromReference($from);
79
        } else {
80
            return parent::from($from); // TODO: Change the autogenerated stub
81
        }
82
    }
83
84
    /**
85
     * @param string $fieldName
86
     * @return $this
87
     * @throws MappingException
88
     */
89
    private function fromReference($fieldName)
90
    {
91
        if (! $this->class->hasReference($fieldName)) {
92
            MappingException::referenceMappingNotFound($this->class->name, $fieldName);
93
        }
94
95
        $referenceMapping = $this->class->getFieldMapping($fieldName);
96
        if ($referenceMapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
97
            // TODO: Change exception
98
            throw new \InvalidArgumentException('Can\'t use non-ID references in lookup stages yet.');
99
        }
100
101
        if (isset($mapping['repositoryMethod'])) {
0 ignored issues
show
Bug introduced by
The variable $mapping does not exist. Did you mean $referenceMapping?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
102
            // TODO: Use proper exception
103
            throw new \InvalidArgumentException('Can\'t use inverse references with repositoryMethod in lookup stages.');
104
        }
105
106
        if ($mapping['isOwningSide'] && $mapping['association'] === ClassMetadataInfo::REFERENCE_MANY) {
0 ignored issues
show
Bug introduced by
The variable $mapping does not exist. Did you mean $referenceMapping?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
107
            // TODO: throw exception here? This would work if users used an unwind stage before
108
            throw new \InvalidArgumentException('Can\'t use owning many references in lookup stages.');
109
        }
110
111
        // Get target mapping
112
        if (empty($mapping['targetDocument'])) {
0 ignored issues
show
Bug introduced by
The variable $mapping does not exist. Did you mean $referenceMapping?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
113
            // TODO: Use proper exception
114
            throw new \InvalidArgumentException('References must have a target document to be used in lookup stages');
115
        }
116
117
        $targetMapping = $this->dm->getClassMetadata($mapping['targetDocument']);
118
        if ($targetMapping->isInheritanceTypeCollectionPerClass()) {
119
            // TODO: Use proper exception
120
            throw new \InvalidArgumentException();
121
        }
122
123
        $this->from($targetMapping->getCollection());
124
125
        if ($mapping['isOwningSide']) {
126
            $this
127
                ->foreignField('_id')
128
                ->localField($fieldName);
129
        } else {
130
            $mappedByMapping = $targetMapping->getFieldMapping($mapping['mappedBy']);
131
            $this
132
                ->localField('_id')
133
                ->foreignField($mappedByMapping['fieldName']);
134
        }
135
136
        return $this;
137
    }
138
}
139