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

YamlDriver::addMappingFromReference()   F

Complexity

Conditions 19
Paths > 20000

Size

Total Lines 39
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 19.1185

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 39
ccs 27
cts 29
cp 0.931
rs 2.6972
cc 19
eloc 30
nc 262144
nop 4
crap 19.1185

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Mapping\Driver;
21
22
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
23
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
24
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata as MappingClassMetadata;
25
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
26
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
27
use Symfony\Component\Yaml\Yaml;
28
29
/**
30
 * The YamlDriver reads the mapping metadata from yaml schema files.
31
 *
32
 * @since       1.0
33
 */
34
class YamlDriver extends FileDriver
35
{
36
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
37
38
    /**
39
     * {@inheritDoc}
40
     */
41 9
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
42
    {
43 9
        parent::__construct($locator, $fileExtension);
44 9
    }
45
46
    /**
47
     * {@inheritDoc}
48
     */
49 5
    public function loadMetadataForClass($className, ClassMetadata $class)
50
    {
51
        /* @var $class ClassMetadataInfo */
52 5
        $element = $this->getElement($className);
53 5
        if ( ! $element) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $element of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
54
            return;
55
        }
56 5
        $element['type'] = isset($element['type']) ? $element['type'] : 'document';
57
58 5
        if (isset($element['db'])) {
59 2
            $class->setDatabase($element['db']);
60
        }
61 5
        if (isset($element['collection'])) {
62 5
            $class->setCollection($element['collection']);
63
        }
64 5
        if ($element['type'] == 'document') {
65 5
            if (isset($element['repositoryClass'])) {
66 5
                $class->setCustomRepositoryClass($element['repositoryClass']);
67
            }
68 1 View Code Duplication
        } elseif ($element['type'] === 'mappedSuperclass') {
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...
69
            $class->setCustomRepositoryClass(
70
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
71
            );
72
            $class->isMappedSuperclass = true;
73 1
        } elseif ($element['type'] === 'embeddedDocument') {
74 1
            $class->isEmbeddedDocument = true;
75
        }
76 5
        if (isset($element['indexes'])) {
77 2
            foreach($element['indexes'] as $index) {
78 2
                $class->addIndex($index['keys'], isset($index['options']) ? $index['options'] : array());
79
            }
80
        }
81 5 View Code Duplication
        if (isset($element['inheritanceType'])) {
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...
82
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
83
        }
84 5
        if (isset($element['discriminatorField'])) {
85 1
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
86
        }
87 5
        if (isset($element['discriminatorMap'])) {
88 1
            $class->setDiscriminatorMap($element['discriminatorMap']);
89
        }
90 5
        if (isset($element['defaultDiscriminatorValue'])) {
91 1
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
92
        }
93 5 View Code Duplication
        if (isset($element['changeTrackingPolicy'])) {
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...
94
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
95
        }
96 5
        if (isset($element['requireIndexes'])) {
97
            $class->setRequireIndexes($element['requireIndexes']);
98
        }
99 5
        if (isset($element['slaveOkay'])) {
100
            $class->setSlaveOkay($element['slaveOkay']);
101
        }
102 5
        if (isset($element['fields'])) {
103 5
            foreach ($element['fields'] as $fieldName => $mapping) {
104 5
                if (is_string($mapping)) {
105 1
                    $type = $mapping;
106 1
                    $mapping = array();
107 1
                    $mapping['type'] = $type;
108
                }
109 5
                if ( ! isset($mapping['fieldName'])) {
110 4
                    $mapping['fieldName'] = $fieldName;
111
                }
112 5
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
113 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
114 5
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
115 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
116
                } else {
117 5
                    $this->addFieldMapping($class, $mapping);
118
                }
119
            }
120
        }
121 5 View Code Duplication
        if (isset($element['embedOne'])) {
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...
122 2
            foreach ($element['embedOne'] as $fieldName => $embed) {
123 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
124
            }
125
        }
126 5 View Code Duplication
        if (isset($element['embedMany'])) {
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...
127 2
            foreach ($element['embedMany'] as $fieldName => $embed) {
128 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
129
            }
130
        }
131 5 View Code Duplication
        if (isset($element['referenceOne'])) {
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 2
            foreach ($element['referenceOne'] as $fieldName => $reference) {
133 2
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
134
            }
135
        }
136 5 View Code Duplication
        if (isset($element['referenceMany'])) {
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...
137 2
            foreach ($element['referenceMany'] as $fieldName => $reference) {
138 2
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
139
            }
140
        }
141 5
        if (isset($element['lifecycleCallbacks'])) {
142 2
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
143 2
                foreach ($methods as $method) {
144 2
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
145
                }
146
            }
147
        }
148 5
        if (isset($element['alsoLoadMethods'])) {
149 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
150 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
151
            }
152
        }
153 5
    }
154
155 5
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
156
    {
157 5 View Code Duplication
        if (isset($mapping['name'])) {
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...
158 1
            $name = $mapping['name'];
159 5
        } elseif (isset($mapping['fieldName'])) {
160 5
            $name = $mapping['fieldName'];
161
        } else {
162
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
163
        }
164
165 5
        $class->mapField($mapping);
166
167 5 View Code Duplication
        if ( ! (isset($mapping['index']) || isset($mapping['unique']) || isset($mapping['sparse']))) {
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...
168 5
            return;
169
        }
170
171
        // Multiple index specifications in one field mapping is ambiguous
172 4
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
173 4
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
174 4
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
175
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
176
        }
177
178
        // Index this field if either "index", "unique", or "sparse" are set
179 4
        $keys = array($name => 'asc');
180
181
        /* The "order" option is only used in the index specification and should
182
         * not be passed along as an index option.
183
         */
184 4
        if (isset($mapping['index']['order'])) {
185 1
            $keys[$name] = $mapping['index']['order'];
186 1
            unset($mapping['index']['order']);
187 4
        } elseif (isset($mapping['unique']['order'])) {
188 1
            $keys[$name] = $mapping['unique']['order'];
189 1
            unset($mapping['unique']['order']);
190 3
        } elseif (isset($mapping['sparse']['order'])) {
191
            $keys[$name] = $mapping['sparse']['order'];
192
            unset($mapping['sparse']['order']);
193
        }
194
195
        /* Initialize $options from any array value among index, unique, and
196
         * sparse. Any boolean values for unique or sparse should be merged into
197
         * the options afterwards to ensure consistent parsing.
198
         */
199 4
        $options = array();
200 4
        $unique = null;
201 4
        $sparse = null;
202
203 4
        if (isset($mapping['index']) && is_array($mapping['index'])) {
204 1
            $options = $mapping['index'];
205
        }
206
207 4 View Code Duplication
        if (isset($mapping['unique'])) {
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...
208 4
            if (is_array($mapping['unique'])) {
209 1
                $options = $mapping['unique'] + array('unique' => true);
210
            } else {
211 3
                $unique = (boolean) $mapping['unique'];
212
            }
213
        }
214
215 4 View Code Duplication
        if (isset($mapping['sparse'])) {
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...
216 3
            if (is_array($mapping['sparse'])) {
217
                $options = $mapping['sparse'] + array('sparse' => true);
218
            } else {
219 3
                $sparse = (boolean) $mapping['sparse'];
220
            }
221
        }
222
223 4
        if (isset($unique)) {
224 3
            $options['unique'] = $unique;
225
        }
226
227 4
        if (isset($sparse)) {
228 3
            $options['sparse'] = $sparse;
229
        }
230
231 4
        $class->addIndex($keys, $options);
232 4
    }
233
234 4
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
235
    {
236 4
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
237
        $mapping = array(
238 4
            'type'           => $type,
239
            'embedded'       => true,
240 4
            'targetDocument' => isset($embed['targetDocument']) ? $embed['targetDocument'] : null,
241 4
            'fieldName'      => $fieldName,
242 4
            'strategy'       => isset($embed['strategy']) ? (string) $embed['strategy'] : $defaultStrategy,
243
        );
244 4
        if (isset($embed['name'])) {
245 1
            $mapping['name'] = $embed['name'];
246
        }
247 4
        if (isset($embed['discriminatorField'])) {
248 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
249
        }
250 4
        if (isset($embed['discriminatorMap'])) {
251 1
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
252
        }
253 4
        if (isset($embed['defaultDiscriminatorValue'])) {
254 1
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
255
        }
256 4
        $this->addFieldMapping($class, $mapping);
257 4
    }
258
259 4
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
260
    {
261 4
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
262
        $mapping = array(
263 4
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : null,
264 4
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
265 4
            'type'             => $type,
266
            'reference'        => true,
267 4
            'simple'           => isset($reference['simple']) ? (boolean) $reference['simple'] : false, // deprecated
268 4
            'storeAs'          => isset($reference['storeAs']) ? (string) $reference['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
269 4
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
270 4
            'fieldName'        => $fieldName,
271 4
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : $defaultStrategy,
272 4
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
273 4
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
274 4
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
275 4
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
276 4
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
277
        );
278 4
        if (isset($reference['name'])) {
279 1
            $mapping['name'] = $reference['name'];
280
        }
281 4
        if (isset($reference['discriminatorField'])) {
282 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
283
        }
284 4
        if (isset($reference['discriminatorMap'])) {
285 1
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
286
        }
287 4
        if (isset($reference['defaultDiscriminatorValue'])) {
288 1
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
289
        }
290 4
        if (isset($reference['sort'])) {
291
            $mapping['sort'] = $reference['sort'];
292
        }
293 4
        if (isset($reference['criteria'])) {
294
            $mapping['criteria'] = $reference['criteria'];
295
        }
296 4
        $this->addFieldMapping($class, $mapping);
297 4
    }
298
299
    /**
300
     * Parses the class or field-level "discriminatorField" option.
301
     *
302
     * If the value is an array, check the "name" option before falling back to
303
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
304
     * a string.
305
     *
306
     * @param array|string $discriminatorField
307
     * @return string
308
     * @throws \InvalidArgumentException if the value is neither a string nor an
309
     *                                   array with a "name" or "fieldName" key.
310
     */
311 1
    private function parseDiscriminatorField($discriminatorField)
312
    {
313 1
        if (is_string($discriminatorField)) {
314 1
            return $discriminatorField;
315
        }
316
317 1
        if ( ! is_array($discriminatorField)) {
318
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
319
        }
320
321 1
        if (isset($discriminatorField['name'])) {
322
            return (string) $discriminatorField['name'];
323
        }
324
325 1
        if (isset($discriminatorField['fieldName'])) {
326 1
            return (string) $discriminatorField['fieldName'];
327
        }
328
329
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
330
    }
331
332
    /**
333
     * {@inheritDoc}
334
     */
335 5
    protected function loadMappingFile($file)
336
    {
337 5
        return Yaml::parse(file_get_contents($file));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Symfony\Componen...e_get_contents($file)); (array|string|stdClass) is incompatible with the return type declared by the abstract method Doctrine\Common\Persiste...Driver::loadMappingFile of type array.

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...
338
    }
339
}
340