Completed
Push — 1.0.x ( bcb4f8...f4d4ca )
by Andreas
9s
created

YamlDriver::loadMetadataForClass()   F

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 106
Code Lines 69

Duplication

Lines 30
Ratio 28.3 %

Code Coverage

Tests 85
CRAP Score 47.6808

Importance

Changes 0
Metric Value
dl 30
loc 106
ccs 85
cts 101
cp 0.8416
rs 2
c 0
b 0
f 0
cc 41
eloc 69
nc 1966081
nop 2
crap 47.6808

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