Completed
Pull Request — master (#1612)
by Maciej
08:32
created

YamlDriver::loadMappingFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.864

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 2
cts 5
cp 0.4
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2.864
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['writeConcern'])) {
66 2
            $class->setWriteConcern($element['writeConcern']);
67
        }
68 10
        if ($element['type'] == 'document') {
69 10
            if (isset($element['repositoryClass'])) {
70 10
                $class->setCustomRepositoryClass($element['repositoryClass']);
71
            }
72 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...
73
            $class->setCustomRepositoryClass(
74
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
75
            );
76
            $class->isMappedSuperclass = true;
77 1
        } elseif ($element['type'] === 'embeddedDocument') {
78 1
            $class->isEmbeddedDocument = true;
79 1
        } elseif ($element['type'] === 'queryResultDocument') {
80 1
            $class->isQueryResultDocument = true;
81
        }
82 10
        if (isset($element['indexes'])) {
83 3
            foreach($element['indexes'] as $index) {
84 3
                $class->addIndex($index['keys'], isset($index['options']) ? $index['options'] : array());
85
            }
86
        }
87 10
        if (isset($element['shardKey'])) {
88 2
            $this->setShardKey($class, $element['shardKey']);
89
        }
90 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...
91
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
92
        }
93 10
        if (isset($element['discriminatorField'])) {
94 2
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
95
        }
96 10
        if (isset($element['discriminatorMap'])) {
97 2
            $class->setDiscriminatorMap($element['discriminatorMap']);
98
        }
99 10
        if (isset($element['defaultDiscriminatorValue'])) {
100 2
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
101
        }
102 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...
103
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
104
        }
105 10
        if (isset($element['requireIndexes'])) {
106
            $class->setRequireIndexes($element['requireIndexes']);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Map...fo::setRequireIndexes() has been deprecated with message: method was deprecated in 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...
107
        }
108 10
        if (isset($element['slaveOkay'])) {
109
            $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...
110
        }
111 10
        if (! empty($element['readOnly'])) {
112 2
            $class->markReadOnly();
113
        }
114 10
        if (isset($element['fields'])) {
115 10
            foreach ($element['fields'] as $fieldName => $mapping) {
116 10
                if (is_string($mapping)) {
117 1
                    $type = $mapping;
118 1
                    $mapping = array();
119 1
                    $mapping['type'] = $type;
120
                }
121 10
                if ( ! isset($mapping['fieldName'])) {
122 8
                    $mapping['fieldName'] = $fieldName;
123
                }
124 10
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
125 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
126 10
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
127 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
128
                } else {
129 10
                    $this->addFieldMapping($class, $mapping);
130
                }
131
            }
132
        }
133 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...
134 3
            foreach ($element['embedOne'] as $fieldName => $embed) {
135 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
136
            }
137
        }
138 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...
139 3
            foreach ($element['embedMany'] as $fieldName => $embed) {
140 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
141
            }
142
        }
143 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...
144 3
            foreach ($element['referenceOne'] as $fieldName => $reference) {
145 3
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
146
            }
147
        }
148 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...
149 4
            foreach ($element['referenceMany'] as $fieldName => $reference) {
150 4
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
151
            }
152
        }
153 10
        if (isset($element['lifecycleCallbacks'])) {
154 3
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
155 3
                foreach ($methods as $method) {
156 3
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
157
                }
158
            }
159
        }
160 10
        if (isset($element['alsoLoadMethods'])) {
161 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
162 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
163
            }
164
        }
165 10
    }
166
167 10
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
168
    {
169 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...
170 2
            $name = $mapping['name'];
171 10
        } elseif (isset($mapping['fieldName'])) {
172 10
            $name = $mapping['fieldName'];
173
        } else {
174
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
175
        }
176
177 10
        $class->mapField($mapping);
178
179 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...
180 10
            return;
181
        }
182
183
        // Multiple index specifications in one field mapping is ambiguous
184 5
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
185 5
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
186 5
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
187
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
188
        }
189
190
        // Index this field if either "index", "unique", or "sparse" are set
191 5
        $keys = array($name => 'asc');
192
193
        /* The "order" option is only used in the index specification and should
194
         * not be passed along as an index option.
195
         */
196 5
        if (isset($mapping['index']['order'])) {
197 2
            $keys[$name] = $mapping['index']['order'];
198 2
            unset($mapping['index']['order']);
199 5
        } elseif (isset($mapping['unique']['order'])) {
200 2
            $keys[$name] = $mapping['unique']['order'];
201 2
            unset($mapping['unique']['order']);
202 3
        } elseif (isset($mapping['sparse']['order'])) {
203
            $keys[$name] = $mapping['sparse']['order'];
204
            unset($mapping['sparse']['order']);
205
        }
206
207
        /* Initialize $options from any array value among index, unique, and
208
         * sparse. Any boolean values for unique or sparse should be merged into
209
         * the options afterwards to ensure consistent parsing.
210
         */
211 5
        $options = array();
212 5
        $unique = null;
213 5
        $sparse = null;
214
215 5
        if (isset($mapping['index']) && is_array($mapping['index'])) {
216 2
            $options = $mapping['index'];
217
        }
218
219 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...
220 5
            if (is_array($mapping['unique'])) {
221 2
                $options = $mapping['unique'] + array('unique' => true);
222
            } else {
223 3
                $unique = (boolean) $mapping['unique'];
224
            }
225
        }
226
227 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...
228 3
            if (is_array($mapping['sparse'])) {
229
                $options = $mapping['sparse'] + array('sparse' => true);
230
            } else {
231 3
                $sparse = (boolean) $mapping['sparse'];
232
            }
233
        }
234
235 5
        if (isset($unique)) {
236 3
            $options['unique'] = $unique;
237
        }
238
239 5
        if (isset($sparse)) {
240 3
            $options['sparse'] = $sparse;
241
        }
242
243 5
        $class->addIndex($keys, $options);
244 5
    }
245
246 5
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
247
    {
248 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
249
        $mapping = array(
250 5
            'type'            => $type,
251
            'embedded'        => true,
252 5
            'targetDocument'  => isset($embed['targetDocument']) ? $embed['targetDocument'] : null,
253 5
            'collectionClass' => isset($embed['collectionClass']) ? $embed['collectionClass'] : null,
254 5
            'fieldName'       => $fieldName,
255 5
            'strategy'        => isset($embed['strategy']) ? (string) $embed['strategy'] : $defaultStrategy,
256
        );
257 5
        if (isset($embed['name'])) {
258 2
            $mapping['name'] = $embed['name'];
259
        }
260 5
        if (isset($embed['discriminatorField'])) {
261 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
262
        }
263 5
        if (isset($embed['discriminatorMap'])) {
264 2
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
265
        }
266 5
        if (isset($embed['defaultDiscriminatorValue'])) {
267 2
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
268
        }
269 5
        $this->addFieldMapping($class, $mapping);
270 5
    }
271
272 6
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
273
    {
274 6
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
275
        $mapping = array(
276 6
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : [],
277 6
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
278 6
            'type'             => $type,
279
            'reference'        => true,
280 6
            'simple'           => isset($reference['simple']) ? (boolean) $reference['simple'] : false, // deprecated
281 6
            'storeAs'          => isset($reference['storeAs']) ? (string) $reference['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
282 6
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
283 6
            'collectionClass'  => isset($reference['collectionClass']) ? $reference['collectionClass'] : null,
284 6
            'fieldName'        => $fieldName,
285 6
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : $defaultStrategy,
286 6
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
287 6
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
288 6
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
289 6
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
290 6
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
291 6
            'prime'            => isset($reference['prime']) ? $reference['prime'] : [],
292
        );
293 6
        if (isset($reference['name'])) {
294 2
            $mapping['name'] = $reference['name'];
295
        }
296 6
        if (isset($reference['discriminatorField'])) {
297 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
298
        }
299 6
        if (isset($reference['discriminatorMap'])) {
300 2
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
301
        }
302 6
        if (isset($reference['defaultDiscriminatorValue'])) {
303 2
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
304
        }
305 6
        if (isset($reference['sort'])) {
306
            $mapping['sort'] = $reference['sort'];
307
        }
308 6
        if (isset($reference['criteria'])) {
309
            $mapping['criteria'] = $reference['criteria'];
310
        }
311 6
        $this->addFieldMapping($class, $mapping);
312 6
    }
313
314
    /**
315
     * Parses the class or field-level "discriminatorField" option.
316
     *
317
     * If the value is an array, check the "name" option before falling back to
318
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
319
     * a string.
320
     *
321
     * @param array|string $discriminatorField
322
     * @return string
323
     * @throws \InvalidArgumentException if the value is neither a string nor an
324
     *                                   array with a "name" or "fieldName" key.
325
     */
326 2
    private function parseDiscriminatorField($discriminatorField)
327
    {
328 2
        if (is_string($discriminatorField)) {
329 2
            return $discriminatorField;
330
        }
331
332 2
        if ( ! is_array($discriminatorField)) {
333
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
334
        }
335
336 2
        if (isset($discriminatorField['name'])) {
337
            return (string) $discriminatorField['name'];
338
        }
339
340 2
        if (isset($discriminatorField['fieldName'])) {
341 2
            return (string) $discriminatorField['fieldName'];
342
        }
343
344
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
345
    }
346
347
    /**
348
     * {@inheritDoc}
349
     */
350 10
    protected function loadMappingFile($file)
351
    {
352
        try {
353 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...
354
        }
355
        catch (ParseException $e) {
356
            $e->setParsedFile($file);
357
            throw $e;
358
        }
359
    }
360
361 2
    private function setShardKey(ClassMetadataInfo $class, array $shardKey)
362
    {
363 2
        $keys = $shardKey['keys'];
364 2
        $options = array();
365
366 2
        if (isset($shardKey['options'])) {
367 2
            $allowed = array('unique', 'numInitialChunks');
368 2
            foreach ($shardKey['options'] as $name => $value) {
369 2
                if ( ! in_array($name, $allowed, true)) {
370
                    continue;
371
                }
372 2
                $options[$name] = $value;
373
            }
374
        }
375
376 2
        $class->setShardKey($keys, $options);
377 2
    }
378
}
379