Passed
Pull Request — 2.8.x (#8022)
by Benjamin
08:51
created

XmlDriver   F

Complexity

Total Complexity 182

Size/Duplication

Total Lines 844
Duplicated Lines 0 %

Test Coverage

Coverage 95.53%

Importance

Changes 0
Metric Value
wmc 182
eloc 413
c 0
b 0
f 0
dl 0
loc 844
ccs 385
cts 403
cp 0.9553
rs 2

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A joinColumnToArray() 0 24 5
A evaluateBoolean() 0 5 2
F loadMetadataForClass() 0 612 142
B loadMappingFile() 0 24 7
F columnToArray() 0 47 12
A _getCascadeMappings() 0 14 2
A cacheToArray() 0 16 6
A _parseOptions() 0 25 5

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
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM\Mapping\Driver;
21
22
use Doctrine\Common\Collections\Criteria;
23
use SimpleXMLElement;
24
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
25
use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder;
26
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
27
use Doctrine\ORM\Mapping\MappingException;
28
use Doctrine\ORM\Mapping\ClassMetadata as Metadata;
29
30
/**
31
 * XmlDriver is a metadata driver that enables mapping through XML files.
32
 *
33
 * @license 	http://www.opensource.org/licenses/mit-license.php MIT
34
 * @link    	www.doctrine-project.org
35
 * @since   	2.0
36
 * @author		Benjamin Eberlei <[email protected]>
37
 * @author		Guilherme Blanco <[email protected]>
38
 * @author      Jonathan H. Wage <[email protected]>
39
 * @author      Roman Borschel <[email protected]>
40
 */
41
class XmlDriver extends FileDriver
42
{
43
    const DEFAULT_FILE_EXTENSION = '.dcm.xml';
44
45
    /**
46
     * {@inheritDoc}
47
     */
48 46
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
49
    {
50 46
        parent::__construct($locator, $fileExtension);
51 46
    }
52
53
    /**
54
     * {@inheritDoc}
55
     */
56 41
    public function loadMetadataForClass($className, ClassMetadata $metadata)
57
    {
58
        /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */
59
        /* @var $xmlRoot SimpleXMLElement */
60 41
        $xmlRoot = $this->getElement($className);
61
62 39
        if ($xmlRoot->getName() == 'entity') {
63 38
            if (isset($xmlRoot['repository-class'])) {
64
                $metadata->setCustomRepositoryClass((string) $xmlRoot['repository-class']);
65
            }
66 38
            if (isset($xmlRoot['read-only']) && $this->evaluateBoolean($xmlRoot['read-only'])) {
67 38
                $metadata->markReadOnly();
68
            }
69 8
        } else if ($xmlRoot->getName() == 'mapped-superclass') {
70 5
            $metadata->setCustomRepositoryClass(
71 5
                isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null
72
            );
73 5
            $metadata->isMappedSuperclass = true;
0 ignored issues
show
Bug introduced by
Accessing isMappedSuperclass on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
74 3
        } else if ($xmlRoot->getName() == 'embeddable') {
75 3
            $metadata->isEmbeddedClass = true;
0 ignored issues
show
Bug introduced by
Accessing isEmbeddedClass on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
76
        } else {
77
            throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
78
        }
79
80
        // Evaluate <entity...> attributes
81 39
        $primaryTable = [];
82
83 39
        if (isset($xmlRoot['table'])) {
84 16
            $primaryTable['name'] = (string) $xmlRoot['table'];
85
        }
86
87 39
        if (isset($xmlRoot['schema'])) {
88 1
            $primaryTable['schema'] = (string) $xmlRoot['schema'];
89
        }
90
91 39
        $metadata->setPrimaryTable($primaryTable);
92
93
        // Evaluate second level cache
94 39
        if (isset($xmlRoot->cache)) {
95 2
            $metadata->enableCache($this->cacheToArray($xmlRoot->cache));
96
        }
97
98
        // Evaluate named queries
99 39
        if (isset($xmlRoot->{'named-queries'})) {
100 4
            foreach ($xmlRoot->{'named-queries'}->{'named-query'} as $namedQueryElement) {
101 4
                $metadata->addNamedQuery(
102
                    [
103 4
                        'name'  => (string) $namedQueryElement['name'],
104 4
                        'query' => (string) $namedQueryElement['query']
105
                    ]
106
                );
107
            }
108
        }
109
110
        // Evaluate native named queries
111 39
        if (isset($xmlRoot->{'named-native-queries'})) {
112 3
            foreach ($xmlRoot->{'named-native-queries'}->{'named-native-query'} as $nativeQueryElement) {
113 3
                $metadata->addNamedNativeQuery(
114
                    [
115 3
                        'name'              => isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null,
116 3
                        'query'             => isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null,
117 3
                        'resultClass'       => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null,
118 3
                        'resultSetMapping'  => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null,
119
                    ]
120
                );
121
            }
122
        }
123
124
        // Evaluate sql result set mapping
125 39
        if (isset($xmlRoot->{'sql-result-set-mappings'})) {
126 3
            foreach ($xmlRoot->{'sql-result-set-mappings'}->{'sql-result-set-mapping'} as $rsmElement) {
127 3
                $entities   = [];
128 3
                $columns    = [];
129 3
                foreach ($rsmElement as $entityElement) {
130
                    //<entity-result/>
131 3
                    if (isset($entityElement['entity-class'])) {
132
                        $entityResult = [
133 3
                            'fields'                => [],
134 3
                            'entityClass'           => (string) $entityElement['entity-class'],
135 3
                            'discriminatorColumn'   => isset($entityElement['discriminator-column']) ? (string) $entityElement['discriminator-column'] : null,
136
                        ];
137
138 3
                        foreach ($entityElement as $fieldElement) {
139 3
                            $entityResult['fields'][] = [
140 3
                                'name'      => isset($fieldElement['name']) ? (string) $fieldElement['name'] : null,
141 3
                                'column'    => isset($fieldElement['column']) ? (string) $fieldElement['column'] : null,
142
                            ];
143
                        }
144
145 3
                        $entities[] = $entityResult;
146
                    }
147
148
                    //<column-result/>
149 3
                    if (isset($entityElement['name'])) {
150 3
                        $columns[] = [
151 3
                            'name' => (string) $entityElement['name'],
152
                        ];
153
                    }
154
                }
155
156 3
                $metadata->addSqlResultSetMapping(
157
                    [
158 3
                        'name'          => (string) $rsmElement['name'],
159 3
                        'entities'      => $entities,
160 3
                        'columns'       => $columns
161
                    ]
162
                );
163
            }
164
        }
165
166 39
        if (isset($xmlRoot['inheritance-type'])) {
167 10
            $inheritanceType = (string) $xmlRoot['inheritance-type'];
168 10
            $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType));
169
170 10
            if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) {
0 ignored issues
show
Bug introduced by
Accessing inheritanceType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
171
                // Evaluate <discriminator-column...>
172 10
                if (isset($xmlRoot->{'discriminator-column'})) {
173 7
                    $discrColumn = $xmlRoot->{'discriminator-column'};
174 7
                    $metadata->setDiscriminatorColumn(
175
                        [
176 7
                            'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null,
177 7
                            'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string',
178 7
                            'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255,
179 7
                            'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null
180
                        ]
181
                    );
182
                } else {
183 6
                    $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]);
184
                }
185
186
                // Evaluate <discriminator-map...>
187 10
                if (isset($xmlRoot->{'discriminator-map'})) {
188 10
                    $map = [];
189 10
                    foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) {
190 10
                        $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class'];
191
                    }
192 10
                    $metadata->setDiscriminatorMap($map);
193
                }
194
            }
195
        }
196
197
198
        // Evaluate <change-tracking-policy...>
199 39
        if (isset($xmlRoot['change-tracking-policy'])) {
200
            $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_'
201
                . strtoupper((string) $xmlRoot['change-tracking-policy'])));
202
        }
203
204
        // Evaluate <indexes...>
205 39
        if (isset($xmlRoot->indexes)) {
206 4
            $metadata->table['indexes'] = [];
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
207 4
            foreach ($xmlRoot->indexes->index as $indexXml) {
208 4
                $index = ['columns' => explode(',', (string) $indexXml['columns'])];
209
210 4
                if (isset($indexXml['flags'])) {
211 1
                    $index['flags'] = explode(',', (string) $indexXml['flags']);
212
                }
213
214 4
                if (isset($indexXml->options)) {
215 1
                    $index['options'] = $this->_parseOptions($indexXml->options->children());
216
                }
217
218 4
                if (isset($indexXml['name'])) {
219 3
                    $metadata->table['indexes'][(string) $indexXml['name']] = $index;
220
                } else {
221 4
                    $metadata->table['indexes'][] = $index;
222
                }
223
            }
224
        }
225
226
        // Evaluate <unique-constraints..>
227 39
        if (isset($xmlRoot->{'unique-constraints'})) {
228 3
            $metadata->table['uniqueConstraints'] = [];
229 3
            foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $uniqueXml) {
230 3
                $unique = ['columns' => explode(',', (string) $uniqueXml['columns'])];
231
232 3
                if (isset($uniqueXml->options)) {
233 3
                    $unique['options'] = $this->_parseOptions($uniqueXml->options->children());
234
                }
235
236 3
                if (isset($uniqueXml['name'])) {
237 3
                    $metadata->table['uniqueConstraints'][(string) $uniqueXml['name']] = $unique;
238
                } else {
239 3
                    $metadata->table['uniqueConstraints'][] = $unique;
240
                }
241
            }
242
        }
243
244 39
        if (isset($xmlRoot->options)) {
245 5
            $metadata->table['options'] = $this->_parseOptions($xmlRoot->options->children());
246
        }
247
248
        // The mapping assignment is done in 2 times as a bug might occurs on some php/xml lib versions
249
        // The internal SimpleXmlIterator get resetted, to this generate a duplicate field exception
250 39
        $mappings = [];
251
        // Evaluate <field ...> mappings
252 39
        if (isset($xmlRoot->field)) {
253 24
            foreach ($xmlRoot->field as $fieldMapping) {
254 24
                $mapping = $this->columnToArray($fieldMapping);
255
256 24
                if (isset($mapping['version'])) {
257 3
                    $metadata->setVersionMapping($mapping);
258 3
                    unset($mapping['version']);
259
                }
260
261 24
                $metadata->mapField($mapping);
262
            }
263
        }
264
265 39
        if (isset($xmlRoot->embedded)) {
266 3
            foreach ($xmlRoot->embedded as $embeddedMapping) {
267 3
                $columnPrefix = isset($embeddedMapping['column-prefix'])
268 3
                    ? (string) $embeddedMapping['column-prefix']
269 3
                    : null;
270
271 3
                $useColumnPrefix = isset($embeddedMapping['use-column-prefix'])
272 2
                    ? $this->evaluateBoolean($embeddedMapping['use-column-prefix'])
273 3
                    : true;
274
275 3
                $nullable = isset($embeddedMapping['nullable'])
276
                    ? $this->evaluateBoolean($embeddedMapping['nullable'])
277 3
                    : null;
278
279
                $mapping = [
280 3
                    'fieldName' => (string) $embeddedMapping['name'],
281 3
                    'class' => (string) $embeddedMapping['class'],
282 3
                    'columnPrefix' => $useColumnPrefix ? $columnPrefix : false,
283 3
                    'nullable' => $nullable,
284
                ];
285
286 3
                $metadata->mapEmbedded($mapping);
287
            }
288
        }
289
290 39
        foreach ($mappings as $mapping) {
291
            if (isset($mapping['version'])) {
292
                $metadata->setVersionMapping($mapping);
293
            }
294
295
            $metadata->mapField($mapping);
296
        }
297
298
        // Evaluate <id ...> mappings
299 39
        $associationIds = [];
300 39
        foreach ($xmlRoot->id as $idElement) {
301 34
            if (isset($idElement['association-key']) && $this->evaluateBoolean($idElement['association-key'])) {
302 2
                $associationIds[(string) $idElement['name']] = true;
303 2
                continue;
304
            }
305
306
            $mapping = [
307 33
                'id' => true,
308 33
                'fieldName' => (string) $idElement['name']
309
            ];
310
311 33
            if (isset($idElement['type'])) {
312 21
                $mapping['type'] = (string) $idElement['type'];
313
            }
314
315 33
            if (isset($idElement['length'])) {
316 3
                $mapping['length'] = (string) $idElement['length'];
317
            }
318
319 33
            if (isset($idElement['column'])) {
320 24
                $mapping['columnName'] = (string) $idElement['column'];
321
            }
322
323 33
            if (isset($idElement['column-definition'])) {
324 1
                $mapping['columnDefinition'] = (string) $idElement['column-definition'];
325
            }
326
327 33
            if (isset($idElement->options)) {
328 3
                $mapping['options'] = $this->_parseOptions($idElement->options->children());
329
            }
330
331 33
            $metadata->mapField($mapping);
332
333 33
            if (isset($idElement->generator)) {
334 32
                $strategy = isset($idElement->generator['strategy']) ?
335 32
                        (string) $idElement->generator['strategy'] : 'AUTO';
336 32
                $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_'
337 32
                    . $strategy));
338
            }
339
340
            // Check for SequenceGenerator/TableGenerator definition
341 33
            if (isset($idElement->{'sequence-generator'})) {
342 3
                $seqGenerator = $idElement->{'sequence-generator'};
343 3
                $metadata->setSequenceGeneratorDefinition(
344
                    [
345 3
                        'sequenceName' => (string) $seqGenerator['sequence-name'],
346 3
                        'allocationSize' => (string) $seqGenerator['allocation-size'],
347 3
                        'initialValue' => (string) $seqGenerator['initial-value']
348
                    ]
349
                );
350 30
            } else if (isset($idElement->{'custom-id-generator'})) {
351 2
                $customGenerator = $idElement->{'custom-id-generator'};
352 2
                $metadata->setCustomGeneratorDefinition(
353
                    [
354 2
                        'class' => (string) $customGenerator['class']
355
                    ]
356
                );
357 28
            } else if (isset($idElement->{'table-generator'})) {
358 33
                throw MappingException::tableIdGeneratorNotImplemented($className);
359
            }
360
        }
361
362
        // Evaluate <one-to-one ...> mappings
363 39
        if (isset($xmlRoot->{'one-to-one'})) {
364 8
            foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) {
365
                $mapping = [
366 8
                    'fieldName' => (string) $oneToOneElement['field'],
367 8
                    'targetEntity' => (string) $oneToOneElement['target-entity']
368
                ];
369
370 8
                if (isset($associationIds[$mapping['fieldName']])) {
371
                    $mapping['id'] = true;
372
                }
373
374 8
                if (isset($oneToOneElement['fetch'])) {
375 2
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $oneToOneElement['fetch']);
376
                }
377
378 8
                if (isset($oneToOneElement['mapped-by'])) {
379 2
                    $mapping['mappedBy'] = (string) $oneToOneElement['mapped-by'];
380
                } else {
381 8
                    if (isset($oneToOneElement['inversed-by'])) {
382 8
                        $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by'];
383
                    }
384 8
                    $joinColumns = [];
385
386 8
                    if (isset($oneToOneElement->{'join-column'})) {
387 7
                        $joinColumns[] = $this->joinColumnToArray($oneToOneElement->{'join-column'});
388 1
                    } else if (isset($oneToOneElement->{'join-columns'})) {
389 1
                        foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
390 1
                            $joinColumns[] = $this->joinColumnToArray($joinColumnElement);
391
                        }
392
                    }
393
394 8
                    $mapping['joinColumns'] = $joinColumns;
395
                }
396
397 8
                if (isset($oneToOneElement->cascade)) {
398 6
                    $mapping['cascade'] = $this->_getCascadeMappings($oneToOneElement->cascade);
399
                }
400
401 8
                if (isset($oneToOneElement['orphan-removal'])) {
402 3
                    $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToOneElement['orphan-removal']);
403
                }
404
405
                // Evaluate second level cache
406 8
                if (isset($oneToOneElement->cache)) {
407
                    $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToOneElement->cache));
0 ignored issues
show
Bug introduced by
The method getAssociationCacheDefaults() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean getAssociationNames()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

407
                    /** @scrutinizer ignore-call */ 
408
                    $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToOneElement->cache));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
408
                }
409
410 8
                $metadata->mapOneToOne($mapping);
411
            }
412
        }
413
414
        // Evaluate <one-to-many ...> mappings
415 39
        if (isset($xmlRoot->{'one-to-many'})) {
416 9
            foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) {
417
                $mapping = [
418 9
                    'fieldName' => (string) $oneToManyElement['field'],
419 9
                    'targetEntity' => (string) $oneToManyElement['target-entity'],
420 9
                    'mappedBy' => (string) $oneToManyElement['mapped-by']
421
                ];
422
423 9
                if (isset($oneToManyElement['fetch'])) {
424 2
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $oneToManyElement['fetch']);
425
                }
426
427 9
                if (isset($oneToManyElement->cascade)) {
428 6
                    $mapping['cascade'] = $this->_getCascadeMappings($oneToManyElement->cascade);
429
                }
430
431 9
                if (isset($oneToManyElement['orphan-removal'])) {
432 6
                    $mapping['orphanRemoval'] = $this->evaluateBoolean($oneToManyElement['orphan-removal']);
433
                }
434
435 9
                if (isset($oneToManyElement->{'order-by'})) {
436 7
                    $orderBy = [];
437 7
                    foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) {
438 7
                        $orderBy[(string) $orderByField['name']] = isset($orderByField['direction'])
439 6
                            ? (string) $orderByField['direction']
440 7
                            : Criteria::ASC
441
                        ;
442
                    }
443 7
                    $mapping['orderBy'] = $orderBy;
444
                }
445
446 9
                if (isset($oneToManyElement['index-by'])) {
447 3
                    $mapping['indexBy'] = (string) $oneToManyElement['index-by'];
448 6
                } else if (isset($oneToManyElement->{'index-by'})) {
449
                    throw new \InvalidArgumentException("<index-by /> is not a valid tag");
450
                }
451
452
                // Evaluate second level cache
453 9
                if (isset($oneToManyElement->cache)) {
454 1
                    $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($oneToManyElement->cache));
455
                }
456
457 9
                $metadata->mapOneToMany($mapping);
458
            }
459
        }
460
461
        // Evaluate <many-to-one ...> mappings
462 39
        if (isset($xmlRoot->{'many-to-one'})) {
463 8
            foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) {
464
                $mapping = [
465 8
                    'fieldName' => (string) $manyToOneElement['field'],
466 8
                    'targetEntity' => (string) $manyToOneElement['target-entity']
467
                ];
468
469 8
                if (isset($associationIds[$mapping['fieldName']])) {
470 2
                    $mapping['id'] = true;
471
                }
472
473 8
                if (isset($manyToOneElement['fetch'])) {
474 1
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $manyToOneElement['fetch']);
475
                }
476
477 8
                if (isset($manyToOneElement['inversed-by'])) {
478 1
                    $mapping['inversedBy'] = (string) $manyToOneElement['inversed-by'];
479
                }
480
481 8
                $joinColumns = [];
482
483 8
                if (isset($manyToOneElement->{'join-column'})) {
484 5
                    $joinColumns[] = $this->joinColumnToArray($manyToOneElement->{'join-column'});
485 3
                } else if (isset($manyToOneElement->{'join-columns'})) {
486 2
                    foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
487 2
                        $joinColumns[] = $this->joinColumnToArray($joinColumnElement);
488
                    }
489
                }
490
491 8
                $mapping['joinColumns'] = $joinColumns;
492
493 8
                if (isset($manyToOneElement->cascade)) {
494 2
                    $mapping['cascade'] = $this->_getCascadeMappings($manyToOneElement->cascade);
495
                }
496
497
                // Evaluate second level cache
498 8
                if (isset($manyToOneElement->cache)) {
499 1
                    $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToOneElement->cache));
500
                }
501
502 8
                $metadata->mapManyToOne($mapping);
503
504
            }
505
        }
506
507
        // Evaluate <many-to-many ...> mappings
508 38
        if (isset($xmlRoot->{'many-to-many'})) {
509 13
            foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) {
510
                $mapping = [
511 13
                    'fieldName' => (string) $manyToManyElement['field'],
512 13
                    'targetEntity' => (string) $manyToManyElement['target-entity']
513
                ];
514
515 13
                if (isset($manyToManyElement['fetch'])) {
516 3
                    $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $manyToManyElement['fetch']);
517
                }
518
519 13
                if (isset($manyToManyElement['orphan-removal'])) {
520
                    $mapping['orphanRemoval'] = $this->evaluateBoolean($manyToManyElement['orphan-removal']);
521
                }
522
523 13
                if (isset($manyToManyElement['mapped-by'])) {
524 3
                    $mapping['mappedBy'] = (string) $manyToManyElement['mapped-by'];
525 10
                } else if (isset($manyToManyElement->{'join-table'})) {
526 8
                    if (isset($manyToManyElement['inversed-by'])) {
527 2
                        $mapping['inversedBy'] = (string) $manyToManyElement['inversed-by'];
528
                    }
529
530 8
                    $joinTableElement = $manyToManyElement->{'join-table'};
531
                    $joinTable = [
532 8
                        'name' => (string) $joinTableElement['name']
533
                    ];
534
535 8
                    if (isset($joinTableElement['schema'])) {
536
                        $joinTable['schema'] = (string) $joinTableElement['schema'];
537
                    }
538
539 8
                    foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
540 8
                        $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement);
541
                    }
542
543 8
                    foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) {
544 8
                        $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement);
545
                    }
546
547 8
                    $mapping['joinTable'] = $joinTable;
548
                }
549
550 13
                if (isset($manyToManyElement->cascade)) {
551 8
                    $mapping['cascade'] = $this->_getCascadeMappings($manyToManyElement->cascade);
552
                }
553
554 13
                if (isset($manyToManyElement->{'order-by'})) {
555 1
                    $orderBy = [];
556 1
                    foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) {
557 1
                        $orderBy[(string) $orderByField['name']] = isset($orderByField['direction'])
558
                            ? (string) $orderByField['direction']
559 1
                            : Criteria::ASC;
560
                    }
561 1
                    $mapping['orderBy'] = $orderBy;
562
                }
563
564 13
                if (isset($manyToManyElement['index-by'])) {
565
                    $mapping['indexBy'] = (string) $manyToManyElement['index-by'];
566 13
                } else if (isset($manyToManyElement->{'index-by'})) {
567
                    throw new \InvalidArgumentException("<index-by /> is not a valid tag");
568
                }
569
570
                // Evaluate second level cache
571 13
                if (isset($manyToManyElement->cache)) {
572
                    $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], $this->cacheToArray($manyToManyElement->cache));
573
                }
574
575 13
                $metadata->mapManyToMany($mapping);
576
            }
577
        }
578
579
        // Evaluate association-overrides
580 38
        if (isset($xmlRoot->{'attribute-overrides'})) {
581 2
            foreach ($xmlRoot->{'attribute-overrides'}->{'attribute-override'} as $overrideElement) {
582 2
                $fieldName = (string) $overrideElement['name'];
583 2
                foreach ($overrideElement->field as $field) {
584 2
                    $mapping = $this->columnToArray($field);
585 2
                    $mapping['fieldName'] = $fieldName;
586 2
                    $metadata->setAttributeOverride($fieldName, $mapping);
587
                }
588
            }
589
        }
590
591
        // Evaluate association-overrides
592 38
        if (isset($xmlRoot->{'association-overrides'})) {
593 4
            foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) {
594 4
                $fieldName  = (string) $overrideElement['name'];
595 4
                $override   = [];
596
597
                // Check for join-columns
598 4
                if (isset($overrideElement->{'join-columns'})) {
599 2
                    $joinColumns = [];
600 2
                    foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
601 2
                        $joinColumns[] = $this->joinColumnToArray($joinColumnElement);
602
                    }
603 2
                    $override['joinColumns'] = $joinColumns;
604
                }
605
606
                // Check for join-table
607 4
                if ($overrideElement->{'join-table'}) {
608 2
                    $joinTable          = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $joinTable is dead and can be removed.
Loading history...
609 2
                    $joinTableElement   = $overrideElement->{'join-table'};
610
611
                    $joinTable = [
612 2
                        'name'      => (string) $joinTableElement['name'],
613 2
                        'schema'    => (string) $joinTableElement['schema']
614
                    ];
615
616 2
                    if (isset($joinTableElement->{'join-columns'})) {
617 2
                        foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) {
618 2
                            $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumnElement);
619
                        }
620
                    }
621
622 2
                    if (isset($joinTableElement->{'inverse-join-columns'})) {
623 2
                        foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) {
624 2
                            $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumnElement);
625
                        }
626
                    }
627
628 2
                    $override['joinTable'] = $joinTable;
629
                }
630
631
                // Check for inversed-by
632 4
                if (isset($overrideElement->{'inversed-by'})) {
633 1
                    $override['inversedBy'] = (string) $overrideElement->{'inversed-by'}['name'];
634
                }
635
636
                // Check for `fetch`
637 4
                if (isset($overrideElement['fetch'])) {
638 1
                    $override['fetch'] = constant(Metadata::class . '::FETCH_' . (string) $overrideElement['fetch']);
639
                }
640
641 4
                $metadata->setAssociationOverride($fieldName, $override);
642
            }
643
        }
644
645
        // Evaluate <lifecycle-callbacks...>
646 38
        if (isset($xmlRoot->{'lifecycle-callbacks'})) {
647 5
            foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) {
648 5
                $metadata->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\ORM\Events::' . (string) $lifecycleCallback['type']));
649
            }
650
        }
651
652
        // Evaluate entity listener
653 38
        if (isset($xmlRoot->{'entity-listeners'})) {
654 6
            foreach ($xmlRoot->{'entity-listeners'}->{'entity-listener'} as $listenerElement) {
655 6
                $className = (string) $listenerElement['class'];
656
                // Evaluate the listener using naming convention.
657 6
                if ($listenerElement->count() === 0) {
658 2
                    EntityListenerBuilder::bindEntityListener($metadata, $className);
659
660 2
                    continue;
661
                }
662
663 4
                foreach ($listenerElement as $callbackElement) {
664 4
                    $eventName   = (string) $callbackElement['type'];
665 4
                    $methodName  = (string) $callbackElement['method'];
666
667 4
                    $metadata->addEntityListener($eventName, $className, $methodName);
668
                }
669
            }
670
        }
671 38
    }
672
673
    /**
674
     * Parses (nested) option elements.
675
     *
676
     * @param SimpleXMLElement $options The XML element.
677
     *
678
     * @return array The options array.
679
     */
680 6
    private function _parseOptions(SimpleXMLElement $options)
681
    {
682 6
        $array = [];
683
684
        /* @var $option SimpleXMLElement */
685 6
        foreach ($options as $option) {
686 6
            if ($option->count()) {
687 5
                $value = $this->_parseOptions($option->children());
688
            } else {
689 6
                $value = (string) $option;
690
            }
691
692 6
            $attributes = $option->attributes();
693
694 6
            if (isset($attributes->name)) {
695 6
                $nameAttribute = (string) $attributes->name;
696 6
                $array[$nameAttribute] = in_array($nameAttribute, ['unsigned', 'fixed'])
697 5
                    ? $this->evaluateBoolean($value)
698 6
                    : $value;
699
            } else {
700 6
                $array[] = $value;
701
            }
702
        }
703
704 6
        return $array;
705
    }
706
707
    /**
708
     * Constructs a joinColumn mapping array based on the information
709
     * found in the given SimpleXMLElement.
710
     *
711
     * @param SimpleXMLElement $joinColumnElement The XML element.
712
     *
713
     * @return array The mapping array.
714
     */
715 14
    private function joinColumnToArray(SimpleXMLElement $joinColumnElement)
716
    {
717
        $joinColumn = [
718 14
            'name' => (string) $joinColumnElement['name'],
719 14
            'referencedColumnName' => (string) $joinColumnElement['referenced-column-name']
720
        ];
721
722 14
        if (isset($joinColumnElement['unique'])) {
723 4
            $joinColumn['unique'] = $this->evaluateBoolean($joinColumnElement['unique']);
724
        }
725
726 14
        if (isset($joinColumnElement['nullable'])) {
727 6
            $joinColumn['nullable'] = $this->evaluateBoolean($joinColumnElement['nullable']);
728
        }
729
730 14
        if (isset($joinColumnElement['on-delete'])) {
731 6
            $joinColumn['onDelete'] = (string) $joinColumnElement['on-delete'];
732
        }
733
734 14
        if (isset($joinColumnElement['column-definition'])) {
735 5
            $joinColumn['columnDefinition'] = (string) $joinColumnElement['column-definition'];
736
        }
737
738 14
        return $joinColumn;
739
    }
740
741
     /**
742
     * Parses the given field as array.
743
     *
744
     * @param SimpleXMLElement $fieldMapping
745
     *
746
     * @return array
747
     */
748 24
    private function columnToArray(SimpleXMLElement $fieldMapping)
749
    {
750
        $mapping = [
751 24
            'fieldName' => (string) $fieldMapping['name'],
752
        ];
753
754 24
        if (isset($fieldMapping['type'])) {
755 20
            $mapping['type'] = (string) $fieldMapping['type'];
756
        }
757
758 24
        if (isset($fieldMapping['column'])) {
759 16
            $mapping['columnName'] = (string) $fieldMapping['column'];
760
        }
761
762 24
        if (isset($fieldMapping['length'])) {
763 11
            $mapping['length'] = (int) $fieldMapping['length'];
764
        }
765
766 24
        if (isset($fieldMapping['precision'])) {
767 1
            $mapping['precision'] = (int) $fieldMapping['precision'];
768
        }
769
770 24
        if (isset($fieldMapping['scale'])) {
771 1
            $mapping['scale'] = (int) $fieldMapping['scale'];
772
        }
773
774 24
        if (isset($fieldMapping['unique'])) {
775 10
            $mapping['unique'] = $this->evaluateBoolean($fieldMapping['unique']);
776
        }
777
778 24
        if (isset($fieldMapping['nullable'])) {
779 9
            $mapping['nullable'] = $this->evaluateBoolean($fieldMapping['nullable']);
780
        }
781
782 24
        if (isset($fieldMapping['version']) && $fieldMapping['version']) {
783 3
            $mapping['version'] = $this->evaluateBoolean($fieldMapping['version']);
784
        }
785
786 24
        if (isset($fieldMapping['column-definition'])) {
787 6
            $mapping['columnDefinition'] = (string) $fieldMapping['column-definition'];
788
        }
789
790 24
        if (isset($fieldMapping->options)) {
791 5
            $mapping['options'] = $this->_parseOptions($fieldMapping->options->children());
792
        }
793
794 24
        return $mapping;
795
    }
796
797
    /**
798
     * Parse / Normalize the cache configuration
799
     *
800
     * @param SimpleXMLElement $cacheMapping
801
     *
802
     * @return array
803
     */
804 2
    private function cacheToArray(SimpleXMLElement $cacheMapping)
805
    {
806 2
        $region = isset($cacheMapping['region']) ? (string) $cacheMapping['region'] : null;
807 2
        $usage  = isset($cacheMapping['usage']) ? strtoupper($cacheMapping['usage']) : null;
808
809 2
        if ($usage && ! defined('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage)) {
810
            throw new \InvalidArgumentException(sprintf('Invalid cache usage "%s"', $usage));
811
        }
812
813 2
        if ($usage) {
814 2
            $usage = constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage);
815
        }
816
817
        return [
818 2
            'usage'  => $usage,
819 2
            'region' => $region,
820
        ];
821
    }
822
823
    /**
824
     * Gathers a list of cascade options found in the given cascade element.
825
     *
826
     * @param SimpleXMLElement $cascadeElement The cascade element.
827
     *
828
     * @return array The list of cascade options.
829
     */
830 8
    private function _getCascadeMappings(SimpleXMLElement $cascadeElement)
831
    {
832 8
        $cascades = [];
833
        /* @var $action SimpleXmlElement */
834 8
        foreach ($cascadeElement->children() as $action) {
835
            // According to the JPA specifications, XML uses "cascade-persist"
836
            // instead of "persist". Here, both variations
837
            // are supported because both YAML and Annotation use "persist"
838
            // and we want to make sure that this driver doesn't need to know
839
            // anything about the supported cascading actions
840 8
            $cascades[] = str_replace('cascade-', '', $action->getName());
841
        }
842
843 8
        return $cascades;
844
    }
845
846
    /**
847
     * {@inheritDoc}
848
     */
849 41
    protected function loadMappingFile($file)
850
    {
851 41
        $result = [];
852
        // Note: we do not use `simplexml_load_file()` because of https://bugs.php.net/bug.php?id=62577
853 41
        $xmlElement = simplexml_load_string(file_get_contents($file));
854
855 41
        if (isset($xmlElement->entity)) {
856 39
            foreach ($xmlElement->entity as $entityElement) {
857 39
                $entityName = (string) $entityElement['name'];
858 39
                $result[$entityName] = $entityElement;
859
            }
860 9
        } else if (isset($xmlElement->{'mapped-superclass'})) {
861 5
            foreach ($xmlElement->{'mapped-superclass'} as $mappedSuperClass) {
862 5
                $className = (string) $mappedSuperClass['name'];
863 5
                $result[$className] = $mappedSuperClass;
864
            }
865 4
        } else if (isset($xmlElement->embeddable)) {
866 3
            foreach ($xmlElement->embeddable as $embeddableElement) {
867 3
                $embeddableName = (string) $embeddableElement['name'];
868 3
                $result[$embeddableName] = $embeddableElement;
869
            }
870
        }
871
872 41
        return $result;
873
    }
874
875
    /**
876
     * @param mixed $element
877
     *
878
     * @return bool
879
     */
880 14
    protected function evaluateBoolean($element)
881
    {
882 14
        $flag = (string) $element;
883
884 14
        return ($flag == "true" || $flag == "1");
885
    }
886
}
887