Completed
Push — master ( 8a5bc1...66dea1 )
by Andreas
23:33
created

XmlDriver::setShardKey()   D

Complexity

Conditions 10
Paths 16

Size

Total Lines 34
Code Lines 21

Duplication

Lines 13
Ratio 38.24 %

Code Coverage

Tests 13
CRAP Score 16.8468

Importance

Changes 0
Metric Value
dl 13
loc 34
ccs 13
cts 22
cp 0.5909
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 21
nc 16
nop 2
crap 16.8468

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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