Completed
Pull Request — master (#1790)
by Andreas
20:58
created

XmlDriver::addGridFSMappings()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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