Passed
Pull Request — master (#7725)
by Guilherme
09:09
created

XmlDriver::convertFieldElementToFieldMetadata()   F

Complexity

Conditions 11
Paths 1024

Size

Total Lines 45
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11

Importance

Changes 0
Metric Value
cc 11
eloc 23
nc 1024
nop 3
dl 0
loc 45
rs 3.15
c 0
b 0
f 0
ccs 24
cts 24
cp 1
crap 11

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
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 42
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
39
    {
40 42
        parent::__construct($locator, $fileExtension);
41 42
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46 37
    public function loadMetadataForClass(
47
        string $className,
48
        Mapping\ClassMetadata $metadata,
49
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
50
    ) {
51
        /** @var SimpleXMLElement $xmlRoot */
52 37
        $xmlRoot = $this->getElement($className);
53
54 35
        if ($xmlRoot->getName() === 'entity') {
55 35
            if (isset($xmlRoot['repository-class'])) {
56
                $metadata->setCustomRepositoryClassName((string) $xmlRoot['repository-class']);
57
            }
58
59 35
            if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) {
60 35
                $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 35
        $parent = $metadata->getParent();
76
77 35
        if ($parent && $parent->inheritanceType === Mapping\InheritanceType::SINGLE_TABLE) {
78 2
            $metadata->setTable($parent->table);
79
        } else {
80 35
            $namingStrategy = $metadataBuildingContext->getNamingStrategy();
81 35
            $tableMetadata  = new Mapping\TableMetadata();
82
83 35
            $tableMetadata->setName($namingStrategy->classToTableName($metadata->getClassName()));
84
85
            // Evaluate <entity...> attributes
86 35
            if (isset($xmlRoot['table'])) {
87 13
                $tableMetadata->setName((string) $xmlRoot['table']);
88
            }
89
90 35
            if (isset($xmlRoot['schema'])) {
91 2
                $tableMetadata->setSchema((string) $xmlRoot['schema']);
92
            }
93
94 35
            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 35
            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 35
            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 35
            $metadata->setTable($tableMetadata);
140
        }
141
142
        // Evaluate second level cache
143 35
        if (isset($xmlRoot->cache)) {
144 2
            $cache = $this->convertCacheElementToCacheMetadata($xmlRoot->cache, $metadata);
145
146 2
            $metadata->setCache($cache);
147
        }
148
149 35
        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 35
        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 35
        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 35
        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 35
        $associationIds = [];
238
239 35
        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 35
        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 35
        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 35
        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 34
        if (isset($xmlRoot->{'many-to-many'})) {
464 14
            foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) {
465 14
                $association  = new Mapping\ManyToManyAssociationMetadata((string) $manyToManyElement['field']);
466 14
                $targetEntity = (string) $manyToManyElement['target-entity'];
467
468 14
                $association->setTargetEntity($targetEntity);
469
470 14
                if (isset($associationIds[$association->getName()])) {
471
                    throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $association->getName());
472
                }
473
474 14
                if (isset($manyToManyElement['fetch'])) {
475 4
                    $association->setFetchMode(
476 4
                        constant(sprintf('%s::%s', Mapping\FetchMode::class, (string) $manyToManyElement['fetch']))
477
                    );
478
                }
479
480 14
                if (isset($manyToManyElement['orphan-removal'])) {
481
                    $association->setOrphanRemoval($this->evaluateBoolean($manyToManyElement['orphan-removal']));
482
                }
483
484 14
                if (isset($manyToManyElement['mapped-by'])) {
485 5
                    $association->setMappedBy((string) $manyToManyElement['mapped-by']);
486 5
                    $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 14
                if (isset($manyToManyElement->cascade)) {
523 8
                    $association->setCascade($this->getCascadeMappings($manyToManyElement->cascade));
524
                }
525
526 14
                if (isset($manyToManyElement->{'order-by'})) {
527 1
                    $orderBy = [];
528
529 1
                    foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) {
530 1
                        $orderBy[(string) $orderByField['name']] = isset($orderByField['direction'])
531
                            ? (string) $orderByField['direction']
532 1
                            : Criteria::ASC;
533
                    }
534
535 1
                    $association->setOrderBy($orderBy);
536
                }
537
538 14
                if (isset($manyToManyElement['index-by'])) {
539
                    $association->setIndexedBy((string) $manyToManyElement['index-by']);
540 14
                } elseif (isset($manyToManyElement->{'index-by'})) {
541
                    throw new InvalidArgumentException('<index-by /> is not a valid tag');
542
                }
543
544
                // Evaluate second level cache
545 14
                if (isset($manyToManyElement->cache)) {
546
                    $association->setCache(
547
                        $this->convertCacheElementToCacheMetadata(
548
                            $manyToManyElement->cache,
549
                            $metadata,
550
                            $association->getName()
551
                        )
552
                    );
553
                }
554
555 14
                $metadata->addProperty($association);
556
            }
557
        }
558
559
        // Evaluate association-overrides
560 34
        if (isset($xmlRoot->{'attribute-overrides'})) {
561 2
            foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) {
562 2
                $fieldName = (string) $overrideElement['name'];
563
564 2
                foreach ($overrideElement->field as $fieldElement) {
565 2
                    $fieldMetadata = $this->convertFieldElementToFieldMetadata($fieldElement, $fieldName, false);
566
567 2
                    $metadata->setPropertyOverride($fieldMetadata);
568
                }
569
            }
570
        }
571
572
        // Evaluate association-overrides
573 34
        if (isset($xmlRoot->{'association-overrides'})) {
574 4
            foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) {
575 4
                $fieldName = (string) $overrideElement['name'];
576 4
                $property  = $metadata->getProperty($fieldName);
577
578 4
                if (! $property) {
579
                    throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName);
580
                }
581
582 4
                $existingClass = get_class($property);
583 4
                $override      = new $existingClass($fieldName);
584
585
                // Check for join-columns
586 4
                if (isset($overrideElement->{'join-columns'})) {
587 2
                    $joinColumns = [];
588
589 2
                    foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
590 2
                        $joinColumns[] = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
591
                    }
592
593 2
                    $override->setJoinColumns($joinColumns);
594
                }
595
596
                // Check for join-table
597 4
                if ($overrideElement->{'join-table'}) {
598 2
                    $joinTableElement = $overrideElement->{'join-table'};
599 2
                    $joinTable        = new Mapping\JoinTableMetadata();
600
601 2
                    if (isset($joinTableElement['name'])) {
602 2
                        $joinTable->setName((string) $joinTableElement['name']);
603
                    }
604
605 2
                    if (isset($joinTableElement['schema'])) {
606
                        $joinTable->setSchema((string) $joinTableElement['schema']);
607
                    }
608
609 2
                    if (isset($joinTableElement->{'join-columns'})) {
610 2
                        foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
611 2
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
612
613 2
                            $joinTable->addJoinColumn($joinColumn);
614
                        }
615
                    }
616
617 2
                    if (isset($joinTableElement->{'inverse-join-columns'})) {
618 2
                        foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) {
619 2
                            $joinColumn = $this->convertJoinColumnElementToJoinColumnMetadata($joinColumnElement);
620
621 2
                            $joinTable->addInverseJoinColumn($joinColumn);
622
                        }
623
                    }
624
625 2
                    $override->setJoinTable($joinTable);
626
                }
627
628
                // Check for inversed-by
629 4
                if (isset($overrideElement->{'inversed-by'})) {
630 1
                    $override->setInversedBy((string) $overrideElement->{'inversed-by'}['name']);
631
                }
632
633
                // Check for fetch
634 4
                if (isset($overrideElement['fetch'])) {
635 1
                    $override->setFetchMode(
636 1
                        constant('Doctrine\ORM\Mapping\FetchMode::' . (string) $overrideElement['fetch'])
637
                    );
638
                }
639
640 4
                $metadata->setPropertyOverride($override);
641
            }
642
        }
643
644
        // Evaluate <lifecycle-callbacks...>
645 34
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
646 3
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
647 3
                $eventName  = constant(Events::class . '::' . (string) $lifecycleCallback['type']);
648 3
                $methodName = (string) $lifecycleCallback['method'];
649
650 3
                $metadata->addLifecycleCallback($methodName, $eventName);
651
            }
652
        }
653
654
        // Evaluate entity listener
655 34
        if (isset($xmlRoot->{'entity-listeners'})) {
656 3
            foreach ($xmlRoot->{'entity-listeners'}->{'entity-listener'} as $listenerElement) {
657 3
                $listenerClassName = (string) $listenerElement['class'];
658
659 3
                if (! class_exists($listenerClassName)) {
660
                    throw Mapping\MappingException::entityListenerClassNotFound(
661
                        $listenerClassName,
662
                        $metadata->getClassName()
663
                    );
664
                }
665
666 3
                $listenerClass = new ReflectionClass($listenerClassName);
667
668
                // Evaluate the listener using naming convention.
669 3
                if ($listenerElement->count() === 0) {
670
                    /** @var ReflectionMethod $method */
671 1
                    foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
672 1
                        foreach ($this->getMethodCallbacks($method) as $callback) {
673 1
                            $metadata->addEntityListener($callback, $listenerClassName, $method->getName());
674
                        }
675
                    }
676
677 1
                    continue;
678
                }
679
680 2
                foreach ($listenerElement as $callbackElement) {
681 2
                    $eventName  = (string) $callbackElement['type'];
682 2
                    $methodName = (string) $callbackElement['method'];
683
684 2
                    $metadata->addEntityListener($eventName, $listenerClassName, $methodName);
685
                }
686
            }
687
        }
688 34
    }
689
690
    /**
691
     * Parses (nested) option elements.
692
     *
693
     * @param SimpleXMLElement $options The XML element.
694
     *
695
     * @return mixed[] The options array.
696
     */
697 4
    private function parseOptions(SimpleXMLElement $options)
698
    {
699 4
        $array = [];
700
701
        /** @var SimpleXMLElement $option */
702 4
        foreach ($options as $option) {
703 4
            if ($option->count()) {
704 3
                $value = $this->parseOptions($option->children());
705
            } else {
706 4
                $value = (string) $option;
707
            }
708
709 4
            $attributes = $option->attributes();
710
711 4
            if (isset($attributes->name)) {
712 4
                $nameAttribute         = (string) $attributes->name;
713 4
                $array[$nameAttribute] = in_array($nameAttribute, ['unsigned', 'fixed'], true)
714 3
                    ? $this->evaluateBoolean($value)
715 4
                    : $value;
716
            } else {
717
                $array[] = $value;
718
            }
719
        }
720
721 4
        return $array;
722
    }
723
724
    /**
725
     * @return Mapping\FieldMetadata
726
     */
727 31
    private function convertFieldElementToFieldMetadata(SimpleXMLElement $fieldElement, string $fieldName, bool $isVersioned)
728
    {
729 31
        $fieldMetadata = $isVersioned
730 3
            ? new Mapping\VersionFieldMetadata($fieldName)
731 31
            : new Mapping\FieldMetadata($fieldName);
732
733 31
        $fieldMetadata->setType(Type::getType('string'));
734
735 31
        if (isset($fieldElement['type'])) {
736 22
            $fieldMetadata->setType(Type::getType((string) $fieldElement['type']));
737
        }
738
739 31
        if (isset($fieldElement['column'])) {
740 21
            $fieldMetadata->setColumnName((string) $fieldElement['column']);
741
        }
742
743 31
        if (isset($fieldElement['length'])) {
744 7
            $fieldMetadata->setLength((int) $fieldElement['length']);
745
        }
746
747 31
        if (isset($fieldElement['precision'])) {
748 1
            $fieldMetadata->setPrecision((int) $fieldElement['precision']);
749
        }
750
751 31
        if (isset($fieldElement['scale'])) {
752 1
            $fieldMetadata->setScale((int) $fieldElement['scale']);
753
        }
754
755 31
        if (isset($fieldElement['unique'])) {
756 7
            $fieldMetadata->setUnique($this->evaluateBoolean($fieldElement['unique']));
757
        }
758
759 31
        if (isset($fieldElement['nullable'])) {
760 7
            $fieldMetadata->setNullable($this->evaluateBoolean($fieldElement['nullable']));
761
        }
762
763 31
        if (isset($fieldElement['column-definition'])) {
764 4
            $fieldMetadata->setColumnDefinition((string) $fieldElement['column-definition']);
765
        }
766
767 31
        if (isset($fieldElement->options)) {
768 3
            $fieldMetadata->setOptions($this->parseOptions($fieldElement->options->children()));
769
        }
770
771 31
        return $fieldMetadata;
772
    }
773
774
    /**
775
     * Constructs a joinColumn mapping array based on the information
776
     * found in the given SimpleXMLElement.
777
     *
778
     * @param SimpleXMLElement $joinColumnElement The XML element.
779
     *
780
     * @return Mapping\JoinColumnMetadata
781
     */
782 14
    private function convertJoinColumnElementToJoinColumnMetadata(SimpleXMLElement $joinColumnElement)
783
    {
784 14
        $joinColumnMetadata = new Mapping\JoinColumnMetadata();
785
786 14
        $joinColumnMetadata->setColumnName((string) $joinColumnElement['name']);
787 14
        $joinColumnMetadata->setReferencedColumnName((string) $joinColumnElement['referenced-column-name']);
788
789 14
        if (isset($joinColumnElement['column-definition'])) {
790 3
            $joinColumnMetadata->setColumnDefinition((string) $joinColumnElement['column-definition']);
791
        }
792
793 14
        if (isset($joinColumnElement['field-name'])) {
794
            $joinColumnMetadata->setAliasedName((string) $joinColumnElement['field-name']);
795
        }
796
797 14
        if (isset($joinColumnElement['nullable'])) {
798 4
            $joinColumnMetadata->setNullable($this->evaluateBoolean($joinColumnElement['nullable']));
799
        }
800
801 14
        if (isset($joinColumnElement['unique'])) {
802 3
            $joinColumnMetadata->setUnique($this->evaluateBoolean($joinColumnElement['unique']));
803
        }
804
805 14
        if (isset($joinColumnElement['on-delete'])) {
806 3
            $joinColumnMetadata->setOnDelete(strtoupper((string) $joinColumnElement['on-delete']));
807
        }
808
809 14
        return $joinColumnMetadata;
810
    }
811
812
    /**
813
     * Parse the given Cache as CacheMetadata
814
     *
815
     * @param string|null $fieldName
816
     *
817
     * @return Mapping\CacheMetadata
818
     */
819 2
    private function convertCacheElementToCacheMetadata(
820
        SimpleXMLElement $cacheMapping,
821
        Mapping\ClassMetadata $metadata,
822
        $fieldName = null
823
    ) {
824 2
        $baseRegion    = strtolower(str_replace('\\', '_', $metadata->getRootClassName()));
825 2
        $defaultRegion = $baseRegion . ($fieldName ? '__' . $fieldName : '');
826
827 2
        $region = (string) ($cacheMapping['region'] ?? $defaultRegion);
828 2
        $usage  = isset($cacheMapping['usage'])
829 2
            ? constant(sprintf('%s::%s', Mapping\CacheUsage::class, strtoupper((string) $cacheMapping['usage'])))
830 2
            : Mapping\CacheUsage::READ_ONLY;
831
832 2
        return new Mapping\CacheMetadata($usage, $region);
833
    }
834
835
    /**
836
     * Parses the given method.
837
     *
838
     * @return string[]
839
     */
840 1
    private function getMethodCallbacks(ReflectionMethod $method)
841
    {
842
        $events = [
843 1
            Events::prePersist,
844
            Events::postPersist,
845
            Events::preUpdate,
846
            Events::postUpdate,
847
            Events::preRemove,
848
            Events::postRemove,
849
            Events::postLoad,
850
            Events::preFlush,
851
        ];
852
853
        return array_filter($events, static function ($eventName) use ($method) {
854 1
            return $eventName === $method->getName();
855 1
        });
856
    }
857
858
    /**
859
     * Gathers a list of cascade options found in the given cascade element.
860
     *
861
     * @param SimpleXMLElement $cascadeElement The cascade element.
862
     *
863
     * @return string[] The list of cascade options.
864
     */
865 10
    private function getCascadeMappings(SimpleXMLElement $cascadeElement)
866
    {
867 10
        $cascades = [];
868
869
        /** @var SimpleXMLElement $action */
870 10
        foreach ($cascadeElement->children() as $action) {
871
            // According to the JPA specifications, XML uses "cascade-persist"
872
            // instead of "persist". Here, both variations are supported
873
            // because Annotation use "persist" and we want to make sure that
874
            // this driver doesn't need to know anything about the supported
875
            // cascading actions
876 10
            $cascades[] = str_replace('cascade-', '', $action->getName());
877
        }
878
879 10
        return $cascades;
880
    }
881
882
    /**
883
     * {@inheritDoc}
884
     */
885 37
    protected function loadMappingFile($file)
886
    {
887 37
        $result = [];
888
        // Note: we do not use `simplexml_load_file()` because of https://bugs.php.net/bug.php?id=62577
889 37
        $xmlElement = simplexml_load_string(file_get_contents($file));
890
891 37
        if (isset($xmlElement->entity)) {
892 36
            foreach ($xmlElement->entity as $entityElement) {
893 36
                $entityName          = (string) $entityElement['name'];
894 36
                $result[$entityName] = $entityElement;
895
            }
896 6
        } elseif (isset($xmlElement->{'mapped-superclass'})) {
897 5
            foreach ($xmlElement->{'mapped-superclass'} as $mappedSuperClass) {
898 5
                $className          = (string) $mappedSuperClass['name'];
899 5
                $result[$className] = $mappedSuperClass;
900
            }
901 1
        } elseif (isset($xmlElement->embeddable)) {
902
            foreach ($xmlElement->embeddable as $embeddableElement) {
903
                $embeddableName          = (string) $embeddableElement['name'];
904
                $result[$embeddableName] = $embeddableElement;
905
            }
906
        }
907
908 37
        return $result;
909
    }
910
911
    /**
912
     * @param mixed $element
913
     *
914
     * @return bool
915
     */
916 9
    protected function evaluateBoolean($element)
917
    {
918 9
        $flag = (string) $element;
919
920 9
        return $flag === 'true' || $flag === '1';
921
    }
922
}
923