Completed
Pull Request — master (#1716)
by Maciej
10:47
created

YamlDriver::addMappingFromReference()   F

Complexity

Conditions 13
Paths 4096

Size

Total Lines 40
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 13.0501

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 28
cts 30
cp 0.9333
rs 2.7716
c 0
b 0
f 0
cc 13
eloc 31
nc 4096
nop 4
crap 13.0501

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\ODM\MongoDB\Mapping\Driver;
4
5
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
6
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
7
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata as MappingClassMetadata;
8
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
9
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
10
use Symfony\Component\Yaml\Yaml;
11
use Symfony\Component\Yaml\Exception\ParseException;
12
13
/**
14
 * The YamlDriver reads the mapping metadata from yaml schema files.
15
 *
16
 * @since       1.0
17
 */
18
class YamlDriver extends FileDriver
19
{
20
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
21
22
    /**
23
     * {@inheritDoc}
24
     */
25 13
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
26
    {
27 13
        parent::__construct($locator, $fileExtension);
28 13
    }
29
30
    /**
31
     * {@inheritDoc}
32
     */
33 9
    public function loadMetadataForClass($className, ClassMetadata $class)
34
    {
35
        /* @var $class ClassMetadataInfo */
36 9
        $element = $this->getElement($className);
37 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...
38
            return;
39
        }
40 9
        $element['type'] = $element['type'] ?? 'document';
41
42 9
        if (isset($element['db'])) {
43 3
            $class->setDatabase($element['db']);
44
        }
45 9
        if (isset($element['collection'])) {
46 9
            $class->setCollection($element['collection']);
47
        }
48 9
        if (isset($element['readPreference'])) {
49 1
            if (! isset($element['readPreference']['mode'])) {
50
                throw new \InvalidArgumentException('"mode" is a required key for the readPreference setting.');
51
            }
52 1
            $class->setReadPreference(
53 1
                $element['readPreference']['mode'],
54 1
                $element['readPreference']['tagSets'] ?? null
55
            );
56
        }
57 9
        if (isset($element['writeConcern'])) {
58 1
            $class->setWriteConcern($element['writeConcern']);
59
        }
60 9
        if ($element['type'] == 'document') {
61 9
            if (isset($element['repositoryClass'])) {
62 9
                $class->setCustomRepositoryClass($element['repositoryClass']);
63
            }
64 1
        } elseif ($element['type'] === 'mappedSuperclass') {
65
            $class->setCustomRepositoryClass(
66
                $element['repositoryClass'] ?? null
67
            );
68
            $class->isMappedSuperclass = true;
69 1
        } elseif ($element['type'] === 'embeddedDocument') {
70 1
            $class->isEmbeddedDocument = true;
71 1
        } elseif ($element['type'] === 'queryResultDocument') {
72 1
            $class->isQueryResultDocument = true;
73
        }
74 9
        if (isset($element['indexes'])) {
75 2
            foreach($element['indexes'] as $index) {
76 2
                $class->addIndex($index['keys'], $index['options'] ?? array());
77
            }
78
        }
79 9
        if (isset($element['shardKey'])) {
80 1
            $this->setShardKey($class, $element['shardKey']);
81
        }
82 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...
83
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
84
        }
85 9
        if (isset($element['discriminatorField'])) {
86 1
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
87
        }
88 9
        if (isset($element['discriminatorMap'])) {
89 1
            $class->setDiscriminatorMap($element['discriminatorMap']);
90
        }
91 9
        if (isset($element['defaultDiscriminatorValue'])) {
92 1
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
93
        }
94 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...
95
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
96
        }
97 9
        if (! empty($element['readOnly'])) {
98 1
            $class->markReadOnly();
99
        }
100 9
        if (isset($element['fields'])) {
101 9
            foreach ($element['fields'] as $fieldName => $mapping) {
102 9
                if (is_string($mapping)) {
103 1
                    $type = $mapping;
104 1
                    $mapping = array();
105 1
                    $mapping['type'] = $type;
106
                }
107 9
                if ( ! isset($mapping['fieldName'])) {
108 7
                    $mapping['fieldName'] = $fieldName;
109
                }
110 9
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
111 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
112 9
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
113 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
114
                } else {
115 9
                    $this->addFieldMapping($class, $mapping);
116
                }
117
            }
118
        }
119 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...
120 2
            foreach ($element['embedOne'] as $fieldName => $embed) {
121 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
122
            }
123
        }
124 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...
125 2
            foreach ($element['embedMany'] as $fieldName => $embed) {
126 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
127
            }
128
        }
129 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...
130 2
            foreach ($element['referenceOne'] as $fieldName => $reference) {
131 2
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
132
            }
133
        }
134 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...
135 3
            foreach ($element['referenceMany'] as $fieldName => $reference) {
136 3
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
137
            }
138
        }
139 9
        if (isset($element['lifecycleCallbacks'])) {
140 2
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
141 2
                foreach ($methods as $method) {
142 2
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
143
                }
144
            }
145
        }
146 9
        if (isset($element['alsoLoadMethods'])) {
147 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
148 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
149
            }
150
        }
151 9
    }
152
153 9
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
154
    {
155 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...
156 1
            $name = $mapping['name'];
157 9
        } elseif (isset($mapping['fieldName'])) {
158 9
            $name = $mapping['fieldName'];
159
        } else {
160
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
161
        }
162
163 9
        $class->mapField($mapping);
164
165 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...
166 9
            return;
167
        }
168
169
        // Multiple index specifications in one field mapping is ambiguous
170 4
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
171 4
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
172 4
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
173
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
174
        }
175
176
        // Index this field if either "index", "unique", or "sparse" are set
177 4
        $keys = array($name => 'asc');
178
179
        /* The "order" option is only used in the index specification and should
180
         * not be passed along as an index option.
181
         */
182 4
        if (isset($mapping['index']['order'])) {
183 1
            $keys[$name] = $mapping['index']['order'];
184 1
            unset($mapping['index']['order']);
185 4
        } elseif (isset($mapping['unique']['order'])) {
186 1
            $keys[$name] = $mapping['unique']['order'];
187 1
            unset($mapping['unique']['order']);
188 3
        } elseif (isset($mapping['sparse']['order'])) {
189
            $keys[$name] = $mapping['sparse']['order'];
190
            unset($mapping['sparse']['order']);
191
        }
192
193
        /* Initialize $options from any array value among index, unique, and
194
         * sparse. Any boolean values for unique or sparse should be merged into
195
         * the options afterwards to ensure consistent parsing.
196
         */
197 4
        $options = array();
198 4
        $unique = null;
199 4
        $sparse = null;
200
201 4
        if (isset($mapping['index']) && is_array($mapping['index'])) {
202 1
            $options = $mapping['index'];
203
        }
204
205 4 View Code Duplication
        if (isset($mapping['unique'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206 4
            if (is_array($mapping['unique'])) {
207 1
                $options = $mapping['unique'] + array('unique' => true);
208
            } else {
209 3
                $unique = (boolean) $mapping['unique'];
210
            }
211
        }
212
213 4 View Code Duplication
        if (isset($mapping['sparse'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214 3
            if (is_array($mapping['sparse'])) {
215
                $options = $mapping['sparse'] + array('sparse' => true);
216
            } else {
217 3
                $sparse = (boolean) $mapping['sparse'];
218
            }
219
        }
220
221 4
        if (isset($unique)) {
222 3
            $options['unique'] = $unique;
223
        }
224
225 4
        if (isset($sparse)) {
226 3
            $options['sparse'] = $sparse;
227
        }
228
229 4
        $class->addIndex($keys, $options);
230 4
    }
231
232 4
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
233
    {
234 4
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
235
        $mapping = array(
236 4
            'type'            => $type,
237
            'embedded'        => true,
238 4
            'targetDocument'  => $embed['targetDocument'] ?? null,
239 4
            'collectionClass' => $embed['collectionClass'] ?? null,
240 4
            'fieldName'       => $fieldName,
241 4
            'strategy'        => (string) ($embed['strategy'] ?? $defaultStrategy),
242
        );
243 4
        if (isset($embed['name'])) {
244 1
            $mapping['name'] = $embed['name'];
245
        }
246 4
        if (isset($embed['discriminatorField'])) {
247 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
248
        }
249 4
        if (isset($embed['discriminatorMap'])) {
250 1
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
251
        }
252 4
        if (isset($embed['defaultDiscriminatorValue'])) {
253 1
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
254
        }
255 4
        $this->addFieldMapping($class, $mapping);
256 4
    }
257
258 5
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
259
    {
260 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
261
        $mapping = array(
262 5
            'cascade'          => $reference['cascade'] ?? [],
263 5
            'orphanRemoval'    => $reference['orphanRemoval'] ?? false,
264 5
            'type'             => $type,
265
            'reference'        => true,
266 5
            'storeAs'          => (string) ($reference['storeAs'] ?? ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF),
267 5
            'targetDocument'   => $reference['targetDocument'] ?? null,
268 5
            'collectionClass'  => $reference['collectionClass'] ?? null,
269 5
            'fieldName'        => $fieldName,
270 5
            'strategy'         => (string) ($reference['strategy'] ?? $defaultStrategy),
271 5
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
272 5
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
273 5
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
274 5
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
275 5
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
276 5
            'prime'            => $reference['prime'] ?? [],
277
        );
278 5
        if (isset($reference['name'])) {
279 1
            $mapping['name'] = $reference['name'];
280
        }
281 5
        if (isset($reference['discriminatorField'])) {
282 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
283
        }
284 5
        if (isset($reference['discriminatorMap'])) {
285 1
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
286
        }
287 5
        if (isset($reference['defaultDiscriminatorValue'])) {
288 1
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
289
        }
290 5
        if (isset($reference['sort'])) {
291
            $mapping['sort'] = $reference['sort'];
292
        }
293 5
        if (isset($reference['criteria'])) {
294
            $mapping['criteria'] = $reference['criteria'];
295
        }
296 5
        $this->addFieldMapping($class, $mapping);
297 5
    }
298
299
    /**
300
     * Parses the class or field-level "discriminatorField" option.
301
     *
302
     * If the value is an array, check the "name" option before falling back to
303
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
304
     * a string.
305
     *
306
     * @param array|string $discriminatorField
307
     * @return string
308
     * @throws \InvalidArgumentException if the value is neither a string nor an
309
     *                                   array with a "name" or "fieldName" key.
310
     */
311 1
    private function parseDiscriminatorField($discriminatorField)
312
    {
313 1
        if (is_string($discriminatorField)) {
314 1
            return $discriminatorField;
315
        }
316
317 1
        if ( ! is_array($discriminatorField)) {
318
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
319
        }
320
321 1
        if (isset($discriminatorField['name'])) {
322
            return (string) $discriminatorField['name'];
323
        }
324
325 1
        if (isset($discriminatorField['fieldName'])) {
326 1
            return (string) $discriminatorField['fieldName'];
327
        }
328
329
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
330
    }
331
332
    /**
333
     * {@inheritDoc}
334
     */
335 9
    protected function loadMappingFile($file)
336
    {
337
        try {
338 9
            return Yaml::parse(file_get_contents($file));
339
        }
340
        catch (ParseException $e) {
341
            $e->setParsedFile($file);
342
            throw $e;
343
        }
344
    }
345
346 1
    private function setShardKey(ClassMetadataInfo $class, array $shardKey)
347
    {
348 1
        $keys = $shardKey['keys'];
349 1
        $options = array();
350
351 1
        if (isset($shardKey['options'])) {
352 1
            $allowed = array('unique', 'numInitialChunks');
353 1
            foreach ($shardKey['options'] as $name => $value) {
354 1
                if ( ! in_array($name, $allowed, true)) {
355
                    continue;
356
                }
357 1
                $options[$name] = $value;
358
            }
359
        }
360
361 1
        $class->setShardKey($keys, $options);
362 1
    }
363
}
364