Completed
Pull Request — master (#1458)
by Tony R
12:09
created

XmlDriver   D

Complexity

Total Complexity 153

Size/Duplication

Total Lines 472
Duplicated Lines 18.22 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 93.98%

Importance

Changes 8
Bugs 2 Features 1
Metric Value
wmc 153
c 8
b 2
f 1
lcom 1
cbo 2
dl 86
loc 472
ccs 250
cts 266
cp 0.9398
rs 4.8717

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F loadMetadataForClass() 16 151 52
F addFieldMapping() 10 41 13
F addIndex() 16 72 22
C getPartialFilterExpression() 0 34 11
C setShardKey() 16 34 11
A loadMappingFile() 0 16 4
F addEmbedMapping() 10 36 12
F addReferenceMapping() 18 62 27

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 XmlDriver 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 XmlDriver, 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
28
/**
29
 * XmlDriver is a metadata driver that enables mapping through XML files.
30
 *
31
 * @since       1.0
32
 */
33
class XmlDriver extends FileDriver
34
{
35
    const DEFAULT_FILE_EXTENSION = '.dcm.xml';
36
37
    /**
38
     * {@inheritDoc}
39
     */
40 13
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
41
    {
42 13
        parent::__construct($locator, $fileExtension);
43 13
    }
44
45
    /**
46
     * {@inheritDoc}
47
     */
48 8
    public function loadMetadataForClass($className, ClassMetadata $class)
49
    {
50
        /* @var $class ClassMetadataInfo */
51
        /* @var $xmlRoot \SimpleXMLElement */
52 8
        $xmlRoot = $this->getElement($className);
53 8
        if ( ! $xmlRoot) {
54
            return;
55
        }
56
57 8
        if ($xmlRoot->getName() == 'document') {
58 8
            if (isset($xmlRoot['repository-class'])) {
59 8
                $class->setCustomRepositoryClass((string) $xmlRoot['repository-class']);
60
            }
61 3 View Code Duplication
        } elseif ($xmlRoot->getName() == 'mapped-superclass') {
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...
62 2
            $class->setCustomRepositoryClass(
63 2
                isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null
64
            );
65 2
            $class->isMappedSuperclass = true;
0 ignored issues
show
Bug introduced by
Accessing isMappedSuperclass on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
66 1
        } elseif ($xmlRoot->getName() == 'embedded-document') {
67 1
            $class->isEmbeddedDocument = true;
0 ignored issues
show
Bug introduced by
Accessing isEmbeddedDocument on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
68
        }
69 8
        if (isset($xmlRoot['db'])) {
70 4
            $class->setDatabase((string) $xmlRoot['db']);
71
        }
72 8
        if (isset($xmlRoot['collection'])) {
73 7
            if (isset($xmlRoot['capped-collection'])) {
74
                $config = array('name' => (string) $xmlRoot['collection']);
75
                $config['capped'] = (bool) $xmlRoot['capped-collection'];
76
                if (isset($xmlRoot['capped-collection-max'])) {
77
                    $config['max'] = (int) $xmlRoot['capped-collection-max'];
78
                }
79
                if (isset($xmlRoot['capped-collection-size'])) {
80
                    $config['size'] = (int) $xmlRoot['capped-collection-size'];
81
                }
82
                $class->setCollection($config);
83
            } else {
84 7
                $class->setCollection((string) $xmlRoot['collection']);
85
            }
86
        }
87 8
        if (isset($xmlRoot['writeConcern'])) {
88 1
            $class->setWriteConcern((string) $xmlRoot['writeConcern']);
89
        }
90 8
        if (isset($xmlRoot['inheritance-type'])) {
91
            $inheritanceType = (string) $xmlRoot['inheritance-type'];
92
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . $inheritanceType));
93
        }
94 8 View Code Duplication
        if (isset($xmlRoot['change-tracking-policy'])) {
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 2
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper((string) $xmlRoot['change-tracking-policy'])));
96
        }
97 8
        if (isset($xmlRoot->{'discriminator-field'})) {
98 1
            $discrField = $xmlRoot->{'discriminator-field'};
99
            /* XSD only allows for "name", which is consistent with association
100
             * configurations, but fall back to "fieldName" for BC.
101
             */
102 1
            $class->setDiscriminatorField(
103 1
                isset($discrField['name']) ? (string) $discrField['name'] : (string) $discrField['fieldName']
104
            );
105
        }
106 8 View Code Duplication
        if (isset($xmlRoot->{'discriminator-map'})) {
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...
107 1
            $map = array();
108 1
            foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} AS $discrMapElement) {
109 1
                $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class'];
110
            }
111 1
            $class->setDiscriminatorMap($map);
112
        }
113 8
        if (isset($xmlRoot->{'default-discriminator-value'})) {
114 1
            $class->setDefaultDiscriminatorValue((string) $xmlRoot->{'default-discriminator-value'}['value']);
115
        }
116 8
        if (isset($xmlRoot->{'indexes'})) {
117 3
            foreach ($xmlRoot->{'indexes'}->{'index'} as $index) {
118 3
                $this->addIndex($class, $index);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
119
            }
120
        }
121 8
        if (isset($xmlRoot->{'shard-key'})) {
122 1
            $this->setShardKey($class, $xmlRoot->{'shard-key'}[0]);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
123
        }
124 8
        if (isset($xmlRoot['require-indexes'])) {
125 1
            $class->setRequireIndexes('true' === (string) $xmlRoot['require-indexes']);
126
        }
127 8
        if (isset($xmlRoot['slave-okay'])) {
128 1
            $class->setSlaveOkay('true' === (string) $xmlRoot['slave-okay']);
129
        }
130 8
        if (isset($xmlRoot->field)) {
131 8
            foreach ($xmlRoot->field as $field) {
132 8
                $mapping = array();
133 8
                $attributes = $field->attributes();
134 8
                foreach ($attributes as $key => $value) {
135 8
                    $mapping[$key] = (string) $value;
136 8
                    $booleanAttributes = array('id', 'reference', 'embed', 'unique', 'sparse', 'file', 'distance');
137 8
                    if (in_array($key, $booleanAttributes)) {
138 8
                        $mapping[$key] = ('true' === $mapping[$key]);
139
                    }
140
                }
141 8
                if (isset($mapping['id']) && $mapping['id'] === true && isset($mapping['strategy'])) {
142 3
                    $mapping['options'] = array();
143 3
                    if (isset($field->{'id-generator-option'})) {
144 1
                        foreach ($field->{'id-generator-option'} as $generatorOptions) {
145 1
                            $attributesGenerator = iterator_to_array($generatorOptions->attributes());
146 1
                            if (isset($attributesGenerator['name']) && isset($attributesGenerator['value'])) {
147 1
                                $mapping['options'][(string) $attributesGenerator['name']] = (string) $attributesGenerator['value'];
148
                            }
149
                        }
150
                    }
151
                }
152
153 8
                if (isset($attributes['not-saved'])) {
154
                    $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
155
                }
156
157 8
                if (isset($attributes['also-load'])) {
158
                    $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
159 8
                } elseif (isset($attributes['version'])) {
160 1
                    $mapping['version'] = ('true' === (string) $attributes['version']);
161 8
                } elseif (isset($attributes['lock'])) {
162 1
                    $mapping['lock'] = ('true' === (string) $attributes['lock']);
163
                }
164
165 8
                $this->addFieldMapping($class, $mapping);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
166
            }
167
        }
168 8
        if (isset($xmlRoot->{'embed-one'})) {
169 2
            foreach ($xmlRoot->{'embed-one'} as $embed) {
170 2
                $this->addEmbedMapping($class, $embed, 'one');
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
171
            }
172
        }
173 8
        if (isset($xmlRoot->{'embed-many'})) {
174 2
            foreach ($xmlRoot->{'embed-many'} as $embed) {
175 2
                $this->addEmbedMapping($class, $embed, 'many');
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
176
            }
177
        }
178 8
        if (isset($xmlRoot->{'reference-many'})) {
179 3
            foreach ($xmlRoot->{'reference-many'} as $reference) {
180 3
                $this->addReferenceMapping($class, $reference, 'many');
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
181
            }
182
        }
183 8
        if (isset($xmlRoot->{'reference-one'})) {
184 3
            foreach ($xmlRoot->{'reference-one'} as $reference) {
185 3
                $this->addReferenceMapping($class, $reference, 'one');
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
186
            }
187
        }
188 8
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
189 2
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
190 2
                $class->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\ODM\MongoDB\Events::' . (string) $lifecycleCallback['type']));
191
            }
192
        }
193 8
        if (isset($xmlRoot->{'also-load-methods'})) {
194 1
            foreach ($xmlRoot->{'also-load-methods'}->{'also-load-method'} as $alsoLoadMethod) {
195 1
                $class->registerAlsoLoadMethod((string) $alsoLoadMethod['method'], (string) $alsoLoadMethod['field']);
196
            }
197
        }
198 8
    }
199
200 8
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
201
    {
202 8 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...
203 8
            $name = $mapping['name'];
204 1
        } elseif (isset($mapping['fieldName'])) {
205 1
            $name = $mapping['fieldName'];
206
        } else {
207
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
208
        }
209
210 8
        $class->mapField($mapping);
211
212
        // Index this field if either "index", "unique", or "sparse" are set
213 8 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...
214 8
            return;
215
        }
216
217 2
        $keys = array($name => isset($mapping['order']) ? $mapping['order'] : 'asc');
218 2
        $options = array();
219
220 2
        if (isset($mapping['background'])) {
221
            $options['background'] = (boolean) $mapping['background'];
222
        }
223 2
        if (isset($mapping['drop-dups'])) {
224 1
            $options['dropDups'] = (boolean) $mapping['drop-dups'];
225
        }
226 2
        if (isset($mapping['index-name'])) {
227
            $options['name'] = (string) $mapping['index-name'];
228
        }
229 2
        if (isset($mapping['safe'])) {
230
            $options['safe'] = (boolean) $mapping['safe'];
231
        }
232 2
        if (isset($mapping['sparse'])) {
233 1
            $options['sparse'] = (boolean) $mapping['sparse'];
234
        }
235 2
        if (isset($mapping['unique'])) {
236 2
            $options['unique'] = (boolean) $mapping['unique'];
237
        }
238
239 2
        $class->addIndex($keys, $options);
240 2
    }
241
242 2
    private function addEmbedMapping(ClassMetadataInfo $class, $embed, $type)
243
    {
244 2
        $attributes = $embed->attributes();
245 2
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
246
        $mapping = array(
247 2
            'type'            => $type,
248
            'embedded'        => true,
249 2
            'targetDocument'  => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
250 2
            'collectionClass' => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
251 2
            'name'            => (string) $attributes['field'],
252 2
            'strategy'        => isset($attributes['strategy']) ? (string) $attributes['strategy'] : $defaultStrategy,
253
        );
254 2
        if (isset($attributes['fieldName'])) {
255 1
            $mapping['fieldName'] = (string) $attributes['fieldName'];
256
        }
257 2 View Code Duplication
        if (isset($embed->{'discriminator-field'})) {
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...
258 1
            $attr = $embed->{'discriminator-field'};
259 1
            $mapping['discriminatorField'] = (string) $attr['name'];
260
        }
261 2 View Code Duplication
        if (isset($embed->{'discriminator-map'})) {
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...
262 1
            foreach ($embed->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
263 1
                $attr = $discriminatorMapping->attributes();
264 1
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
265
            }
266
        }
267 2
        if (isset($embed->{'default-discriminator-value'})) {
268 1
            $mapping['defaultDiscriminatorValue'] = (string) $embed->{'default-discriminator-value'}['value'];
269
        }
270 2
        if (isset($attributes['not-saved'])) {
271
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
272
        }
273 2
        if (isset($attributes['also-load'])) {
274
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
275
        }
276 2
        $this->addFieldMapping($class, $mapping);
277 2
    }
278
279 3
    private function addReferenceMapping(ClassMetadataInfo $class, $reference, $type)
280
    {
281 3
        $cascade = array_keys((array) $reference->cascade);
282 3
        if (1 === count($cascade)) {
283 2
            $cascade = current($cascade) ?: next($cascade);
284
        }
285 3
        $attributes = $reference->attributes();
286 3
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
287
        $mapping = array(
288 3
            'cascade'          => $cascade,
289 3
            'orphanRemoval'    => isset($attributes['orphan-removal']) ? ('true' === (string) $attributes['orphan-removal']) : false,
290 3
            'type'             => $type,
291
            'reference'        => true,
292 3
            'simple'           => isset($attributes['simple']) ? ('true' === (string) $attributes['simple']) : false, // deprecated
293 3
            'storeAs'          => isset($attributes['store-as']) ? (string) $attributes['store-as'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
294 3
            'targetDocument'   => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
295 3
            'collectionClass'  => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
296 3
            'name'             => (string) $attributes['field'],
297 3
            'strategy'         => isset($attributes['strategy']) ? (string) $attributes['strategy'] : $defaultStrategy,
298 3
            'inversedBy'       => isset($attributes['inversed-by']) ? (string) $attributes['inversed-by'] : null,
299 3
            'mappedBy'         => isset($attributes['mapped-by']) ? (string) $attributes['mapped-by'] : null,
300 3
            'repositoryMethod' => isset($attributes['repository-method']) ? (string) $attributes['repository-method'] : null,
301 3
            'limit'            => isset($attributes['limit']) ? (integer) $attributes['limit'] : null,
302 3
            'skip'             => isset($attributes['skip']) ? (integer) $attributes['skip'] : null,
303
        );
304
305 3
        if (isset($attributes['fieldName'])) {
306 1
            $mapping['fieldName'] = (string) $attributes['fieldName'];
307
        }
308 3 View Code Duplication
        if (isset($reference->{'discriminator-field'})) {
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...
309 1
            $attr = $reference->{'discriminator-field'};
310 1
            $mapping['discriminatorField'] = (string) $attr['name'];
311
        }
312 3 View Code Duplication
        if (isset($reference->{'discriminator-map'})) {
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...
313 1
            foreach ($reference->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
314 1
                $attr = $discriminatorMapping->attributes();
315 1
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
316
            }
317
        }
318 3
        if (isset($reference->{'default-discriminator-value'})) {
319 1
            $mapping['defaultDiscriminatorValue'] = (string) $reference->{'default-discriminator-value'}['value'];
320
        }
321 3
        if (isset($reference->{'sort'})) {
322 View Code Duplication
            foreach ($reference->{'sort'}->{'sort'} as $sort) {
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...
323
                $attr = $sort->attributes();
324
                $mapping['sort'][(string) $attr['field']] = isset($attr['order']) ? (string) $attr['order'] : 'asc';
325
            }
326
        }
327 3
        if (isset($reference->{'criteria'})) {
328 View Code Duplication
            foreach ($reference->{'criteria'}->{'criteria'} as $criteria) {
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...
329
                $attr = $criteria->attributes();
330
                $mapping['criteria'][(string) $attr['field']] = (string) $attr['value'];
331
            }
332
        }
333 3
        if (isset($attributes['not-saved'])) {
334
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
335
        }
336 3
        if (isset($attributes['also-load'])) {
337
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
338
        }
339 3
        $this->addFieldMapping($class, $mapping);
340 3
    }
341
342 3
    private function addIndex(ClassMetadataInfo $class, \SimpleXmlElement $xmlIndex)
343
    {
344 3
        $attributes = $xmlIndex->attributes();
345
346 3
        $keys = array();
347
348 3 View Code Duplication
        foreach ($xmlIndex->{'key'} as $key) {
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...
349 3
            $keys[(string) $key['name']] = isset($key['order']) ? (string) $key['order'] : 'asc';
350
        }
351
352 3
        $options = array();
353
354 3
        if (isset($attributes['background'])) {
355
            $options['background'] = ('true' === (string) $attributes['background']);
356
        }
357 3
        if (isset($attributes['drop-dups'])) {
358
            $options['dropDups'] = ('true' === (string) $attributes['drop-dups']);
359
        }
360 3
        if (isset($attributes['name'])) {
361
            $options['name'] = (string) $attributes['name'];
362
        }
363 3
        if (isset($attributes['safe'])) {
364
            $options['safe'] = ('true' === (string) $attributes['safe']);
365
        }
366 3
        if (isset($attributes['sparse'])) {
367
            $options['sparse'] = ('true' === (string) $attributes['sparse']);
368
        }
369 3
        if (isset($attributes['unique'])) {
370 1
            $options['unique'] = ('true' === (string) $attributes['unique']);
371
        }
372
373 3 View Code Duplication
        if (isset($xmlIndex->{'option'})) {
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...
374 1
            foreach ($xmlIndex->{'option'} as $option) {
375 1
                $value = (string) $option['value'];
376 1
                if ($value === 'true') {
377
                    $value = true;
378 1
                } elseif ($value === 'false') {
379 1
                    $value = false;
380 1
                } elseif (is_numeric($value)) {
381 1
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
382
                }
383 1
                $options[(string) $option['name']] = $value;
384
            }
385
        }
386
387 3
        if (isset($xmlIndex->{'partial-filter-expression'})) {
388 3
            $partialFilterExpressionMapping = $xmlIndex->{'partial-filter-expression'};
389
390 3
            if (isset($partialFilterExpressionMapping->and)) {
391 2
                foreach ($partialFilterExpressionMapping->and as $and) {
392 2
                    if (! isset($and->field)) {
393 1
                        continue;
394
                    }
395
396 2
                    $partialFilterExpression = $this->getPartialFilterExpression($and->field);
397 2
                    if (! $partialFilterExpression) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $partialFilterExpression 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...
398
                        continue;
399
                    }
400
401 2
                    $options['partialFilterExpression']['$and'][] = $partialFilterExpression;
402
                }
403
            } elseif (isset($partialFilterExpressionMapping->field)) {
404 2
                $partialFilterExpression = $this->getPartialFilterExpression($partialFilterExpressionMapping->field);
405
406 2
                if ($partialFilterExpression) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $partialFilterExpression 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...
407 2
                    $options['partialFilterExpression'] = $partialFilterExpression;
408
                }
409
            }
410
        }
411
412 3
        $class->addIndex($keys, $options);
413 3
    }
414
415 3
    private function getPartialFilterExpression(\SimpleXMLElement $fields)
416
    {
417 3
        $partialFilterExpression = [];
418 3
        foreach ($fields as $field) {
419 3
            $operator = (string) $field['operator'] ?: null;
420
421 3
            if (! isset($field['value'])) {
422 1
                if (! isset($field->field)) {
423
                    continue;
424
                }
425
426 1
                $nestedExpression = $this->getPartialFilterExpression($field->field);
427 1
                if (! $nestedExpression) {
428
                    continue;
429
                }
430
431 1
                $value = $nestedExpression;
432
            } else {
433 3
                $value = trim((string) $field['value']);
434
            }
435
436 3
            if ($value === 'true') {
437
                $value = true;
438 3
            } elseif ($value === 'false') {
439
                $value = false;
440 3
            } elseif (is_numeric($value)) {
441 2
                $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
442
            }
443
444 3
            $partialFilterExpression[(string) $field['name']] = $operator ? ['$' . $operator => $value] : $value;
445
        }
446
447 3
        return $partialFilterExpression;
448
    }
449
450 2
    private function setShardKey(ClassMetadataInfo $class, \SimpleXmlElement $xmlShardkey)
451
    {
452 2
        $attributes = $xmlShardkey->attributes();
453
454 2
        $keys = array();
455 2
        $options = array();
456 2 View Code Duplication
        foreach ($xmlShardkey->{'key'} as $key) {
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...
457 2
            $keys[(string) $key['name']] = isset($key['order']) ? (string)$key['order'] : 'asc';
458
        }
459
460 2
        if (isset($attributes['unique'])) {
461 1
            $options['unique'] = ('true' === (string) $attributes['unique']);
462
        }
463
464 2
        if (isset($attributes['numInitialChunks'])) {
465 1
            $options['numInitialChunks'] = (int) $attributes['numInitialChunks'];
466
        }
467
468 2 View Code Duplication
        if (isset($xmlShardkey->{'option'})) {
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...
469 1
            foreach ($xmlShardkey->{'option'} as $option) {
470 1
                $value = (string) $option['value'];
471 1
                if ($value === 'true') {
472 1
                    $value = true;
473 1
                } elseif ($value === 'false') {
474
                    $value = false;
475 1
                } elseif (is_numeric($value)) {
476 1
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
477
                }
478 1
                $options[(string) $option['name']] = $value;
479
            }
480
        }
481
482 2
        $class->setShardKey($keys, $options);
483 2
    }
484
485
    /**
486
     * {@inheritDoc}
487
     */
488 8
    protected function loadMappingFile($file)
489
    {
490 8
        $result = array();
491 8
        $xmlElement = simplexml_load_file($file);
492
493 8
        foreach (array('document', 'embedded-document', 'mapped-superclass') as $type) {
494 8
            if (isset($xmlElement->$type)) {
495 8
                foreach ($xmlElement->$type as $documentElement) {
496 8
                    $documentName = (string) $documentElement['name'];
497 8
                    $result[$documentName] = $documentElement;
498
                }
499
            }
500
        }
501
502 8
        return $result;
503
    }
504
}
505