Completed
Pull Request — master (#1448)
by Andreas
10:20
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 13
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
43
    {
44 13
        parent::__construct($locator, $fileExtension);
45 13
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50 9
    public function loadMetadataForClass($className, ClassMetadata $class)
51
    {
52
        /* @var $class ClassMetadataInfo */
53 9
        $element = $this->getElement($className);
54 9
        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 9
        $element['type'] = isset($element['type']) ? $element['type'] : 'document';
58
59 9
        if (isset($element['db'])) {
60 2
            $class->setDatabase($element['db']);
61
        }
62 9
        if (isset($element['collection'])) {
63 9
            $class->setCollection($element['collection']);
64
        }
65 9
        if (isset($element['writeConcern'])) {
66 2
            $class->setWriteConcern($element['writeConcern']);
67
        }
68 9
        if ($element['type'] == 'document') {
69 9
            if (isset($element['repositoryClass'])) {
70 9
                $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 9
        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 9
        if (isset($element['shardKey'])) {
88 2
            $this->setShardKey($class, $element['shardKey']);
89
        }
90 9 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 9
        if (isset($element['discriminatorField'])) {
94 2
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
95
        }
96 9
        if (isset($element['discriminatorMap'])) {
97 2
            $class->setDiscriminatorMap($element['discriminatorMap']);
98
        }
99 9
        if (isset($element['defaultDiscriminatorValue'])) {
100 2
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
101
        }
102 9 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 9
        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 9
        if (isset($element['slaveOkay'])) {
109
            $class->setSlaveOkay($element['slaveOkay']);
110
        }
111 9
        if (isset($element['fields'])) {
112 9
            foreach ($element['fields'] as $fieldName => $mapping) {
113 9
                if (is_string($mapping)) {
114 1
                    $type = $mapping;
115 1
                    $mapping = array();
116 1
                    $mapping['type'] = $type;
117
                }
118 9
                if ( ! isset($mapping['fieldName'])) {
119 8
                    $mapping['fieldName'] = $fieldName;
120
                }
121 9
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
122 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
123 9
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
124 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
125
                } else {
126 9
                    $this->addFieldMapping($class, $mapping);
127
                }
128
            }
129
        }
130 9 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 9 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 9 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 9 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 3
            foreach ($element['referenceMany'] as $fieldName => $reference) {
147 3
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
148
            }
149
        }
150 9
        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 9
        if (isset($element['alsoLoadMethods'])) {
158 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
159 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
160
            }
161
        }
162 9
    }
163
164 9
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
165
    {
166 9 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 9
        } elseif (isset($mapping['fieldName'])) {
169 9
            $name = $mapping['fieldName'];
170
        } else {
171
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
172
        }
173
174 9
        $class->mapField($mapping);
175
176 9 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 9
            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 5
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
270
    {
271 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
272
        $mapping = array(
273 5
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : null,
274 5
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
275 5
            'type'             => $type,
276
            'reference'        => true,
277 5
            'simple'           => isset($reference['simple']) ? (boolean) $reference['simple'] : false, // deprecated
278 5
            'storeAs'          => isset($reference['storeAs']) ? (string) $reference['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
279 5
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
280 5
            'collectionClass'  => isset($reference['collectionClass']) ? $reference['collectionClass'] : null,
281 5
            'fieldName'        => $fieldName,
282 5
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : $defaultStrategy,
283 5
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
284 5
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
285 5
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
286 5
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
287 5
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
288
        );
289 5
        if (isset($reference['name'])) {
290 2
            $mapping['name'] = $reference['name'];
291
        }
292 5
        if (isset($reference['discriminatorField'])) {
293 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
294
        }
295 5
        if (isset($reference['discriminatorMap'])) {
296 2
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
297
        }
298 5
        if (isset($reference['defaultDiscriminatorValue'])) {
299 2
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
300
        }
301 5
        if (isset($reference['sort'])) {
302
            $mapping['sort'] = $reference['sort'];
303
        }
304 5
        if (isset($reference['criteria'])) {
305
            $mapping['criteria'] = $reference['criteria'];
306
        }
307 5
        $this->addFieldMapping($class, $mapping);
308 5
    }
309
310
    /**
311
     * Parses the class or field-level "discriminatorField" option.
312
     *
313
     * If the value is an array, check the "name" option before falling back to
314
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
315
     * a string.
316
     *
317
     * @param array|string $discriminatorField
318
     * @return string
319
     * @throws \InvalidArgumentException if the value is neither a string nor an
320
     *                                   array with a "name" or "fieldName" key.
321
     */
322 2
    private function parseDiscriminatorField($discriminatorField)
323
    {
324 2
        if (is_string($discriminatorField)) {
325 2
            return $discriminatorField;
326
        }
327
328 2
        if ( ! is_array($discriminatorField)) {
329
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
330
        }
331
332 2
        if (isset($discriminatorField['name'])) {
333
            return (string) $discriminatorField['name'];
334
        }
335
336 2
        if (isset($discriminatorField['fieldName'])) {
337 2
            return (string) $discriminatorField['fieldName'];
338
        }
339
340
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
341
    }
342
343
    /**
344
     * {@inheritDoc}
345
     */
346 9
    protected function loadMappingFile($file)
347
    {
348
        try {
349 9
            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)); (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...
350
        }
351
        catch (ParseException $e) {
352
            $e->setParsedFile($file);
353
            throw $e;
354
        }
355
    }
356
357 2
    private function setShardKey(ClassMetadataInfo $class, array $shardKey)
358
    {
359 2
        $keys = $shardKey['keys'];
360 2
        $options = array();
361
362 2
        if (isset($shardKey['options'])) {
363 2
            $allowed = array('unique', 'numInitialChunks');
364 2
            foreach ($shardKey['options'] as $name => $value) {
365 2
                if ( ! in_array($name, $allowed, true)) {
366
                    continue;
367
                }
368 2
                $options[$name] = $value;
369
            }
370
        }
371
372 2
        $class->setShardKey($keys, $options);
373 2
    }
374
}
375