Completed
Pull Request — master (#7725)
by Guilherme
08:45
created

XmlDriver   F

Complexity

Total Complexity 168

Size/Duplication

Total Lines 888
Duplicated Lines 0 %

Test Coverage

Coverage 86.25%

Importance

Changes 0
Metric Value
eloc 435
dl 0
loc 888
ccs 370
cts 429
cp 0.8625
rs 2
c 0
b 0
f 0
wmc 168

10 Methods

Rating   Name   Duplication   Size   Complexity  
A evaluateBoolean() 0 5 2
F convertFieldElementToFieldMetadata() 0 45 11
A convertJoinColumnElementToJoinColumnMetadata() 0 28 6
F loadMetadataForClass() 0 637 130
A getMethodCallbacks() 0 15 1
B loadMappingFile() 0 24 7
A getCascadeMappings() 0 15 2
A parseOptions() 0 25 5
A __construct() 0 3 1
A convertCacheElementToCacheMetadata() 0 14 3

How to fix   Complexity   

Complex Class

Complex classes like XmlDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use XmlDriver, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Mapping\Driver;
6
7
use Doctrine\Common\Collections\Criteria;
8
use Doctrine\DBAL\Types\Type;
9
use Doctrine\ORM\Events;
10
use Doctrine\ORM\Mapping;
11
use InvalidArgumentException;
12
use ReflectionClass;
13
use ReflectionMethod;
14
use SimpleXMLElement;
15
use function array_filter;
16
use function class_exists;
17
use function constant;
18
use function explode;
19
use function file_get_contents;
20
use function get_class;
21
use function in_array;
22
use function simplexml_load_string;
23
use function sprintf;
24
use function str_replace;
25
use function strtolower;
26
use function strtoupper;
27
28
/**
29
 * XmlDriver is a metadata driver that enables mapping through XML files.
30
 */
31
class XmlDriver extends FileDriver
32
{
33
    public const DEFAULT_FILE_EXTENSION = '.dcm.xml';
34
35
    /**
36
     * {@inheritDoc}
37
     */
38 41
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
39
    {
40 41
        parent::__construct($locator, $fileExtension);
41 41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46 36
    public function loadMetadataForClass(
47
        string $className,
48
        Mapping\ClassMetadata $metadata,
49
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
50
    ) {
51
        /** @var SimpleXMLElement $xmlRoot */
52 36
        $xmlRoot = $this->getElement($className);
53
54 34
        if ($xmlRoot->getName() === 'entity') {
55 34
            if (isset($xmlRoot['repository-class'])) {
56
                $metadata->setCustomRepositoryClassName((string) $xmlRoot['repository-class']);
57
            }
58
59 34
            if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) {
60 34
                $metadata->asReadOnly();
61
            }
62 5
        } elseif ($xmlRoot->getName() === 'mapped-superclass') {
63 5
            if (isset($xmlRoot['repository-class'])) {
64 1
                $metadata->setCustomRepositoryClassName((string) $xmlRoot['repository-class']);
65
            }
66
67 5
            $metadata->isMappedSuperclass = true;
68
        } elseif ($xmlRoot->getName() === 'embeddable') {
69
            $metadata->isEmbeddedClass = true;
70
        } else {
71
            throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
72
        }
73
74
        // Process table information
75 34
        $parent = $metadata->getParent();
76
77 34
        if ($parent && $parent->inheritanceType === Mapping\InheritanceType::SINGLE_TABLE) {
78 2
            $metadata->setTable($parent->table);
79
        } else {
80 34
            $namingStrategy = $metadataBuildingContext->getNamingStrategy();
81 34
            $tableMetadata  = new Mapping\TableMetadata();
82
83 34
            $tableMetadata->setName($namingStrategy->classToTableName($metadata->getClassName()));
84
85
            // Evaluate <entity...> attributes
86 34
            if (isset($xmlRoot['table'])) {
87 13
                $tableMetadata->setName((string) $xmlRoot['table']);
88
            }
89
90 34
            if (isset($xmlRoot['schema'])) {
91 2
                $tableMetadata->setSchema((string) $xmlRoot['schema']);
92
            }
93
94 34
            if (isset($xmlRoot->options)) {
95 3
                $options = $this->parseOptions($xmlRoot->options->children());
96
97 3
                foreach ($options as $optionName => $optionValue) {
98 3
                    $tableMetadata->addOption($optionName, $optionValue);
99
                }
100
            }
101
102
            // Evaluate <indexes...>
103 34
            if (isset($xmlRoot->indexes)) {
104 4
                foreach ($xmlRoot->indexes->index as $indexXml) {
105 4
                    $indexName = isset($indexXml['name']) ? (string) $indexXml['name'] : null;
106 4
                    $columns   = explode(',', (string) $indexXml['columns']);
107 4
                    $isUnique  = isset($indexXml['unique']) && $indexXml['unique'];
108 4
                    $options   = isset($indexXml->options) ? $this->parseOptions($indexXml->options->children()) : [];
109 4
                    $flags     = isset($indexXml['flags']) ? explode(',', (string) $indexXml['flags']) : [];
110
111 4
                    $tableMetadata->addIndex([
112 4
                        'name'    => $indexName,
113 4
                        'columns' => $columns,
114 4
                        'unique'  => $isUnique,
115 4
                        'options' => $options,
116 4
                        'flags'   => $flags,
117
                    ]);
118
                }
119
            }
120
121
            // Evaluate <unique-constraints..>
122
123 34
            if (isset($xmlRoot->{'unique-constraints'})) {
124 3
                foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $uniqueXml) {
125 3
                    $indexName = isset($uniqueXml['name']) ? (string) $uniqueXml['name'] : null;
126 3
                    $columns   = explode(',', (string) $uniqueXml['columns']);
127 3
                    $options   = isset($uniqueXml->options) ? $this->parseOptions($uniqueXml->options->children()) : [];
128 3
                    $flags     = isset($uniqueXml['flags']) ? explode(',', (string) $uniqueXml['flags']) : [];
129
130 3
                    $tableMetadata->addUniqueConstraint([
131 3
                        'name'    => $indexName,
132 3
                        'columns' => $columns,
133 3
                        'options' => $options,
134 3
                        'flags'   => $flags,
135
                    ]);
136
                }
137
            }
138
139 34
            $metadata->setTable($tableMetadata);
140
        }
141
142
        // Evaluate second level cache
143 34
        if (isset($xmlRoot->cache)) {
144 2
            $cache = $this->convertCacheElementToCacheMetadata($xmlRoot->cache, $metadata);
145
146 2
            $metadata->setCache($cache);
147
        }
148
149 34
        if (isset($xmlRoot['inheritance-type'])) {
150 10
            $inheritanceType = strtoupper((string) $xmlRoot['inheritance-type']);
151
152 10
            $metadata->setInheritanceType(
153 10
                constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceType))
154
            );
155
156 10
            if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) {
157 10
                $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata();
158
159 10
                $discriminatorColumn->setTableName($metadata->getTableName());
160 10
                $discriminatorColumn->setColumnName('dtype');
161 10
                $discriminatorColumn->setType(Type::getType('string'));
162 10
                $discriminatorColumn->setLength(255);
163
164
                // Evaluate <discriminator-column...>
165 10
                if (isset($xmlRoot->{'discriminator-column'})) {
166 8
                    $discriminatorColumnMapping = $xmlRoot->{'discriminator-column'};
167 8
                    $typeName                   = (string) ($discriminatorColumnMapping['type'] ?? 'string');
168
169 8
                    $discriminatorColumn->setType(Type::getType($typeName));
170 8
                    $discriminatorColumn->setColumnName((string) $discriminatorColumnMapping['name']);
171
172 8
                    if (isset($discriminatorColumnMapping['column-definition'])) {
173 1
                        $discriminatorColumn->setColumnDefinition((string) $discriminatorColumnMapping['column-definition']);
174
                    }
175
176 8
                    if (isset($discriminatorColumnMapping['length'])) {
177 3
                        $discriminatorColumn->setLength((int) $discriminatorColumnMapping['length']);
178
                    }
179
                }
180
181 10
                $metadata->setDiscriminatorColumn($discriminatorColumn);
182
183
                // Evaluate <discriminator-map...>
184 10
                if (isset($xmlRoot->{'discriminator-map'})) {
185 10
                    $map = [];
186
187 10
                    foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) {
188 10
                        $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class'];
189
                    }
190
191 10
                    $metadata->setDiscriminatorMap($map);
192
                }
193
            }
194
        }
195
196
        // Evaluate <change-tracking-policy...>
197 34
        if (isset($xmlRoot['change-tracking-policy'])) {
198
            $changeTrackingPolicy = strtoupper((string) $xmlRoot['change-tracking-policy']);
199
200
            $metadata->setChangeTrackingPolicy(
201
                constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingPolicy))
202
            );
203
        }
204
205
        // Evaluate <field ...> mappings
206 34
        if (isset($xmlRoot->field)) {
207 21
            foreach ($xmlRoot->field as $fieldElement) {
208 21
                $fieldName        = (string) $fieldElement['name'];
209 21
                $isFieldVersioned = isset($fieldElement['version']) && $fieldElement['version'];
210 21
                $fieldMetadata    = $this->convertFieldElementToFieldMetadata($fieldElement, $fieldName, $isFieldVersioned);
211
212 21
                $metadata->addProperty($fieldMetadata);
213
            }
214
        }
215
216 34
        if (isset($xmlRoot->embedded)) {
217
            foreach ($xmlRoot->embedded as $embeddedMapping) {
218
                $columnPrefix = isset($embeddedMapping['column-prefix'])
219
                    ? (string) $embeddedMapping['column-prefix']
220
                    : null;
221
222
                $useColumnPrefix = isset($embeddedMapping['use-column-prefix'])
223
                    ? $this->evaluateBoolean($embeddedMapping['use-column-prefix'])
224
                    : true;
225
226
                $mapping = [
227
                    'fieldName' => (string) $embeddedMapping['name'],
228
                    'class' => (string) $embeddedMapping['class'],
229
                    'columnPrefix' => $useColumnPrefix ? $columnPrefix : false,
230
                ];
231
232
                $metadata->mapEmbedded($mapping);
233
            }
234
        }
235
236
        // Evaluate <id ...> mappings
237 34
        $associationIds = [];
238
239 34
        foreach ($xmlRoot->id as $idElement) {
240 30
            $fieldName = (string) $idElement['name'];
241
242 30
            if (isset($idElement['association-key']) && $this->evaluateBoolean($idElement['association-key'])) {
243 2
                $associationIds[$fieldName] = true;
244
245 2
                continue;
246
            }
247
248 29
            $fieldMetadata = $this->convertFieldElementToFieldMetadata($idElement, $fieldName, false);
249
250 29
            $fieldMetadata->setPrimaryKey(true);
251
252 29
            if (isset($idElement->generator)) {
253 28
                $strategy = (string) ($idElement->generator['strategy'] ?? 'AUTO');
254
255 28
                $idGeneratorType = constant(sprintf('%s::%s', Mapping\GeneratorType::class, strtoupper($strategy)));
256
257 28
                if ($idGeneratorType !== Mapping\GeneratorType::NONE) {
258 21
                    $idGeneratorDefinition = [];
259
260
                    // Check for SequenceGenerator/TableGenerator definition
261 21
                    if (isset($idElement->{'sequence-generator'})) {
262 3
                        $seqGenerator          = $idElement->{'sequence-generator'};
263
                        $idGeneratorDefinition = [
264 3
                            'sequenceName' => (string) $seqGenerator['sequence-name'],
265 3
                            'allocationSize' => (string) $seqGenerator['allocation-size'],
266
                        ];
267 18
                    } elseif (isset($idElement->{'custom-id-generator'})) {
268 2
                        $customGenerator = $idElement->{'custom-id-generator'};
269
270
                        $idGeneratorDefinition = [
271 2
                            'class' => (string) $customGenerator['class'],
272
                            'arguments' => [],
273
                        ];
274 16
                    } elseif (isset($idElement->{'table-generator'})) {
275
                        throw Mapping\MappingException::tableIdGeneratorNotImplemented($className);
276
                    }
277
278 21
                    $fieldMetadata->setValueGenerator(new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition));
279
                }
280
            }
281
282 29
            $metadata->addProperty($fieldMetadata);
283
        }
284
285
        // Evaluate <one-to-one ...> mappings
286 34
        if (isset($xmlRoot->{'one-to-one'})) {
287 8
            foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) {
288 8
                $association  = new Mapping\OneToOneAssociationMetadata((string) $oneToOneElement['field']);
289 8
                $targetEntity = (string) $oneToOneElement['target-entity'];
290
291 8
                $association->setTargetEntity($targetEntity);
292
293 8
                if (isset($associationIds[$association->getName()])) {
294
                    $association->setPrimaryKey(true);
295
                }
296
297 8
                if (isset($oneToOneElement['fetch'])) {
298 3
                    $association->setFetchMode(
299 3
                        constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $oneToOneElement['fetch']))
300
                    );
301
                }
302
303 8
                if (isset($oneToOneElement['mapped-by'])) {
304 3
                    $association->setMappedBy((string) $oneToOneElement['mapped-by']);
305 3
                    $association->setOwningSide(false);
306
                } else {
307 6
                    if (isset($oneToOneElement['inversed-by'])) {
308 5
                        $association->setInversedBy((string) $oneToOneElement['inversed-by']);
309
                    }
310
311 6
                    $joinColumns = [];
312
313 6
                    if (isset($oneToOneElement->{'join-column'})) {
314 6
                        $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($oneToOneElement->{'join-column'});
315
                    } elseif (isset($oneToOneElement->{'join-columns'})) {
316
                        foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
317
                            $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
318
                        }
319
                    }
320
321 6
                    $association->setJoinColumns($joinColumns);
322
                }
323
324 8
                if (isset($oneToOneElement->cascade)) {
325 7
                    $association->setCascade($this->getCascadeMappings($oneToOneElement->cascade));
326
                }
327
328 8
                if (isset($oneToOneElement['orphan-removal'])) {
329
                    $association->setOrphanRemoval($this->evaluateBoolean($oneToOneElement['orphan-removal']));
330
                }
331
332
                // Evaluate second level cache
333 8
                if (isset($oneToOneElement->cache)) {
334
                    $association->setCache(
335
                        $this->convertCacheElementToCacheMetadata(
336
                            $oneToOneElement->cache,
337
                            $metadata,
338
                            $association->getName()
339
                        )
340
                    );
341
                }
342
343 8
                $metadata->addProperty($association);
344
            }
345
        }
346
347
        // Evaluate <one-to-many ...> mappings
348 34
        if (isset($xmlRoot->{'one-to-many'})) {
349 9
            foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) {
350 9
                $association  = new Mapping\OneToManyAssociationMetadata((string) $oneToManyElement['field']);
351 9
                $targetEntity = (string) $oneToManyElement['target-entity'];
352
353 9
                $association->setTargetEntity($targetEntity);
354 9
                $association->setOwningSide(false);
355 9
                $association->setMappedBy((string) $oneToManyElement['mapped-by']);
356
357 9
                if (isset($associationIds[$association->getName()])) {
358
                    throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $association->getName());
359
                }
360
361 9
                if (isset($oneToManyElement['fetch'])) {
362
                    $association->setFetchMode(
363
                        constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $oneToManyElement['fetch']))
364
                    );
365
                }
366
367 9
                if (isset($oneToManyElement->cascade)) {
368 6
                    $association->setCascade($this->getCascadeMappings($oneToManyElement->cascade));
369
                }
370
371 9
                if (isset($oneToManyElement['orphan-removal'])) {
372 3
                    $association->setOrphanRemoval($this->evaluateBoolean($oneToManyElement['orphan-removal']));
373
                }
374
375 9
                if (isset($oneToManyElement->{'order-by'})) {
376 5
                    $orderBy = [];
377
378 5
                    foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) {
379 5
                        $orderBy[(string) $orderByField['name']] = isset($orderByField['direction'])
380 4
                            ? (string) $orderByField['direction']
381 1
                            : Criteria::ASC
382
                        ;
0 ignored issues
show
Coding Style introduced by
Space found before semicolon; expected "ASC;" but found "ASC
;"
Loading history...
383
                    }
384
385 5
                    $association->setOrderBy($orderBy);
386
                }
387
388 9
                if (isset($oneToManyElement['index-by'])) {
389 3
                    $association->setIndexedBy((string) $oneToManyElement['index-by']);
390 6
                } elseif (isset($oneToManyElement->{'index-by'})) {
391
                    throw new InvalidArgumentException('<index-by /> is not a valid tag');
392
                }
393
394
                // Evaluate second level cache
395 9
                if (isset($oneToManyElement->cache)) {
396 1
                    $association->setCache(
397 1
                        $this->convertCacheElementToCacheMetadata(
398 1
                            $oneToManyElement->cache,
399 1
                            $metadata,
400 1
                            $association->getName()
401
                        )
402
                    );
403
                }
404
405 9
                $metadata->addProperty($association);
406
            }
407
        }
408
409
        // Evaluate <many-to-one ...> mappings
410 34
        if (isset($xmlRoot->{'many-to-one'})) {
411 8
            foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) {
412 8
                $association  = new Mapping\ManyToOneAssociationMetadata((string) $manyToOneElement['field']);
413 8
                $targetEntity = (string) $manyToOneElement['target-entity'];
414
415 8
                $association->setTargetEntity($targetEntity);
416
417 8
                if (isset($associationIds[$association->getName()])) {
418 2
                    $association->setPrimaryKey(true);
419
                }
420
421 8
                if (isset($manyToOneElement['fetch'])) {
422
                    $association->setFetchMode(
423
                        constant('Doctrine\ORM\Mapping\FetchMode::' . (string) $manyToOneElement['fetch'])
424
                    );
425
                }
426
427 8
                if (isset($manyToOneElement['inversed-by'])) {
428 2
                    $association->setInversedBy((string) $manyToOneElement['inversed-by']);
429
                }
430
431 8
                $joinColumns = [];
432
433 8
                if (isset($manyToOneElement->{'join-column'})) {
434 7
                    $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($manyToOneElement->{'join-column'});
435 1
                } elseif (isset($manyToOneElement->{'join-columns'})) {
436 1
                    foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
437 1
                        $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
438
                    }
439
                }
440
441 8
                $association->setJoinColumns($joinColumns);
442
443 8
                if (isset($manyToOneElement->cascade)) {
444 4
                    $association->setCascade($this->getCascadeMappings($manyToOneElement->cascade));
445
                }
446
447
                // Evaluate second level cache
448 8
                if (isset($manyToOneElement->cache)) {
449 1
                    $association->setCache(
450 1
                        $this->convertCacheElementToCacheMetadata(
451 1
                            $manyToOneElement->cache,
452 1
                            $metadata,
453 1
                            $association->getName()
454
                        )
455
                    );
456
                }
457
458 8
                $metadata->addProperty($association);
459
            }
460
        }
461
462
        // Evaluate <many-to-many ...> mappings
463 33
        if (isset($xmlRoot->{'many-to-many'})) {
464 13
            foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) {
465 13
                $association  = new Mapping\ManyToManyAssociationMetadata((string) $manyToManyElement['field']);
466 13
                $targetEntity = (string) $manyToManyElement['target-entity'];
467
468 13
                $association->setTargetEntity($targetEntity);
469
470 13
                if (isset($associationIds[$association->getName()])) {
471
                    throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $association->getName());
472
                }
473
474 13
                if (isset($manyToManyElement['fetch'])) {
475 4
                    $association->setFetchMode(
476 4
                        constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $manyToManyElement['fetch']))
477
                    );
478
                }
479
480 13
                if (isset($manyToManyElement['orphan-removal'])) {
481
                    $association->setOrphanRemoval($this->evaluateBoolean($manyToManyElement['orphan-removal']));
482
                }
483
484 13
                if (isset($manyToManyElement['mapped-by'])) {
485 4
                    $association->setMappedBy((string) $manyToManyElement['mapped-by']);
486 4
                    $association->setOwningSide(false);
487 10
                } elseif (isset($manyToManyElement->{'join-table'})) {
488 8
                    if (isset($manyToManyElement['inversed-by'])) {
489 5
                        $association->setInversedBy((string) $manyToManyElement['inversed-by']);
490
                    }
491
492 8
                    $joinTableElement = $manyToManyElement->{'join-table'};
493 8
                    $joinTable        = new Mapping\JoinTableMetadata();
494
495 8
                    if (isset($joinTableElement['name'])) {
496 8
                        $joinTable->setName((string) $joinTableElement['name']);
497
                    }
498
499 8
                    if (isset($joinTableElement['schema'])) {
500
                        $joinTable->setSchema((string) $joinTableElement['schema']);
501
                    }
502
503 8
                    if (isset($joinTableElement->{'join-columns'})) {
504 8
                        foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
505 8
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
506
507 8
                            $joinTable->addJoinColumn($joinColumn);
508
                        }
509
                    }
510
511 8
                    if (isset($joinTableElement->{'inverse-join-columns'})) {
512 8
                        foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) {
513 8
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
514
515 8
                            $joinTable->addInverseJoinColumn($joinColumn);
516
                        }
517
                    }
518
519 8
                    $association->setJoinTable($joinTable);
520
                }
521
522 13
                if (isset($manyToManyElement->cascade)) {
523 8
                    $association->setCascade($this->getCascadeMappings($manyToManyElement->cascade));
524
                }
525
526 13
                if (isset($manyToManyElement->{'order-by'})) {
527
                    $orderBy = [];
528
529
                    foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) {
530
                        $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction'];
531
                    }
532
533
                    $association->setOrderBy($orderBy);
534
                }
535
536 13
                if (isset($manyToManyElement['index-by'])) {
537
                    $association->setIndexedBy((string) $manyToManyElement['index-by']);
538 13
                } elseif (isset($manyToManyElement->{'index-by'})) {
539
                    throw new InvalidArgumentException('<index-by /> is not a valid tag');
540
                }
541
542
                // Evaluate second level cache
543 13
                if (isset($manyToManyElement->cache)) {
544
                    $association->setCache(
545
                        $this->convertCacheElementToCacheMetadata(
546
                            $manyToManyElement->cache,
547
                            $metadata,
548
                            $association->getName()
549
                        )
550
                    );
551
                }
552
553 13
                $metadata->addProperty($association);
554
            }
555
        }
556
557
        // Evaluate association-overrides
558 33
        if (isset($xmlRoot->{'attribute-overrides'})) {
559 2
            foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) {
560 2
                $fieldName = (string) $overrideElement['name'];
561
562 2
                foreach ($overrideElement->field as $fieldElement) {
563 2
                    $fieldMetadata = $this->convertFieldElementToFieldMetadata($fieldElement, $fieldName, false);
564
565 2
                    $metadata->setPropertyOverride($fieldMetadata);
566
                }
567
            }
568
        }
569
570
        // Evaluate association-overrides
571 33
        if (isset($xmlRoot->{'association-overrides'})) {
572 4
            foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) {
573 4
                $fieldName = (string) $overrideElement['name'];
574 4
                $property  = $metadata->getProperty($fieldName);
575
576 4
                if (! $property) {
577
                    throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName);
578
                }
579
580 4
                $existingClass = get_class($property);
581 4
                $override      = new $existingClass($fieldName);
582
583
                // Check for join-columns
584 4
                if (isset($overrideElement->{'join-columns'})) {
585 2
                    $joinColumns = [];
586
587 2
                    foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
588 2
                        $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
589
                    }
590
591 2
                    $override->setJoinColumns($joinColumns);
592
                }
593
594
                // Check for join-table
595 4
                if ($overrideElement->{'join-table'}) {
596 2
                    $joinTableElement = $overrideElement->{'join-table'};
597 2
                    $joinTable        = new Mapping\JoinTableMetadata();
598
599 2
                    if (isset($joinTableElement['name'])) {
600 2
                        $joinTable->setName((string) $joinTableElement['name']);
601
                    }
602
603 2
                    if (isset($joinTableElement['schema'])) {
604
                        $joinTable->setSchema((string) $joinTableElement['schema']);
605
                    }
606
607 2
                    if (isset($joinTableElement->{'join-columns'})) {
608 2
                        foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
609 2
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
610
611 2
                            $joinTable->addJoinColumn($joinColumn);
612
                        }
613
                    }
614
615 2
                    if (isset($joinTableElement->{'inverse-join-columns'})) {
616 2
                        foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) {
617 2
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
618
619 2
                            $joinTable->addInverseJoinColumn($joinColumn);
620
                        }
621
                    }
622
623 2
                    $override->setJoinTable($joinTable);
624
                }
625
626
                // Check for inversed-by
627 4
                if (isset($overrideElement->{'inversed-by'})) {
628 1
                    $override->setInversedBy((string) $overrideElement->{'inversed-by'}['name']);
629
                }
630
631
                // Check for fetch
632 4
                if (isset($overrideElement['fetch'])) {
633 1
                    $override->setFetchMode(
634 1
                        constant('Doctrine\ORM\Mapping\FetchMode::' . (string) $overrideElement['fetch'])
635
                    );
636
                }
637
638 4
                $metadata->setPropertyOverride($override);
639
            }
640
        }
641
642
        // Evaluate <lifecycle-callbacks...>
643 33
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
644 3
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
645 3
                $eventName  = constant(Events::class . '::' . (string) $lifecycleCallback['type']);
646 3
                $methodName = (string) $lifecycleCallback['method'];
647
648 3
                $metadata->addLifecycleCallback($methodName, $eventName);
649
            }
650
        }
651
652
        // Evaluate entity listener
653 33
        if (isset($xmlRoot->{'entity-listeners'})) {
654 3
            foreach ($xmlRoot->{'entity-listeners'}->{'entity-listener'} as $listenerElement) {
655 3
                $listenerClassName = (string) $listenerElement['class'];
656
657 3
                if (! class_exists($listenerClassName)) {
658
                    throw Mapping\MappingException::entityListenerClassNotFound(
659
                        $listenerClassName,
660
                        $metadata->getClassName()
661
                    );
662
                }
663
664 3
                $listenerClass = new ReflectionClass($listenerClassName);
665
666
                // Evaluate the listener using naming convention.
667 3
                if ($listenerElement->count() === 0) {
668
                    /** @var ReflectionMethod $method */
669 1
                    foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
670 1
                        foreach ($this->getMethodCallbacks($method) as $callback) {
671 1
                            $metadata->addEntityListener($callback, $listenerClassName, $method->getName());
672
                        }
673
                    }
674
675 1
                    continue;
676
                }
677
678 2
                foreach ($listenerElement as $callbackElement) {
679 2
                    $eventName  = (string) $callbackElement['type'];
680 2
                    $methodName = (string) $callbackElement['method'];
681
682 2
                    $metadata->addEntityListener($eventName, $listenerClassName, $methodName);
683
                }
684
            }
685
        }
686 33
    }
687
688
    /**
689
     * Parses (nested) option elements.
690
     *
691
     * @param SimpleXMLElement $options The XML element.
692
     *
693
     * @return mixed[] The options array.
694
     */
695 4
    private function parseOptions(SimpleXMLElement $options)
696
    {
697 4
        $array = [];
698
699
        /** @var SimpleXMLElement $option */
700 4
        foreach ($options as $option) {
701 4
            if ($option->count()) {
702 3
                $value = $this->parseOptions($option->children());
703
            } else {
704 4
                $value = (string) $option;
705
            }
706
707 4
            $attributes = $option->attributes();
708
709 4
            if (isset($attributes->name)) {
710 4
                $nameAttribute         = (string) $attributes->name;
711 4
                $array[$nameAttribute] = in_array($nameAttribute, ['unsigned', 'fixed'], true)
712 3
                    ? $this->evaluateBoolean($value)
713 4
                    : $value;
714
            } else {
715
                $array[] = $value;
716
            }
717
        }
718
719 4
        return $array;
720
    }
721
722
    /**
723
     * @return Mapping\FieldMetadata
724
     */
725 31
    private function convertFieldElementToFieldMetadata(SimpleXMLElement $fieldElement, string $fieldName, bool $isVersioned)
726
    {
727 31
        $fieldMetadata = $isVersioned
728 3
            ? new Mapping\VersionFieldMetadata($fieldName)
729 31
            : new Mapping\FieldMetadata($fieldName);
730
731 31
        $fieldMetadata->setType(Type::getType('string'));
732
733 31
        if (isset($fieldElement['type'])) {
734 22
            $fieldMetadata->setType(Type::getType((string) $fieldElement['type']));
735
        }
736
737 31
        if (isset($fieldElement['column'])) {
738 21
            $fieldMetadata->setColumnName((string) $fieldElement['column']);
739
        }
740
741 31
        if (isset($fieldElement['length'])) {
742 7
            $fieldMetadata->setLength((int) $fieldElement['length']);
743
        }
744
745 31
        if (isset($fieldElement['precision'])) {
746 1
            $fieldMetadata->setPrecision((int) $fieldElement['precision']);
747
        }
748
749 31
        if (isset($fieldElement['scale'])) {
750 1
            $fieldMetadata->setScale((int) $fieldElement['scale']);
751
        }
752
753 31
        if (isset($fieldElement['unique'])) {
754 7
            $fieldMetadata->setUnique($this->evaluateBoolean($fieldElement['unique']));
755
        }
756
757 31
        if (isset($fieldElement['nullable'])) {
758 7
            $fieldMetadata->setNullable($this->evaluateBoolean($fieldElement['nullable']));
759
        }
760
761 31
        if (isset($fieldElement['column-definition'])) {
762 4
            $fieldMetadata->setColumnDefinition((string) $fieldElement['column-definition']);
763
        }
764
765 31
        if (isset($fieldElement->options)) {
766 3
            $fieldMetadata->setOptions($this->parseOptions($fieldElement->options->children()));
767
        }
768
769 31
        return $fieldMetadata;
770
    }
771
772
    /**
773
     * Constructs a joinColumn mapping array based on the information
774
     * found in the given SimpleXMLElement.
775
     *
776
     * @param SimpleXMLElement $joinColumnElement The XML element.
777
     *
778
     * @return Mapping\JoinColumnMetadata
779
     */
780 14
    private function convertJoinColumnElementToJoinColumnMetadata(SimpleXMLElement $joinColumnElement)
781
    {
782 14
        $joinColumnMetadata = new Mapping\JoinColumnMetadata();
783
784 14
        $joinColumnMetadata->setColumnName((string) $joinColumnElement['name']);
785 14
        $joinColumnMetadata->setReferencedColumnName((string) $joinColumnElement['referenced-column-name']);
786
787 14
        if (isset($joinColumnElement['column-definition'])) {
788 3
            $joinColumnMetadata->setColumnDefinition((string) $joinColumnElement['column-definition']);
789
        }
790
791 14
        if (isset($joinColumnElement['field-name'])) {
792
            $joinColumnMetadata->setAliasedName((string) $joinColumnElement['field-name']);
793
        }
794
795 14
        if (isset($joinColumnElement['nullable'])) {
796 4
            $joinColumnMetadata->setNullable($this->evaluateBoolean($joinColumnElement['nullable']));
797
        }
798
799 14
        if (isset($joinColumnElement['unique'])) {
800 3
            $joinColumnMetadata->setUnique($this->evaluateBoolean($joinColumnElement['unique']));
801
        }
802
803 14
        if (isset($joinColumnElement['on-delete'])) {
804 3
            $joinColumnMetadata->setOnDelete(strtoupper((string) $joinColumnElement['on-delete']));
805
        }
806
807 14
        return $joinColumnMetadata;
808
    }
809
810
    /**
811
     * Parse the given Cache as CacheMetadata
812
     *
813
     * @param string|null $fieldName
814
     *
815
     * @return Mapping\CacheMetadata
816
     */
817 2
    private function convertCacheElementToCacheMetadata(
818
        SimpleXMLElement $cacheMapping,
819
        Mapping\ClassMetadata $metadata,
820
        $fieldName = null
821
    ) {
822 2
        $baseRegion    = strtolower(str_replace('\\', '_', $metadata->getRootClassName()));
823 2
        $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : '');
824
825 2
        $region = (string) ($cacheMapping['region'] ?? $defaultRegion);
826 2
        $usage  = isset($cacheMapping['usage'])
827 2
            ? constant(sprintf('%s::%s', Mapping\CacheUsage::class, strtoupper((string) $cacheMapping['usage'])))
828 2
            : Mapping\CacheUsage::READ_ONLY;
829
830 2
        return new Mapping\CacheMetadata($usage, $region);
831
    }
832
833
    /**
834
     * Parses the given method.
835
     *
836
     * @return string[]
837
     */
838 1
    private function getMethodCallbacks(ReflectionMethod $method)
839
    {
840
        $events = [
841 1
            Events::prePersist,
842
            Events::postPersist,
843
            Events::preUpdate,
844
            Events::postUpdate,
845
            Events::preRemove,
846
            Events::postRemove,
847
            Events::postLoad,
848
            Events::preFlush,
849
        ];
850
851
        return array_filter($events, static function ($eventName) use ($method) {
852 1
            return $eventName === $method->getName();
853 1
        });
854
    }
855
856
    /**
857
     * Gathers a list of cascade options found in the given cascade element.
858
     *
859
     * @param SimpleXMLElement $cascadeElement The cascade element.
860
     *
861
     * @return string[] The list of cascade options.
862
     */
863 10
    private function getCascadeMappings(SimpleXMLElement $cascadeElement)
864
    {
865 10
        $cascades = [];
866
867
        /** @var SimpleXMLElement $action */
868 10
        foreach ($cascadeElement->children() as $action) {
869
            // According to the JPA specifications, XML uses "cascade-persist"
870
            // instead of "persist". Here, both variations are supported
871
            // because Annotation use "persist" and we want to make sure that
872
            // this driver doesn't need to know anything about the supported
873
            // cascading actions
874 10
            $cascades[] = str_replace('cascade-', '', $action->getName());
875
        }
876
877 10
        return $cascades;
878
    }
879
880
    /**
881
     * {@inheritDoc}
882
     */
883 36
    protected function loadMappingFile($file)
884
    {
885 36
        $result = [];
886
        // Note: we do not use `simplexml_load_file()` because of https://bugs.php.net/bug.php?id=62577
887 36
        $xmlElement = simplexml_load_string(file_get_contents($file));
888
889 36
        if (isset($xmlElement->entity)) {
890 35
            foreach ($xmlElement->entity as $entityElement) {
891 35
                $entityName          = (string) $entityElement['name'];
892 35
                $result[$entityName] = $entityElement;
893
            }
894 6
        } elseif (isset($xmlElement->{'mapped-superclass'})) {
895 5
            foreach ($xmlElement->{'mapped-superclass'} as $mappedSuperClass) {
896 5
                $className          = (string) $mappedSuperClass['name'];
897 5
                $result[$className] = $mappedSuperClass;
898
            }
899 1
        } elseif (isset($xmlElement->embeddable)) {
900
            foreach ($xmlElement->embeddable as $embeddableElement) {
901
                $embeddableName          = (string) $embeddableElement['name'];
902
                $result[$embeddableName] = $embeddableElement;
903
            }
904
        }
905
906 36
        return $result;
907
    }
908
909
    /**
910
     * @param mixed $element
911
     *
912
     * @return bool
913
     */
914 9
    protected function evaluateBoolean($element)
915
    {
916 9
        $flag = (string) $element;
917
918 9
        return $flag === 'true' || $flag === '1';
919
    }
920
}
921