Completed
Pull Request — master (#1624)
by Abir
08:47
created

YamlDriver::parseDiscriminatorField()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.675

Importance

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