Completed
Pull Request — master (#1668)
by Andreas
04:58
created

YamlDriver::addFieldMapping()   F

Complexity

Conditions 21
Paths 581

Size

Total Lines 78
Code Lines 44

Duplication

Lines 24
Ratio 30.77 %

Code Coverage

Tests 37
CRAP Score 21.743

Importance

Changes 0
Metric Value
dl 24
loc 78
ccs 37
cts 42
cp 0.881
rs 2.6858
c 0
b 0
f 0
cc 21
eloc 44
nc 581
nop 2
crap 21.743

How to fix   Long Method    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
use Symfony\Component\Yaml\Exception\ParseException;
29
30
/**
31
 * The YamlDriver reads the mapping metadata from yaml schema files.
32
 *
33
 * @since       1.0
34
 */
35
class YamlDriver extends FileDriver
36
{
37
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
38
39
    /**
40
     * {@inheritDoc}
41
     */
42 14
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
43
    {
44 14
        parent::__construct($locator, $fileExtension);
45 14
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50 10
    public function loadMetadataForClass($className, ClassMetadata $class)
51
    {
52
        /* @var $class ClassMetadataInfo */
53 10
        $element = $this->getElement($className);
54 10
        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...
55
            return;
56
        }
57 10
        $element['type'] = isset($element['type']) ? $element['type'] : 'document';
58
59 10
        if (isset($element['db'])) {
60 3
            $class->setDatabase($element['db']);
61
        }
62 10
        if (isset($element['collection'])) {
63 10
            $class->setCollection($element['collection']);
64
        }
65 10
        if (isset($element['readPreference'])) {
66 2
            if (! isset($element['readPreference']['mode'])) {
67
                throw new \InvalidArgumentException('"mode" is a required key for the readPreference setting.');
68
            }
69 2
            $class->setReadPreference(
70 2
                $element['readPreference']['mode'],
71 2
                isset($element['readPreference']['tagSets']) ? $element['readPreference']['tagSets'] : null
72
            );
73
        }
74 10
        if (isset($element['writeConcern'])) {
75 2
            $class->setWriteConcern($element['writeConcern']);
76
        }
77 10
        if ($element['type'] == 'document') {
78 10
            if (isset($element['repositoryClass'])) {
79 10
                $class->setCustomRepositoryClass($element['repositoryClass']);
80
            }
81 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...
82
            $class->setCustomRepositoryClass(
83
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
84
            );
85
            $class->isMappedSuperclass = true;
86 1
        } elseif ($element['type'] === 'embeddedDocument') {
87 1
            $class->isEmbeddedDocument = true;
88 1
        } elseif ($element['type'] === 'queryResultDocument') {
89 1
            $class->isQueryResultDocument = true;
90
        }
91 10
        if (isset($element['indexes'])) {
92 3
            foreach($element['indexes'] as $index) {
93 3
                $class->addIndex($index['keys'], isset($index['options']) ? $index['options'] : array());
94
            }
95
        }
96 10
        if (isset($element['shardKey'])) {
97 2
            $this->setShardKey($class, $element['shardKey']);
98
        }
99 10 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...
100
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
101
        }
102 10
        if (isset($element['discriminatorField'])) {
103 2
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
104
        }
105 10
        if (isset($element['discriminatorMap'])) {
106 2
            $class->setDiscriminatorMap($element['discriminatorMap']);
107
        }
108 10
        if (isset($element['defaultDiscriminatorValue'])) {
109 2
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
110
        }
111 10 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...
112
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
113
        }
114 10
        if (isset($element['slaveOkay'])) {
115
            $class->setSlaveOkay($element['slaveOkay']);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Map...ataInfo::setSlaveOkay() has been deprecated with message: in version 1.2 and will be removed in 2.0.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
116
        }
117 10
        if (! empty($element['readOnly'])) {
118 2
            $class->markReadOnly();
119
        }
120 10
        if (isset($element['fields'])) {
121 10
            foreach ($element['fields'] as $fieldName => $mapping) {
122 10
                if (is_string($mapping)) {
123 1
                    $type = $mapping;
124 1
                    $mapping = array();
125 1
                    $mapping['type'] = $type;
126
                }
127 10
                if ( ! isset($mapping['fieldName'])) {
128 8
                    $mapping['fieldName'] = $fieldName;
129
                }
130 10
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
131 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
132 10
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
133 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
134
                } else {
135 10
                    $this->addFieldMapping($class, $mapping);
136
                }
137
            }
138
        }
139 10 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...
140 3
            foreach ($element['embedOne'] as $fieldName => $embed) {
141 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
142
            }
143
        }
144 10 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...
145 3
            foreach ($element['embedMany'] as $fieldName => $embed) {
146 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
147
            }
148
        }
149 10 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...
150 3
            foreach ($element['referenceOne'] as $fieldName => $reference) {
151 3
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
152
            }
153
        }
154 10 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...
155 4
            foreach ($element['referenceMany'] as $fieldName => $reference) {
156 4
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
157
            }
158
        }
159 10
        if (isset($element['lifecycleCallbacks'])) {
160 3
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
161 3
                foreach ($methods as $method) {
162 3
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
163
                }
164
            }
165
        }
166 10
        if (isset($element['alsoLoadMethods'])) {
167 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
168 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
169
            }
170
        }
171 10
    }
172
173 10
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
174
    {
175 10 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...
176 2
            $name = $mapping['name'];
177 10
        } elseif (isset($mapping['fieldName'])) {
178 10
            $name = $mapping['fieldName'];
179
        } else {
180
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
181
        }
182
183 10
        $class->mapField($mapping);
184
185 10 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...
186 10
            return;
187
        }
188
189
        // Multiple index specifications in one field mapping is ambiguous
190 5
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
191 5
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
192 5
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
193
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
194
        }
195
196
        // Index this field if either "index", "unique", or "sparse" are set
197 5
        $keys = array($name => 'asc');
198
199
        /* The "order" option is only used in the index specification and should
200
         * not be passed along as an index option.
201
         */
202 5
        if (isset($mapping['index']['order'])) {
203 2
            $keys[$name] = $mapping['index']['order'];
204 2
            unset($mapping['index']['order']);
205 5
        } elseif (isset($mapping['unique']['order'])) {
206 2
            $keys[$name] = $mapping['unique']['order'];
207 2
            unset($mapping['unique']['order']);
208 3
        } elseif (isset($mapping['sparse']['order'])) {
209
            $keys[$name] = $mapping['sparse']['order'];
210
            unset($mapping['sparse']['order']);
211
        }
212
213
        /* Initialize $options from any array value among index, unique, and
214
         * sparse. Any boolean values for unique or sparse should be merged into
215
         * the options afterwards to ensure consistent parsing.
216
         */
217 5
        $options = array();
218 5
        $unique = null;
219 5
        $sparse = null;
220
221 5
        if (isset($mapping['index']) && is_array($mapping['index'])) {
222 2
            $options = $mapping['index'];
223
        }
224
225 5 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...
226 5
            if (is_array($mapping['unique'])) {
227 2
                $options = $mapping['unique'] + array('unique' => true);
228
            } else {
229 3
                $unique = (boolean) $mapping['unique'];
230
            }
231
        }
232
233 5 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...
234 3
            if (is_array($mapping['sparse'])) {
235
                $options = $mapping['sparse'] + array('sparse' => true);
236
            } else {
237 3
                $sparse = (boolean) $mapping['sparse'];
238
            }
239
        }
240
241 5
        if (isset($unique)) {
242 3
            $options['unique'] = $unique;
243
        }
244
245 5
        if (isset($sparse)) {
246 3
            $options['sparse'] = $sparse;
247
        }
248
249 5
        $class->addIndex($keys, $options);
250 5
    }
251
252 5
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
253
    {
254 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
255
        $mapping = array(
256 5
            'type'            => $type,
257
            'embedded'        => true,
258 5
            'targetDocument'  => isset($embed['targetDocument']) ? $embed['targetDocument'] : null,
259 5
            'collectionClass' => isset($embed['collectionClass']) ? $embed['collectionClass'] : null,
260 5
            'fieldName'       => $fieldName,
261 5
            'strategy'        => isset($embed['strategy']) ? (string) $embed['strategy'] : $defaultStrategy,
262
        );
263 5
        if (isset($embed['name'])) {
264 2
            $mapping['name'] = $embed['name'];
265
        }
266 5
        if (isset($embed['discriminatorField'])) {
267 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
268
        }
269 5
        if (isset($embed['discriminatorMap'])) {
270 2
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
271
        }
272 5
        if (isset($embed['defaultDiscriminatorValue'])) {
273 2
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
274
        }
275 5
        $this->addFieldMapping($class, $mapping);
276 5
    }
277
278 6
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
279
    {
280 6
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
281
        $mapping = array(
282 6
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : [],
283 6
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
284 6
            'type'             => $type,
285
            'reference'        => true,
286 6
            'storeAs'          => isset($reference['storeAs']) ? (string) $reference['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF,
287 6
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
288 6
            'collectionClass'  => isset($reference['collectionClass']) ? $reference['collectionClass'] : null,
289 6
            'fieldName'        => $fieldName,
290 6
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : $defaultStrategy,
291 6
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
292 6
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
293 6
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
294 6
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
295 6
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
296 6
            'prime'            => isset($reference['prime']) ? $reference['prime'] : [],
297
        );
298 6
        if (isset($reference['name'])) {
299 2
            $mapping['name'] = $reference['name'];
300
        }
301 6
        if (isset($reference['discriminatorField'])) {
302 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
303
        }
304 6
        if (isset($reference['discriminatorMap'])) {
305 2
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
306
        }
307 6
        if (isset($reference['defaultDiscriminatorValue'])) {
308 2
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
309
        }
310 6
        if (isset($reference['sort'])) {
311
            $mapping['sort'] = $reference['sort'];
312
        }
313 6
        if (isset($reference['criteria'])) {
314
            $mapping['criteria'] = $reference['criteria'];
315
        }
316 6
        $this->addFieldMapping($class, $mapping);
317 6
    }
318
319
    /**
320
     * Parses the class or field-level "discriminatorField" option.
321
     *
322
     * If the value is an array, check the "name" option before falling back to
323
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
324
     * a string.
325
     *
326
     * @param array|string $discriminatorField
327
     * @return string
328
     * @throws \InvalidArgumentException if the value is neither a string nor an
329
     *                                   array with a "name" or "fieldName" key.
330
     */
331 2
    private function parseDiscriminatorField($discriminatorField)
332
    {
333 2
        if (is_string($discriminatorField)) {
334 2
            return $discriminatorField;
335
        }
336
337 2
        if ( ! is_array($discriminatorField)) {
338
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
339
        }
340
341 2
        if (isset($discriminatorField['name'])) {
342
            return (string) $discriminatorField['name'];
343
        }
344
345 2
        if (isset($discriminatorField['fieldName'])) {
346 2
            return (string) $discriminatorField['fieldName'];
347
        }
348
349
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
350
    }
351
352
    /**
353
     * {@inheritDoc}
354
     */
355 10
    protected function loadMappingFile($file)
356
    {
357
        try {
358 10
            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)); (null|Symfony\Component\Y...e|string|array|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...
359
        }
360
        catch (ParseException $e) {
361
            $e->setParsedFile($file);
362
            throw $e;
363
        }
364
    }
365
366 2
    private function setShardKey(ClassMetadataInfo $class, array $shardKey)
367
    {
368 2
        $keys = $shardKey['keys'];
369 2
        $options = array();
370
371 2
        if (isset($shardKey['options'])) {
372 2
            $allowed = array('unique', 'numInitialChunks');
373 2
            foreach ($shardKey['options'] as $name => $value) {
374 2
                if ( ! in_array($name, $allowed, true)) {
375
                    continue;
376
                }
377 2
                $options[$name] = $value;
378
            }
379
        }
380
381 2
        $class->setShardKey($keys, $options);
382 2
    }
383
}
384