Completed
Pull Request — master (#1733)
by
unknown
10:30
created

XmlDriver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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