Completed
Pull Request — master (#1419)
by Robert
39:37 queued 36:54
created

YamlDriver::setShardKey()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

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