Completed
Pull Request — master (#1263)
by Andreas
10:33
created

YamlDriver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

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