Completed
Pull Request — master (#1612)
by Maciej
08:32
created

XmlDriver   D

Complexity

Total Complexity 158

Size/Duplication

Total Lines 485
Duplicated Lines 17.73 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 86.87%

Importance

Changes 0
Metric Value
wmc 158
lcom 1
cbo 2
dl 86
loc 485
c 0
b 0
f 0
ccs 258
cts 297
cp 0.8687
rs 4.8717

9 Methods

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

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 15
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
41
    {
42 15
        parent::__construct($locator, $fileExtension);
43 15
    }
44
45
    /**
46
     * {@inheritDoc}
47
     */
48 9
    public function loadMetadataForClass($className, ClassMetadata $class)
49
    {
50
        /* @var $class ClassMetadataInfo */
51
        /* @var $xmlRoot \SimpleXMLElement */
52 9
        $xmlRoot = $this->getElement($className);
53 9
        if ( ! $xmlRoot) {
54
            return;
55
        }
56
57 9
        if ($xmlRoot->getName() == 'document') {
58 9
            if (isset($xmlRoot['repository-class'])) {
59 9
                $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 1
        } elseif ($xmlRoot->getName() == 'query-result-document') {
69 1
            $class->isQueryResultDocument = true;
0 ignored issues
show
Bug introduced by
Accessing isQueryResultDocument 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...
70
        }
71 9
        if (isset($xmlRoot['db'])) {
72 4
            $class->setDatabase((string) $xmlRoot['db']);
73
        }
74 9
        if (isset($xmlRoot['collection'])) {
75 8
            if (isset($xmlRoot['capped-collection'])) {
76
                $config = array('name' => (string) $xmlRoot['collection']);
77
                $config['capped'] = (bool) $xmlRoot['capped-collection'];
78
                if (isset($xmlRoot['capped-collection-max'])) {
79
                    $config['max'] = (int) $xmlRoot['capped-collection-max'];
80
                }
81
                if (isset($xmlRoot['capped-collection-size'])) {
82
                    $config['size'] = (int) $xmlRoot['capped-collection-size'];
83
                }
84
                $class->setCollection($config);
85
            } else {
86 8
                $class->setCollection((string) $xmlRoot['collection']);
87
            }
88
        }
89 9
        if (isset($xmlRoot['writeConcern'])) {
90 1
            $class->setWriteConcern((string) $xmlRoot['writeConcern']);
91
        }
92 9
        if (isset($xmlRoot['inheritance-type'])) {
93
            $inheritanceType = (string) $xmlRoot['inheritance-type'];
94
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . $inheritanceType));
95
        }
96 9 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...
97 2
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper((string) $xmlRoot['change-tracking-policy'])));
98
        }
99 9
        if (isset($xmlRoot->{'discriminator-field'})) {
100 1
            $discrField = $xmlRoot->{'discriminator-field'};
101
            /* XSD only allows for "name", which is consistent with association
102
             * configurations, but fall back to "fieldName" for BC.
103
             */
104 1
            $class->setDiscriminatorField(
105 1
                isset($discrField['name']) ? (string) $discrField['name'] : (string) $discrField['fieldName']
106
            );
107
        }
108 9 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...
109 1
            $map = array();
110 1
            foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} AS $discrMapElement) {
111 1
                $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class'];
112
            }
113 1
            $class->setDiscriminatorMap($map);
114
        }
115 9
        if (isset($xmlRoot->{'default-discriminator-value'})) {
116 1
            $class->setDefaultDiscriminatorValue((string) $xmlRoot->{'default-discriminator-value'}['value']);
117
        }
118 9
        if (isset($xmlRoot->{'indexes'})) {
119 3
            foreach ($xmlRoot->{'indexes'}->{'index'} as $index) {
120 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...
121
            }
122
        }
123 9
        if (isset($xmlRoot->{'shard-key'})) {
124 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...
125
        }
126 9
        if (isset($xmlRoot['require-indexes'])) {
127 1
            $class->setRequireIndexes('true' === (string) $xmlRoot['require-indexes']);
128
        }
129 9
        if (isset($xmlRoot['slave-okay'])) {
130 1
            $class->setSlaveOkay('true' === (string) $xmlRoot['slave-okay']);
131
        }
132 9
        if (isset($xmlRoot['read-only']) && 'true' === (string) $xmlRoot['read-only']) {
133 1
            $class->markReadOnly();
134
        }
135 9
        if (isset($xmlRoot->field)) {
136 9
            foreach ($xmlRoot->field as $field) {
137 9
                $mapping = array();
138 9
                $attributes = $field->attributes();
139 9
                foreach ($attributes as $key => $value) {
140 9
                    $mapping[$key] = (string) $value;
141 9
                    $booleanAttributes = array('id', 'reference', 'embed', 'unique', 'sparse', 'file', 'distance');
142 9
                    if (in_array($key, $booleanAttributes)) {
143 9
                        $mapping[$key] = ('true' === $mapping[$key]);
144
                    }
145
                }
146 9
                if (isset($mapping['id']) && $mapping['id'] === true && isset($mapping['strategy'])) {
147 3
                    $mapping['options'] = array();
148 3
                    if (isset($field->{'id-generator-option'})) {
149 1
                        foreach ($field->{'id-generator-option'} as $generatorOptions) {
150 1
                            $attributesGenerator = iterator_to_array($generatorOptions->attributes());
151 1
                            if (isset($attributesGenerator['name']) && isset($attributesGenerator['value'])) {
152 1
                                $mapping['options'][(string) $attributesGenerator['name']] = (string) $attributesGenerator['value'];
153
                            }
154
                        }
155
                    }
156
                }
157
158 9
                if (isset($attributes['not-saved'])) {
159
                    $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
160
                }
161
162 9
                if (isset($attributes['also-load'])) {
163
                    $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
164 9
                } elseif (isset($attributes['version'])) {
165 1
                    $mapping['version'] = ('true' === (string) $attributes['version']);
166 9
                } elseif (isset($attributes['lock'])) {
167 1
                    $mapping['lock'] = ('true' === (string) $attributes['lock']);
168
                }
169
170 9
                $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...
171
            }
172
        }
173 9
        if (isset($xmlRoot->{'embed-one'})) {
174 2
            foreach ($xmlRoot->{'embed-one'} as $embed) {
175 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...
176
            }
177
        }
178 9
        if (isset($xmlRoot->{'embed-many'})) {
179 2
            foreach ($xmlRoot->{'embed-many'} as $embed) {
180 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...
181
            }
182
        }
183 9
        if (isset($xmlRoot->{'reference-many'})) {
184 4
            foreach ($xmlRoot->{'reference-many'} as $reference) {
185 4
                $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...
186
            }
187
        }
188 9
        if (isset($xmlRoot->{'reference-one'})) {
189 3
            foreach ($xmlRoot->{'reference-one'} as $reference) {
190 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...
191
            }
192
        }
193 9
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
194 2
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
195 2
                $class->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\ODM\MongoDB\Events::' . (string) $lifecycleCallback['type']));
196
            }
197
        }
198 9
        if (isset($xmlRoot->{'also-load-methods'})) {
199 1
            foreach ($xmlRoot->{'also-load-methods'}->{'also-load-method'} as $alsoLoadMethod) {
200 1
                $class->registerAlsoLoadMethod((string) $alsoLoadMethod['method'], (string) $alsoLoadMethod['field']);
201
            }
202
        }
203 9
    }
204
205 10
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
206
    {
207 10 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...
208 10
            $name = $mapping['name'];
209 1
        } elseif (isset($mapping['fieldName'])) {
210 1
            $name = $mapping['fieldName'];
211
        } else {
212
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
213
        }
214
215 10
        $class->mapField($mapping);
216
217
        // Index this field if either "index", "unique", or "sparse" are set
218 10 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...
219 10
            return;
220
        }
221
222 2
        $keys = array($name => isset($mapping['order']) ? $mapping['order'] : 'asc');
223 2
        $options = array();
224
225 2
        if (isset($mapping['background'])) {
226
            $options['background'] = (boolean) $mapping['background'];
227
        }
228 2
        if (isset($mapping['drop-dups'])) {
229 1
            $options['dropDups'] = (boolean) $mapping['drop-dups'];
230
        }
231 2
        if (isset($mapping['index-name'])) {
232
            $options['name'] = (string) $mapping['index-name'];
233
        }
234 2
        if (isset($mapping['safe'])) {
235
            $options['safe'] = (boolean) $mapping['safe'];
236
        }
237 2
        if (isset($mapping['sparse'])) {
238 1
            $options['sparse'] = (boolean) $mapping['sparse'];
239
        }
240 2
        if (isset($mapping['unique'])) {
241 2
            $options['unique'] = (boolean) $mapping['unique'];
242
        }
243
244 2
        $class->addIndex($keys, $options);
245 2
    }
246
247 2
    private function addEmbedMapping(ClassMetadataInfo $class, $embed, $type)
248
    {
249 2
        $attributes = $embed->attributes();
250 2
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
251
        $mapping = array(
252 2
            'type'            => $type,
253
            'embedded'        => true,
254 2
            'targetDocument'  => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
255 2
            'collectionClass' => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
256 2
            'name'            => (string) $attributes['field'],
257 2
            'strategy'        => isset($attributes['strategy']) ? (string) $attributes['strategy'] : $defaultStrategy,
258
        );
259 2
        if (isset($attributes['fieldName'])) {
260 1
            $mapping['fieldName'] = (string) $attributes['fieldName'];
261
        }
262 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...
263 1
            $attr = $embed->{'discriminator-field'};
264 1
            $mapping['discriminatorField'] = (string) $attr['name'];
265
        }
266 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...
267 1
            foreach ($embed->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
268 1
                $attr = $discriminatorMapping->attributes();
269 1
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
270
            }
271
        }
272 2
        if (isset($embed->{'default-discriminator-value'})) {
273 1
            $mapping['defaultDiscriminatorValue'] = (string) $embed->{'default-discriminator-value'}['value'];
274
        }
275 2
        if (isset($attributes['not-saved'])) {
276
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
277
        }
278 2
        if (isset($attributes['also-load'])) {
279
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
280
        }
281 2
        $this->addFieldMapping($class, $mapping);
282 2
    }
283
284 5
    private function addReferenceMapping(ClassMetadataInfo $class, $reference, $type)
285
    {
286 5
        $cascade = array_keys((array) $reference->cascade);
287 5
        if (1 === count($cascade)) {
288 2
            $cascade = current($cascade) ?: next($cascade);
289
        }
290 5
        $attributes = $reference->attributes();
291 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
292
        $mapping = array(
293 5
            'cascade'          => $cascade,
294 5
            'orphanRemoval'    => isset($attributes['orphan-removal']) ? ('true' === (string) $attributes['orphan-removal']) : false,
295 5
            'type'             => $type,
296
            'reference'        => true,
297 5
            'simple'           => isset($attributes['simple']) ? ('true' === (string) $attributes['simple']) : false, // deprecated
298 5
            'storeAs'          => isset($attributes['store-as']) ? (string) $attributes['store-as'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
299 5
            'targetDocument'   => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
300 5
            'collectionClass'  => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
301 5
            'name'             => (string) $attributes['field'],
302 5
            'strategy'         => isset($attributes['strategy']) ? (string) $attributes['strategy'] : $defaultStrategy,
303 5
            'inversedBy'       => isset($attributes['inversed-by']) ? (string) $attributes['inversed-by'] : null,
304 5
            'mappedBy'         => isset($attributes['mapped-by']) ? (string) $attributes['mapped-by'] : null,
305 5
            'repositoryMethod' => isset($attributes['repository-method']) ? (string) $attributes['repository-method'] : null,
306 5
            'limit'            => isset($attributes['limit']) ? (integer) $attributes['limit'] : null,
307 5
            'skip'             => isset($attributes['skip']) ? (integer) $attributes['skip'] : null,
308
            'prime'            => [],
309
        );
310
311 5
        if (isset($attributes['fieldName'])) {
312 1
            $mapping['fieldName'] = (string) $attributes['fieldName'];
313
        }
314 5 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...
315 1
            $attr = $reference->{'discriminator-field'};
316 1
            $mapping['discriminatorField'] = (string) $attr['name'];
317
        }
318 5 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...
319 1
            foreach ($reference->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
320 1
                $attr = $discriminatorMapping->attributes();
321 1
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
322
            }
323
        }
324 5
        if (isset($reference->{'default-discriminator-value'})) {
325 1
            $mapping['defaultDiscriminatorValue'] = (string) $reference->{'default-discriminator-value'}['value'];
326
        }
327 5
        if (isset($reference->{'sort'})) {
328 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...
329
                $attr = $sort->attributes();
330
                $mapping['sort'][(string) $attr['field']] = isset($attr['order']) ? (string) $attr['order'] : 'asc';
331
            }
332
        }
333 5
        if (isset($reference->{'criteria'})) {
334 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...
335
                $attr = $criteria->attributes();
336
                $mapping['criteria'][(string) $attr['field']] = (string) $attr['value'];
337
            }
338
        }
339 5
        if (isset($attributes['not-saved'])) {
340
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
341
        }
342 5
        if (isset($attributes['also-load'])) {
343
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
344
        }
345 5
        if (isset($reference->{'prime'})) {
346 1
            foreach ($reference->{'prime'}->{'field'} as $field) {
347 1
                $attr = $field->attributes();
348 1
                $mapping['prime'][] = (string) $attr['name'];
349
            }
350
        }
351
352 5
        $this->addFieldMapping($class, $mapping);
353 5
    }
354
355 3
    private function addIndex(ClassMetadataInfo $class, \SimpleXmlElement $xmlIndex)
356
    {
357 3
        $attributes = $xmlIndex->attributes();
358
359 3
        $keys = array();
360
361 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...
362 3
            $keys[(string) $key['name']] = isset($key['order']) ? (string) $key['order'] : 'asc';
363
        }
364
365 3
        $options = array();
366
367 3
        if (isset($attributes['background'])) {
368
            $options['background'] = ('true' === (string) $attributes['background']);
369
        }
370 3
        if (isset($attributes['drop-dups'])) {
371
            $options['dropDups'] = ('true' === (string) $attributes['drop-dups']);
372
        }
373 3
        if (isset($attributes['name'])) {
374
            $options['name'] = (string) $attributes['name'];
375
        }
376 3
        if (isset($attributes['safe'])) {
377
            $options['safe'] = ('true' === (string) $attributes['safe']);
378
        }
379 3
        if (isset($attributes['sparse'])) {
380
            $options['sparse'] = ('true' === (string) $attributes['sparse']);
381
        }
382 3
        if (isset($attributes['unique'])) {
383 1
            $options['unique'] = ('true' === (string) $attributes['unique']);
384
        }
385
386 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...
387 1
            foreach ($xmlIndex->{'option'} as $option) {
388 1
                $value = (string) $option['value'];
389 1
                if ($value === 'true') {
390
                    $value = true;
391 1
                } elseif ($value === 'false') {
392 1
                    $value = false;
393 1
                } elseif (is_numeric($value)) {
394 1
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
395
                }
396 1
                $options[(string) $option['name']] = $value;
397
            }
398
        }
399
400 3
        if (isset($xmlIndex->{'partial-filter-expression'})) {
401 3
            $partialFilterExpressionMapping = $xmlIndex->{'partial-filter-expression'};
402
403 3
            if (isset($partialFilterExpressionMapping->and)) {
404 2
                foreach ($partialFilterExpressionMapping->and as $and) {
405 2
                    if (! isset($and->field)) {
406 1
                        continue;
407
                    }
408
409 2
                    $partialFilterExpression = $this->getPartialFilterExpression($and->field);
410 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...
411
                        continue;
412
                    }
413
414 2
                    $options['partialFilterExpression']['$and'][] = $partialFilterExpression;
415
                }
416
            } elseif (isset($partialFilterExpressionMapping->field)) {
417 2
                $partialFilterExpression = $this->getPartialFilterExpression($partialFilterExpressionMapping->field);
418
419 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...
420 2
                    $options['partialFilterExpression'] = $partialFilterExpression;
421
                }
422
            }
423
        }
424
425 3
        $class->addIndex($keys, $options);
426 3
    }
427
428 3
    private function getPartialFilterExpression(\SimpleXMLElement $fields)
429
    {
430 3
        $partialFilterExpression = [];
431 3
        foreach ($fields as $field) {
432 3
            $operator = (string) $field['operator'] ?: null;
433
434 3
            if (! isset($field['value'])) {
435 1
                if (! isset($field->field)) {
436
                    continue;
437
                }
438
439 1
                $nestedExpression = $this->getPartialFilterExpression($field->field);
440 1
                if (! $nestedExpression) {
441
                    continue;
442
                }
443
444 1
                $value = $nestedExpression;
445
            } else {
446 3
                $value = trim((string) $field['value']);
447
            }
448
449 3
            if ($value === 'true') {
450
                $value = true;
451 3
            } elseif ($value === 'false') {
452
                $value = false;
453 3
            } elseif (is_numeric($value)) {
454 2
                $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
455
            }
456
457 3
            $partialFilterExpression[(string) $field['name']] = $operator ? ['$' . $operator => $value] : $value;
458
        }
459
460 3
        return $partialFilterExpression;
461
    }
462
463 2
    private function setShardKey(ClassMetadataInfo $class, \SimpleXmlElement $xmlShardkey)
464
    {
465 2
        $attributes = $xmlShardkey->attributes();
466
467 2
        $keys = array();
468 2
        $options = array();
469 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...
470 2
            $keys[(string) $key['name']] = isset($key['order']) ? (string)$key['order'] : 'asc';
471
        }
472
473 2
        if (isset($attributes['unique'])) {
474 1
            $options['unique'] = ('true' === (string) $attributes['unique']);
475
        }
476
477 2
        if (isset($attributes['numInitialChunks'])) {
478 1
            $options['numInitialChunks'] = (int) $attributes['numInitialChunks'];
479
        }
480
481 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...
482 1
            foreach ($xmlShardkey->{'option'} as $option) {
483 1
                $value = (string) $option['value'];
484 1
                if ($value === 'true') {
485 1
                    $value = true;
486 1
                } elseif ($value === 'false') {
487
                    $value = false;
488 1
                } elseif (is_numeric($value)) {
489 1
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
490
                }
491 1
                $options[(string) $option['name']] = $value;
492
            }
493
        }
494
495 2
        $class->setShardKey($keys, $options);
496 2
    }
497
498
    /**
499
     * {@inheritDoc}
500
     */
501 9
    protected function loadMappingFile($file)
502
    {
503 9
        $result = array();
504 9
        $xmlElement = simplexml_load_file($file);
505
506 9
        foreach (array('document', 'embedded-document', 'mapped-superclass', 'query-result-document') as $type) {
507 9
            if (isset($xmlElement->$type)) {
508 9
                foreach ($xmlElement->$type as $documentElement) {
509 9
                    $documentName = (string) $documentElement['name'];
510 9
                    $result[$documentName] = $documentElement;
511
                }
512
            }
513
        }
514
515 9
        return $result;
516
    }
517
}
518