Completed
Pull Request — master (#1321)
by Jefersson
14:35
created

YamlDriver   D

Complexity

Total Complexity 93

Size/Duplication

Total Lines 303
Duplicated Lines 18.48 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 86.94%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 93
c 1
b 0
f 0
lcom 1
cbo 3
dl 56
loc 303
ccs 193
cts 222
cp 0.8694
rs 4.8718

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F loadMetadataForClass() 32 105 41
F addFieldMapping() 24 78 21
C addMappingFromEmbed() 0 23 7
F addMappingFromReference() 0 37 17
B parseDiscriminatorField() 0 20 5
A loadMappingFile() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like YamlDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use YamlDriver, and based on these observations, apply Extract Interface, too.

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
29
/**
30
 * The YamlDriver reads the mapping metadata from yaml schema files.
31
 *
32
 * @since       1.0
33
 * @author      Jonathan H. Wage <[email protected]>
34
 * @author      Roman Borschel <[email protected]>
35
 * @author      Jefersson Nathan <[email protected]>
36
 */
37
class YamlDriver extends FileDriver
38
{
39
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
40
41
    /**
42
     * {@inheritDoc}
43
     */
44 8
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
45
    {
46 8
        parent::__construct($locator, $fileExtension);
47 8
    }
48
49
    /**
50
     * {@inheritDoc}
51
     */
52 4
    public function loadMetadataForClass($className, ClassMetadata $class)
53
    {
54
        /* @var $class ClassMetadataInfo */
55 4
        $element = $this->getElement($className);
56 4
        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...
57
            return;
58
        }
59 4
        $element['type'] = isset($element['type']) ? $element['type'] : 'document';
60
61 4
        if (isset($element['db'])) {
62 1
            $class->setDatabase($element['db']);
63 1
        }
64 4
        if (isset($element['collection'])) {
65 4
            $class->setCollection($element['collection']);
66 4
        }
67 4
        if ($element['type'] == 'document') {
68 4
            if (isset($element['repositoryClass'])) {
69
                $class->setCustomRepositoryClass($element['repositoryClass']);
70
            }
71 4 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...
72
            $class->setCustomRepositoryClass(
73
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
74
            );
75
            $class->isMappedSuperclass = true;
76 1
        } elseif ($element['type'] === 'embeddedDocument') {
77 1
            $class->isEmbeddedDocument = true;
78 1
        }
79 4
        if (isset($element['indexes'])) {
80 1
            foreach($element['indexes'] as $index) {
81 1
                $class->addIndex($index['keys'], isset($index['options']) ? $index['options'] : array());
82 1
            }
83 1
        }
84 4 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...
85
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
86
        }
87 4
        if (isset($element['discriminatorField'])) {
88 1
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
89 1
        }
90 4
        if (isset($element['discriminatorMap'])) {
91 1
            $class->setDiscriminatorMap($element['discriminatorMap']);
92 1
        }
93 4
        if (isset($element['defaultDiscriminatorValue'])) {
94 1
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
95 1
        }
96 4 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...
97
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
98
        }
99 4
        if (isset($element['requireIndexes'])) {
100
            $class->setRequireIndexes($element['requireIndexes']);
101
        }
102 4
        if (isset($element['slaveOkay'])) {
103
            $class->setSlaveOkay($element['slaveOkay']);
104
        }
105 4
        if (isset($element['fields'])) {
106 4
            foreach ($element['fields'] as $fieldName => $mapping) {
107 4
                if (is_string($mapping)) {
108 1
                    $type = $mapping;
109 1
                    $mapping = array();
110 1
                    $mapping['type'] = $type;
111 1
                }
112 4
                if ( ! isset($mapping['fieldName'])) {
113 4
                    $mapping['fieldName'] = $fieldName;
114 4
                }
115 4
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
116 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
117 4
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
118 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
119 2
                } else {
120 4
                    $this->addFieldMapping($class, $mapping);
121
                }
122 4
            }
123 4
        }
124 4 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...
125 2
            foreach ($element['embedOne'] as $fieldName => $embed) {
126 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
127 2
            }
128 2
        }
129 4 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...
130 2
            foreach ($element['embedMany'] as $fieldName => $embed) {
131 2
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
132 2
            }
133 2
        }
134 4 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...
135 2
            foreach ($element['referenceOne'] as $fieldName => $reference) {
136 2
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
137 2
            }
138 2
        }
139 4 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...
140 2
            foreach ($element['referenceMany'] as $fieldName => $reference) {
141 2
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
142 2
            }
143 2
        }
144 4
        if (isset($element['lifecycleCallbacks'])) {
145 2
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
146 2
                foreach ($methods as $method) {
147 2
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
148 2
                }
149 2
            }
150 2
        }
151 4
        if (isset($element['alsoLoadMethods'])) {
152 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
153 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
154 1
            }
155 1
        }
156 4
    }
157
158 4
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
159
    {
160 4 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...
161 1
            $name = $mapping['name'];
162 4
        } elseif (isset($mapping['fieldName'])) {
163 4
            $name = $mapping['fieldName'];
164 4
        } else {
165
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
166
        }
167
168 4
        $class->mapField($mapping);
169
170 4 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...
171 4
            return;
172
        }
173
174
        // Multiple index specifications in one field mapping is ambiguous
175 4
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
176 4
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
177 4
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
178
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
179
        }
180
181
        // Index this field if either "index", "unique", or "sparse" are set
182 4
        $keys = array($name => 'asc');
183
184
        /* The "order" option is only used in the index specification and should
185
         * not be passed along as an index option.
186
         */
187 4
        if (isset($mapping['index']['order'])) {
188 1
            $keys[$name] = $mapping['index']['order'];
189 1
            unset($mapping['index']['order']);
190 4
        } elseif (isset($mapping['unique']['order'])) {
191 1
            $keys[$name] = $mapping['unique']['order'];
192 1
            unset($mapping['unique']['order']);
193 4
        } elseif (isset($mapping['sparse']['order'])) {
194
            $keys[$name] = $mapping['sparse']['order'];
195
            unset($mapping['sparse']['order']);
196
        }
197
198
        /* Initialize $options from any array value among index, unique, and
199
         * sparse. Any boolean values for unique or sparse should be merged into
200
         * the options afterwards to ensure consistent parsing.
201
         */
202 4
        $options = array();
203 4
        $unique = null;
204 4
        $sparse = null;
205
206 4
        if (isset($mapping['index']) && is_array($mapping['index'])) {
207 1
            $options = $mapping['index'];
208 1
        }
209
210 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...
211 4
            if (is_array($mapping['unique'])) {
212 1
                $options = $mapping['unique'] + array('unique' => true);
213 1
            } else {
214 3
                $unique = (boolean) $mapping['unique'];
215
            }
216 4
        }
217
218 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...
219 3
            if (is_array($mapping['sparse'])) {
220
                $options = $mapping['sparse'] + array('sparse' => true);
221
            } else {
222 3
                $sparse = (boolean) $mapping['sparse'];
223
            }
224 3
        }
225
226 4
        if (isset($unique)) {
227 3
            $options['unique'] = $unique;
228 3
        }
229
230 4
        if (isset($sparse)) {
231 3
            $options['sparse'] = $sparse;
232 3
        }
233
234 4
        $class->addIndex($keys, $options);
235 4
    }
236
237 4
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
238
    {
239
        $mapping = array(
240 4
            'type'           => $type,
241 4
            'embedded'       => true,
242 4
            'targetDocument' => isset($embed['targetDocument']) ? $embed['targetDocument'] : null,
243 4
            'fieldName'      => $fieldName,
244 4
            'strategy'       => isset($embed['strategy']) ? (string) $embed['strategy'] : CollectionHelper::DEFAULT_STRATEGY,
245 4
        );
246 4
        if (isset($embed['name'])) {
247 1
            $mapping['name'] = $embed['name'];
248 1
        }
249 4
        if (isset($embed['discriminatorField'])) {
250 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
251 1
        }
252 4
        if (isset($embed['discriminatorMap'])) {
253 1
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
254 1
        }
255 4
        if (isset($embed['defaultDiscriminatorValue'])) {
256 1
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
257 1
        }
258 4
        $this->addFieldMapping($class, $mapping);
259 4
    }
260
261 4
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
262
    {
263
        $mapping = array(
264 4
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : null,
265 4
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
266 4
            'type'             => $type,
267 4
            'reference'        => true,
268 4
            'simple'           => isset($reference['simple']) ? (boolean) $reference['simple'] : false,
269 4
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
270 4
            'fieldName'        => $fieldName,
271 4
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : CollectionHelper::DEFAULT_STRATEGY,
272 4
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
273 4
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
274 4
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
275 4
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
276 4
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
277 4
        );
278 4
        if (isset($reference['name'])) {
279 1
            $mapping['name'] = $reference['name'];
280 1
        }
281 4
        if (isset($reference['discriminatorField'])) {
282 1
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
283 1
        }
284 4
        if (isset($reference['discriminatorMap'])) {
285 1
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
286 1
        }
287 4
        if (isset($reference['defaultDiscriminatorValue'])) {
288 1
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
289 1
        }
290 4
        if (isset($reference['sort'])) {
291
            $mapping['sort'] = $reference['sort'];
292
        }
293 4
        if (isset($reference['criteria'])) {
294
            $mapping['criteria'] = $reference['criteria'];
295
        }
296 4
        $this->addFieldMapping($class, $mapping);
297 4
    }
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 4
    protected function loadMappingFile($file)
336
    {
337 4
        return Yaml::parse(file_get_contents($file));
0 ignored issues
show
Bug Compatibility introduced by
The expression \Symfony\Component\Yaml\...e_get_contents($file)); of type array|string adds the type string to the return on line 337 which is incompatible with the return type declared by the abstract method Doctrine\Common\Persiste...Driver::loadMappingFile of type array.
Loading history...
338
    }
339
}
340