Completed
Pull Request — master (#1716)
by Maciej
10:47
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
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['read-only']) && 'true' === (string) $xmlRoot['read-only']) {
110
            $class->markReadOnly();
111
        }
112 8
        if (isset($xmlRoot->{'read-preference'})) {
113
            $class->setReadPreference(...$this->transformReadPreference($xmlRoot->{'read-preference'}));
114
        }
115 8
        if (isset($xmlRoot->field)) {
116 8
            foreach ($xmlRoot->field as $field) {
117 8
                $mapping = array();
118 8
                $attributes = $field->attributes();
119 8
                foreach ($attributes as $key => $value) {
120 8
                    $mapping[$key] = (string) $value;
121 8
                    $booleanAttributes = array('id', 'reference', 'embed', 'unique', 'sparse');
122 8
                    if (in_array($key, $booleanAttributes)) {
123 8
                        $mapping[$key] = ('true' === $mapping[$key]);
124
                    }
125
                }
126 8
                if (isset($mapping['id']) && $mapping['id'] === true && isset($mapping['strategy'])) {
127 3
                    $mapping['options'] = array();
128 3
                    if (isset($field->{'id-generator-option'})) {
129 1
                        foreach ($field->{'id-generator-option'} as $generatorOptions) {
130 1
                            $attributesGenerator = iterator_to_array($generatorOptions->attributes());
131 1
                            if (isset($attributesGenerator['name']) && isset($attributesGenerator['value'])) {
132 1
                                $mapping['options'][(string) $attributesGenerator['name']] = (string) $attributesGenerator['value'];
133
                            }
134
                        }
135
                    }
136
                }
137
138 8
                if (isset($attributes['not-saved'])) {
139
                    $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
140
                }
141
142 8
                if (isset($attributes['also-load'])) {
143
                    $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
144 8
                } elseif (isset($attributes['version'])) {
145
                    $mapping['version'] = ('true' === (string) $attributes['version']);
146 8
                } elseif (isset($attributes['lock'])) {
147
                    $mapping['lock'] = ('true' === (string) $attributes['lock']);
148
                }
149
150 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...
151
            }
152
        }
153 8
        if (isset($xmlRoot->{'embed-one'})) {
154 1
            foreach ($xmlRoot->{'embed-one'} as $embed) {
155 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...
156
            }
157
        }
158 8
        if (isset($xmlRoot->{'embed-many'})) {
159 1
            foreach ($xmlRoot->{'embed-many'} as $embed) {
160 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...
161
            }
162
        }
163 8
        if (isset($xmlRoot->{'reference-many'})) {
164 3
            foreach ($xmlRoot->{'reference-many'} as $reference) {
165 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...
166
            }
167
        }
168 8
        if (isset($xmlRoot->{'reference-one'})) {
169 2
            foreach ($xmlRoot->{'reference-one'} as $reference) {
170 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...
171
            }
172
        }
173 8
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
174 1
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
175 1
                $class->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\ODM\MongoDB\Events::' . (string) $lifecycleCallback['type']));
176
            }
177
        }
178 8
        if (isset($xmlRoot->{'also-load-methods'})) {
179 1
            foreach ($xmlRoot->{'also-load-methods'}->{'also-load-method'} as $alsoLoadMethod) {
180 1
                $class->registerAlsoLoadMethod((string) $alsoLoadMethod['method'], (string) $alsoLoadMethod['field']);
181
            }
182
        }
183 8
    }
184
185 9
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
186
    {
187 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...
188 9
            $name = $mapping['name'];
189
        } elseif (isset($mapping['fieldName'])) {
190
            $name = $mapping['fieldName'];
191
        } else {
192
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
193
        }
194
195 9
        $class->mapField($mapping);
196
197
        // Index this field if either "index", "unique", or "sparse" are set
198 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...
199 9
            return;
200
        }
201
202 1
        $keys = array($name => $mapping['order'] ?? 'asc');
203 1
        $options = array();
204
205 1
        if (isset($mapping['background'])) {
206
            $options['background'] = (boolean) $mapping['background'];
207
        }
208 1
        if (isset($mapping['drop-dups'])) {
209
            $options['dropDups'] = (boolean) $mapping['drop-dups'];
210
        }
211 1
        if (isset($mapping['index-name'])) {
212
            $options['name'] = (string) $mapping['index-name'];
213
        }
214 1
        if (isset($mapping['sparse'])) {
215 1
            $options['sparse'] = (boolean) $mapping['sparse'];
216
        }
217 1
        if (isset($mapping['unique'])) {
218 1
            $options['unique'] = (boolean) $mapping['unique'];
219
        }
220
221 1
        $class->addIndex($keys, $options);
222 1
    }
223
224 1
    private function addEmbedMapping(ClassMetadataInfo $class, $embed, $type)
225
    {
226 1
        $attributes = $embed->attributes();
227 1
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
228
        $mapping = array(
229 1
            'type'            => $type,
230
            'embedded'        => true,
231 1
            'targetDocument'  => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
232 1
            'collectionClass' => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
233 1
            'name'            => (string) $attributes['field'],
234 1
            'strategy'        => (string) ($attributes['strategy'] ?? $defaultStrategy),
235
        );
236 1
        if (isset($attributes['fieldName'])) {
237
            $mapping['fieldName'] = (string) $attributes['fieldName'];
238
        }
239 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...
240
            $attr = $embed->{'discriminator-field'};
241
            $mapping['discriminatorField'] = (string) $attr['name'];
242
        }
243 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...
244
            foreach ($embed->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
245
                $attr = $discriminatorMapping->attributes();
246
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
247
            }
248
        }
249 1
        if (isset($embed->{'default-discriminator-value'})) {
250
            $mapping['defaultDiscriminatorValue'] = (string) $embed->{'default-discriminator-value'}['value'];
251
        }
252 1
        if (isset($attributes['not-saved'])) {
253
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
254
        }
255 1
        if (isset($attributes['also-load'])) {
256
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
257
        }
258 1
        $this->addFieldMapping($class, $mapping);
259 1
    }
260
261 4
    private function addReferenceMapping(ClassMetadataInfo $class, $reference, $type)
262
    {
263 4
        $cascade = array_keys((array) $reference->cascade);
264 4
        if (1 === count($cascade)) {
265 1
            $cascade = current($cascade) ?: next($cascade);
266
        }
267 4
        $attributes = $reference->attributes();
268 4
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
269
        $mapping = array(
270 4
            'cascade'          => $cascade,
271 4
            'orphanRemoval'    => isset($attributes['orphan-removal']) ? ('true' === (string) $attributes['orphan-removal']) : false,
272 4
            'type'             => $type,
273
            'reference'        => true,
274 4
            'storeAs'          => (string) ($attributes['store-as'] ?? ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF),
275 4
            'targetDocument'   => isset($attributes['target-document']) ? (string) $attributes['target-document'] : null,
276 4
            'collectionClass'  => isset($attributes['collection-class']) ? (string) $attributes['collection-class'] : null,
277 4
            'name'             => (string) $attributes['field'],
278 4
            'strategy'         => (string) ($attributes['strategy'] ?? $defaultStrategy),
279 4
            'inversedBy'       => isset($attributes['inversed-by']) ? (string) $attributes['inversed-by'] : null,
280 4
            'mappedBy'         => isset($attributes['mapped-by']) ? (string) $attributes['mapped-by'] : null,
281 4
            'repositoryMethod' => isset($attributes['repository-method']) ? (string) $attributes['repository-method'] : null,
282 4
            'limit'            => isset($attributes['limit']) ? (integer) $attributes['limit'] : null,
283 4
            'skip'             => isset($attributes['skip']) ? (integer) $attributes['skip'] : null,
284
            'prime'            => [],
285
        );
286
287 4
        if (isset($attributes['fieldName'])) {
288
            $mapping['fieldName'] = (string) $attributes['fieldName'];
289
        }
290 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...
291
            $attr = $reference->{'discriminator-field'};
292
            $mapping['discriminatorField'] = (string) $attr['name'];
293
        }
294 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...
295
            foreach ($reference->{'discriminator-map'}->{'discriminator-mapping'} as $discriminatorMapping) {
296
                $attr = $discriminatorMapping->attributes();
297
                $mapping['discriminatorMap'][(string) $attr['value']] = (string) $attr['class'];
298
            }
299
        }
300 4
        if (isset($reference->{'default-discriminator-value'})) {
301
            $mapping['defaultDiscriminatorValue'] = (string) $reference->{'default-discriminator-value'}['value'];
302
        }
303 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...
304
            foreach ($reference->{'sort'}->{'sort'} as $sort) {
305
                $attr = $sort->attributes();
306
                $mapping['sort'][(string) $attr['field']] = (string) ($attr['order'] ?? 'asc');
307
            }
308
        }
309 4
        if (isset($reference->{'criteria'})) {
310
            foreach ($reference->{'criteria'}->{'criteria'} as $criteria) {
311
                $attr = $criteria->attributes();
312
                $mapping['criteria'][(string) $attr['field']] = (string) $attr['value'];
313
            }
314
        }
315 4
        if (isset($attributes['not-saved'])) {
316
            $mapping['notSaved'] = ('true' === (string) $attributes['not-saved']);
317
        }
318 4
        if (isset($attributes['also-load'])) {
319
            $mapping['alsoLoadFields'] = explode(',', $attributes['also-load']);
320
        }
321 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...
322 1
            foreach ($reference->{'prime'}->{'field'} as $field) {
323 1
                $attr = $field->attributes();
324 1
                $mapping['prime'][] = (string) $attr['name'];
325
            }
326
        }
327
328 4
        $this->addFieldMapping($class, $mapping);
329 4
    }
330
331 2
    private function addIndex(ClassMetadataInfo $class, \SimpleXmlElement $xmlIndex)
332
    {
333 2
        $attributes = $xmlIndex->attributes();
334
335 2
        $keys = array();
336
337 2
        foreach ($xmlIndex->{'key'} as $key) {
338 2
            $keys[(string) $key['name']] = (string) ($key['order'] ?? 'asc');
339
        }
340
341 2
        $options = array();
342
343 2
        if (isset($attributes['background'])) {
344
            $options['background'] = ('true' === (string) $attributes['background']);
345
        }
346 2
        if (isset($attributes['drop-dups'])) {
347
            $options['dropDups'] = ('true' === (string) $attributes['drop-dups']);
348
        }
349 2
        if (isset($attributes['name'])) {
350
            $options['name'] = (string) $attributes['name'];
351
        }
352 2
        if (isset($attributes['sparse'])) {
353
            $options['sparse'] = ('true' === (string) $attributes['sparse']);
354
        }
355 2
        if (isset($attributes['unique'])) {
356
            $options['unique'] = ('true' === (string) $attributes['unique']);
357
        }
358
359 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...
360
            foreach ($xmlIndex->{'option'} as $option) {
361
                $value = (string) $option['value'];
362
                if ($value === 'true') {
363
                    $value = true;
364
                } elseif ($value === 'false') {
365
                    $value = false;
366
                } elseif (is_numeric($value)) {
367
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
368
                }
369
                $options[(string) $option['name']] = $value;
370
            }
371
        }
372
373 2
        if (isset($xmlIndex->{'partial-filter-expression'})) {
374 2
            $partialFilterExpressionMapping = $xmlIndex->{'partial-filter-expression'};
375
376 2
            if (isset($partialFilterExpressionMapping->and)) {
377 2
                foreach ($partialFilterExpressionMapping->and as $and) {
378 2
                    if (! isset($and->field)) {
379 1
                        continue;
380
                    }
381
382 2
                    $partialFilterExpression = $this->getPartialFilterExpression($and->field);
383 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...
384
                        continue;
385
                    }
386
387 2
                    $options['partialFilterExpression']['$and'][] = $partialFilterExpression;
388
                }
389 1
            } elseif (isset($partialFilterExpressionMapping->field)) {
390 1
                $partialFilterExpression = $this->getPartialFilterExpression($partialFilterExpressionMapping->field);
391
392 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...
393 1
                    $options['partialFilterExpression'] = $partialFilterExpression;
394
                }
395
            }
396
        }
397
398 2
        $class->addIndex($keys, $options);
399 2
    }
400
401 2
    private function getPartialFilterExpression(\SimpleXMLElement $fields)
402
    {
403 2
        $partialFilterExpression = [];
404 2
        foreach ($fields as $field) {
405 2
            $operator = (string) $field['operator'] ?: null;
406
407 2
            if (! isset($field['value'])) {
408 1
                if (! isset($field->field)) {
409
                    continue;
410
                }
411
412 1
                $nestedExpression = $this->getPartialFilterExpression($field->field);
413 1
                if (! $nestedExpression) {
414
                    continue;
415
                }
416
417 1
                $value = $nestedExpression;
418
            } else {
419 2
                $value = trim((string) $field['value']);
420
            }
421
422 2
            if ($value === 'true') {
423
                $value = true;
424 2
            } elseif ($value === 'false') {
425
                $value = false;
426 2
            } elseif (is_numeric($value)) {
427 1
                $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
428
            }
429
430 2
            $partialFilterExpression[(string) $field['name']] = $operator ? ['$' . $operator => $value] : $value;
431
        }
432
433 2
        return $partialFilterExpression;
434
    }
435
436 1
    private function setShardKey(ClassMetadataInfo $class, \SimpleXmlElement $xmlShardkey)
437
    {
438 1
        $attributes = $xmlShardkey->attributes();
439
440 1
        $keys = array();
441 1
        $options = array();
442 1
        foreach ($xmlShardkey->{'key'} as $key) {
443 1
            $keys[(string) $key['name']] = (string) ($key['order'] ?? 'asc');
444
        }
445
446 1
        if (isset($attributes['unique'])) {
447 1
            $options['unique'] = ('true' === (string) $attributes['unique']);
448
        }
449
450 1
        if (isset($attributes['numInitialChunks'])) {
451 1
            $options['numInitialChunks'] = (int) $attributes['numInitialChunks'];
452
        }
453
454 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...
455
            foreach ($xmlShardkey->{'option'} as $option) {
456
                $value = (string) $option['value'];
457
                if ($value === 'true') {
458
                    $value = true;
459
                } elseif ($value === 'false') {
460
                    $value = false;
461
                } elseif (is_numeric($value)) {
462
                    $value = preg_match('/^[-]?\d+$/', $value) ? (integer) $value : (float) $value;
463
                }
464
                $options[(string) $option['name']] = $value;
465
            }
466
        }
467
468 1
        $class->setShardKey($keys, $options);
469 1
    }
470
471
    /**
472
     * Parses <read-preference> to a format suitable for the underlying driver.
473
     *
474
     * list($readPreference, $tags) = $this->transformReadPreference($xml->{read-preference});
475
     *
476
     * @param \SimpleXMLElement $xmlReadPreference
477
     * @return array
478
     */
479
    private function transformReadPreference($xmlReadPreference)
480
    {
481
        $tags = null;
482
        if (isset($xmlReadPreference->{'tag-set'})) {
483
            $tags = [];
484
            foreach ($xmlReadPreference->{'tag-set'} as $tagSet) {
485
                $set = [];
486
                foreach ($tagSet->tag as $tag) {
487
                    $set[(string) $tag['name']] = (string) $tag['value'];
488
                }
489
                $tags[] = $set;
490
            }
491
        }
492
        return [(string) $xmlReadPreference['mode'], $tags];
493
    }
494
495
    /**
496
     * {@inheritDoc}
497
     */
498 8
    protected function loadMappingFile($file)
499
    {
500 8
        $result = array();
501 8
        $xmlElement = simplexml_load_file($file);
502
503 8
        foreach (array('document', 'embedded-document', 'mapped-superclass', 'query-result-document') as $type) {
504 8
            if (isset($xmlElement->$type)) {
505 8
                foreach ($xmlElement->$type as $documentElement) {
506 8
                    $documentName = (string) $documentElement['name'];
507 8
                    $result[$documentName] = $documentElement;
508
                }
509
            }
510
        }
511
512 8
        return $result;
513
    }
514
}
515