Completed
Push — master ( 8a5bc1...66dea1 )
by Andreas
23:33
created

YamlDriver::addMappingFromEmbed()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

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