Failed Conditions
Pull Request — 2.7 (#8036)
by Benjamin
06:53
created

AnnotationDriver   F

Complexity

Total Complexity 112

Size/Duplication

Total Lines 636
Duplicated Lines 0 %

Test Coverage

Coverage 96.41%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 112
eloc 319
c 1
b 0
f 0
dl 0
loc 636
ccs 295
cts 306
cp 0.9641
rs 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 7 2
A joinColumnToArray() 0 9 1
A columnToArray() 0 25 4
F loadMetadataForClass() 0 481 93
A getFetchMode() 0 7 2
C getMethodCallbacks() 0 40 10

How to fix   Complexity   

Complex Class

Complex classes like AnnotationDriver 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 AnnotationDriver, 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\Annotations\AnnotationReader;
23
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
24
use Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver;
25
use Doctrine\ORM\Events;
26
use Doctrine\ORM\Mapping;
27
use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder;
28
use Doctrine\ORM\Mapping\MappingException;
29
30
/**
31
 * The AnnotationDriver reads the mapping metadata from docblock annotations.
32
 *
33
 * @since 2.0
34
 * @author Benjamin Eberlei <[email protected]>
35
 * @author Guilherme Blanco <[email protected]>
36
 * @author Jonathan H. Wage <[email protected]>
37
 * @author Roman Borschel <[email protected]>
38
 */
39
class AnnotationDriver extends AbstractAnnotationDriver
40
{
41
    /**
42
     * {@inheritDoc}
43
     */
44
    protected $entityAnnotationClasses = [
45
        Mapping\Entity::class => 1,
46
        Mapping\MappedSuperclass::class => 2,
47
        Mapping\Embeddable::class => 3,
48
    ];
49
50
    /**
51
     * {@inheritDoc}
52
     */
53 437
    public function loadMetadataForClass($className, ClassMetadata $metadata)
54
    {
55
        /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */
56 437
        $class = $metadata->getReflectionClass();
57
58 437
        if ( ! $class) {
0 ignored issues
show
introduced by
$class is of type ReflectionClass, thus it always evaluated to true.
Loading history...
59
            // this happens when running annotation driver in combination with
60
            // static reflection services. This is not the nicest fix
61 1
            $class = new \ReflectionClass($metadata->name);
62
        }
63
64 437
        $classAnnotations = $this->reader->getClassAnnotations($class);
65
66 437
        if ($classAnnotations) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $classAnnotations of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
67 431
            foreach ($classAnnotations as $key => $annot) {
68 431
                if ( ! is_numeric($key)) {
69
                    continue;
70
                }
71
72 431
                $classAnnotations[get_class($annot)] = $annot;
73
            }
74
        }
75
76
        // Evaluate Entity annotation
77 437
        if (isset($classAnnotations[Mapping\Entity::class])) {
78 426
            $entityAnnot = $classAnnotations[Mapping\Entity::class];
79 426
            if ($entityAnnot->repositoryClass !== null) {
80 8
                $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass);
81
            }
82
83 426
            if ($entityAnnot->readOnly) {
84 426
                $metadata->markReadOnly();
85
            }
86 48
        } else if (isset($classAnnotations[Mapping\MappedSuperclass::class])) {
87 31
            $mappedSuperclassAnnot = $classAnnotations[Mapping\MappedSuperclass::class];
88
89 31
            $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass);
90 31
            $metadata->isMappedSuperclass = true;
91 19
        } else if (isset($classAnnotations[Mapping\Embeddable::class])) {
92 13
            $metadata->isEmbeddedClass = true;
93
        } else {
94 6
            throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
95
        }
96
97
        // Evaluate Table annotation
98 431
        if (isset($classAnnotations[Mapping\Table::class])) {
99 221
            $tableAnnot   = $classAnnotations[Mapping\Table::class];
100
            $primaryTable = [
101 221
                'name'   => $tableAnnot->name,
102 221
                'schema' => $tableAnnot->schema
103
            ];
104
105 221
            if ($tableAnnot->indexes !== null) {
106 16
                foreach ($tableAnnot->indexes as $indexAnnot) {
107 16
                    $index = ['columns' => $indexAnnot->columns];
108
109 16
                    if ( ! empty($indexAnnot->flags)) {
110 1
                        $index['flags'] = $indexAnnot->flags;
111
                    }
112
113 16
                    if ( ! empty($indexAnnot->options)) {
114 1
                        $index['options'] = $indexAnnot->options;
115
                    }
116
117 16
                    if ( ! empty($indexAnnot->name)) {
118 15
                        $primaryTable['indexes'][$indexAnnot->name] = $index;
119
                    } else {
120 16
                        $primaryTable['indexes'][] = $index;
121
                    }
122
                }
123
            }
124
125 221
            if ($tableAnnot->uniqueConstraints !== null) {
126 9
                foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) {
127 9
                    $uniqueConstraint = ['columns' => $uniqueConstraintAnnot->columns];
128
129 9
                    if ( ! empty($uniqueConstraintAnnot->options)) {
130 3
                        $uniqueConstraint['options'] = $uniqueConstraintAnnot->options;
131
                    }
132
133 9
                    if ( ! empty($uniqueConstraintAnnot->name)) {
134 9
                        $primaryTable['uniqueConstraints'][$uniqueConstraintAnnot->name] = $uniqueConstraint;
135
                    } else {
136 9
                        $primaryTable['uniqueConstraints'][] = $uniqueConstraint;
137
                    }
138
                }
139
            }
140
141 221
            if ($tableAnnot->options) {
142 6
                $primaryTable['options'] = $tableAnnot->options;
143
            }
144
145 221
            $metadata->setPrimaryTable($primaryTable);
146
        }
147
148
        // Evaluate @Cache annotation
149 431
        if (isset($classAnnotations[Mapping\Cache::class])) {
150 19
            $cacheAnnot = $classAnnotations[Mapping\Cache::class];
151
            $cacheMap   = [
152 19
                'region' => $cacheAnnot->region,
153 19
                'usage'  => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage),
154
            ];
155
156 19
            $metadata->enableCache($cacheMap);
157
        }
158
159
        // Evaluate NamedNativeQueries annotation
160 431
        if (isset($classAnnotations[Mapping\NamedNativeQueries::class])) {
161 17
            $namedNativeQueriesAnnot = $classAnnotations[Mapping\NamedNativeQueries::class];
162
163 17
            foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) {
164 17
                $metadata->addNamedNativeQuery(
165
                    [
166 17
                        'name'              => $namedNativeQuery->name,
167 17
                        'query'             => $namedNativeQuery->query,
168 17
                        'resultClass'       => $namedNativeQuery->resultClass,
169 17
                        'resultSetMapping'  => $namedNativeQuery->resultSetMapping,
170
                    ]
171
                );
172
            }
173
        }
174
175
        // Evaluate SqlResultSetMappings annotation
176 431
        if (isset($classAnnotations[Mapping\SqlResultSetMappings::class])) {
177 17
            $sqlResultSetMappingsAnnot = $classAnnotations[Mapping\SqlResultSetMappings::class];
178
179 17
            foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) {
180 17
                $entities = [];
181 17
                $columns  = [];
182 17
                foreach ($resultSetMapping->entities as $entityResultAnnot) {
183
                    $entityResult = [
184 17
                        'fields'                => [],
185 17
                        'entityClass'           => $entityResultAnnot->entityClass,
186 17
                        'discriminatorColumn'   => $entityResultAnnot->discriminatorColumn,
187
                    ];
188
189 17
                    foreach ($entityResultAnnot->fields as $fieldResultAnnot) {
190 17
                        $entityResult['fields'][] = [
191 17
                            'name'      => $fieldResultAnnot->name,
192 17
                            'column'    => $fieldResultAnnot->column
193
                        ];
194
                    }
195
196 17
                    $entities[] = $entityResult;
197
                }
198
199 17
                foreach ($resultSetMapping->columns as $columnResultAnnot) {
200 10
                    $columns[] = [
201 10
                        'name' => $columnResultAnnot->name,
202
                    ];
203
                }
204
205 17
                $metadata->addSqlResultSetMapping(
206
                    [
207 17
                        'name'          => $resultSetMapping->name,
208 17
                        'entities'      => $entities,
209 17
                        'columns'       => $columns
210
                    ]
211
                );
212
            }
213
        }
214
215
        // Evaluate NamedQueries annotation
216 431
        if (isset($classAnnotations[Mapping\NamedQueries::class])) {
217 11
            $namedQueriesAnnot = $classAnnotations[Mapping\NamedQueries::class];
218
219 11
            if ( ! is_array($namedQueriesAnnot->value)) {
220
                throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations.");
221
            }
222
223 11
            foreach ($namedQueriesAnnot->value as $namedQuery) {
224 11
                if ( ! ($namedQuery instanceof Mapping\NamedQuery)) {
225
                    throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations.");
226
                }
227 11
                $metadata->addNamedQuery(
228
                    [
229 11
                        'name'  => $namedQuery->name,
230 11
                        'query' => $namedQuery->query
231
                    ]
232
                );
233
            }
234
        }
235
236
        // Evaluate InheritanceType annotation
237 431
        if (isset($classAnnotations[Mapping\InheritanceType::class])) {
238 85
            $inheritanceTypeAnnot = $classAnnotations[Mapping\InheritanceType::class];
239
240 85
            $metadata->setInheritanceType(
241 85
                constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value)
242
            );
243
244 85
            if ($metadata->inheritanceType != Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) {
245
                // Evaluate DiscriminatorColumn annotation
246 85
                if (isset($classAnnotations[Mapping\DiscriminatorColumn::class])) {
247 68
                    $discrColumnAnnot = $classAnnotations[Mapping\DiscriminatorColumn::class];
248
249 68
                    $metadata->setDiscriminatorColumn(
250
                        [
251 68
                            'name'             => $discrColumnAnnot->name,
252 68
                            'type'             => $discrColumnAnnot->type ?: 'string',
253 68
                            'length'           => $discrColumnAnnot->length ?: 255,
254 68
                            'columnDefinition' => $discrColumnAnnot->columnDefinition,
255
                        ]
256
                    );
257
                } else {
258 20
                    $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]);
259
                }
260
261
                // Evaluate DiscriminatorMap annotation
262 85
                if (isset($classAnnotations[Mapping\DiscriminatorMap::class])) {
263 85
                    $discrMapAnnot = $classAnnotations[Mapping\DiscriminatorMap::class];
264 85
                    $metadata->setDiscriminatorMap($discrMapAnnot->value);
265
                }
266
            }
267
        }
268
269
270
        // Evaluate DoctrineChangeTrackingPolicy annotation
271 431
        if (isset($classAnnotations[Mapping\ChangeTrackingPolicy::class])) {
272 7
            $changeTrackingAnnot = $classAnnotations[Mapping\ChangeTrackingPolicy::class];
273 7
            $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value));
274
        }
275
276
        // Evaluate annotations on properties/fields
277
        /* @var $property \ReflectionProperty */
278 431
        foreach ($class->getProperties() as $property) {
279 429
            if ($metadata->isMappedSuperclass && ! $property->isPrivate()
280
                ||
281 429
                $metadata->isEmbeddedClass && $property->getDeclaringClass()->getName() !== $class->getName()
282
                ||
283 429
                $metadata->isInheritedField($property->name)
284
                ||
285 429
                $metadata->isInheritedAssociation($property->name)
286
                ||
287 429
                $metadata->isInheritedEmbeddedClass($property->name)) {
288 83
                continue;
289
            }
290
291 429
            $mapping = [];
292 429
            $mapping['fieldName'] = $property->getName();
293
294
            // Evaluate @Cache annotation
295 429
            if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Cache::class)) !== null) {
296 15
                $mapping['cache'] = $metadata->getAssociationCacheDefaults(
297 15
                    $mapping['fieldName'],
298
                    [
299 15
                        'usage'  => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage),
300 15
                        'region' => $cacheAnnot->region,
301
                    ]
302
                );
303
            }
304
            // Check for JoinColumn/JoinColumns annotations
305 428
            $joinColumns = [];
306
307 428
            if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class)) {
308 158
                $joinColumns[] = $this->joinColumnToArray($joinColumnAnnot);
309 426
            } else if ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class)) {
310 19
                foreach ($joinColumnsAnnot->value as $joinColumn) {
311 19
                    $joinColumns[] = $this->joinColumnToArray($joinColumn);
312
                }
313
            }
314
315
            // Field can only be annotated with one of:
316
            // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany
317 428
            if ($columnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Column::class)) {
318 419
                if ($columnAnnot->type == null) {
319
                    throw MappingException::propertyTypeIsRequired($className, $property->getName());
320
                }
321
322 419
                $mapping = $this->columnToArray($property->getName(), $columnAnnot);
323
324 419
                if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $idAnnot is dead and can be removed.
Loading history...
325 413
                    $mapping['id'] = true;
326
                }
327
328 419
                if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, Mapping\GeneratedValue::class)) {
329 351
                    $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy));
330
                }
331
332 419
                if ($this->reader->getPropertyAnnotation($property, Mapping\Version::class)) {
333 18
                    $metadata->setVersionMapping($mapping);
334
                }
335
336 419
                $metadata->mapField($mapping);
337
338
                // Check for SequenceGenerator/TableGenerator definition
339 419
                if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\SequenceGenerator::class)) {
340 9
                    $metadata->setSequenceGeneratorDefinition(
341
                        [
342 9
                            'sequenceName' => $seqGeneratorAnnot->sequenceName,
343 9
                            'allocationSize' => $seqGeneratorAnnot->allocationSize,
344 9
                            'initialValue' => $seqGeneratorAnnot->initialValue
345
                        ]
346
                    );
347 416
                } else if ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\TableGenerator')) {
348
                    throw MappingException::tableIdGeneratorNotImplemented($className);
349 416
                } else if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) {
350 3
                    $metadata->setCustomGeneratorDefinition(
351
                        [
352 419
                            'class' => $customGeneratorAnnot->class
353
                        ]
354
                    );
355
                }
356 299
            } else if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToOne::class)) {
357 125
                if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) {
358 12
                    $mapping['id'] = true;
359
                }
360
361 125
                $mapping['targetEntity'] = $oneToOneAnnot->targetEntity;
362 125
                $mapping['joinColumns'] = $joinColumns;
363 125
                $mapping['mappedBy'] = $oneToOneAnnot->mappedBy;
364 125
                $mapping['inversedBy'] = $oneToOneAnnot->inversedBy;
365 125
                $mapping['cascade'] = $oneToOneAnnot->cascade;
366 125
                $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval;
367 125
                $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch);
368 125
                $metadata->mapOneToOne($mapping);
369 245
            } else if ($oneToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToMany::class)) {
370 121
                $mapping['mappedBy'] = $oneToManyAnnot->mappedBy;
371 121
                $mapping['targetEntity'] = $oneToManyAnnot->targetEntity;
372 121
                $mapping['cascade'] = $oneToManyAnnot->cascade;
373 121
                $mapping['indexBy'] = $oneToManyAnnot->indexBy;
374 121
                $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval;
375 121
                $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch);
376
377 121
                if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) {
378 18
                    $mapping['orderBy'] = $orderByAnnot->value;
379
                }
380
381 121
                $metadata->mapOneToMany($mapping);
382 241
            } else if ($manyToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToOne::class)) {
383 157
                if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) {
384 36
                    $mapping['id'] = true;
385
                }
386
387 157
                $mapping['joinColumns'] = $joinColumns;
388 157
                $mapping['cascade'] = $manyToOneAnnot->cascade;
389 157
                $mapping['inversedBy'] = $manyToOneAnnot->inversedBy;
390 157
                $mapping['targetEntity'] = $manyToOneAnnot->targetEntity;
391 157
                $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch);
392 157
                $metadata->mapManyToOne($mapping);
393 135
            } else if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToMany::class)) {
394 99
                $joinTable = [];
395
396 99
                if ($joinTableAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinTable::class)) {
397
                    $joinTable = [
398 79
                        'name' => $joinTableAnnot->name,
399 79
                        'schema' => $joinTableAnnot->schema
400
                    ];
401
402 79
                    foreach ($joinTableAnnot->joinColumns as $joinColumn) {
403 77
                        $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn);
404
                    }
405
406 79
                    foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) {
407 78
                        $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn);
408
                    }
409
                }
410
411 99
                $mapping['joinTable'] = $joinTable;
412 99
                $mapping['targetEntity'] = $manyToManyAnnot->targetEntity;
413 99
                $mapping['mappedBy'] = $manyToManyAnnot->mappedBy;
414 99
                $mapping['inversedBy'] = $manyToManyAnnot->inversedBy;
415 99
                $mapping['cascade'] = $manyToManyAnnot->cascade;
416 99
                $mapping['indexBy'] = $manyToManyAnnot->indexBy;
417 99
                $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval;
418 99
                $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch);
419
420 99
                if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) {
421 3
                    $mapping['orderBy'] = $orderByAnnot->value;
422
                }
423
424 99
                $metadata->mapManyToMany($mapping);
425 56
            } else if ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class)) {
426 14
                $mapping['class'] = $embeddedAnnot->class;
427 14
                $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix;
428
429 427
                $metadata->mapEmbedded($mapping);
430
            }
431
        }
432
433
        // Evaluate AssociationOverrides annotation
434 429
        if (isset($classAnnotations[Mapping\AssociationOverrides::class])) {
435 5
            $associationOverridesAnnot = $classAnnotations[Mapping\AssociationOverrides::class];
436
437 5
            foreach ($associationOverridesAnnot->value as $associationOverride) {
438 5
                $override   = [];
439 5
                $fieldName  = $associationOverride->name;
440
441
                // Check for JoinColumn/JoinColumns annotations
442 5
                if ($associationOverride->joinColumns) {
443 3
                    $joinColumns = [];
444
445 3
                    foreach ($associationOverride->joinColumns as $joinColumn) {
446 3
                        $joinColumns[] = $this->joinColumnToArray($joinColumn);
447
                    }
448
449 3
                    $override['joinColumns'] = $joinColumns;
450
                }
451
452
                // Check for JoinTable annotations
453 5
                if ($associationOverride->joinTable) {
454 2
                    $joinTableAnnot = $associationOverride->joinTable;
455
                    $joinTable      = [
456 2
                        'name'      => $joinTableAnnot->name,
457 2
                        'schema'    => $joinTableAnnot->schema
458
                    ];
459
460 2
                    foreach ($joinTableAnnot->joinColumns as $joinColumn) {
461 2
                        $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn);
462
                    }
463
464 2
                    foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) {
465 2
                        $joinTable['inverseJoinColumns'][] = $this->joinColumnToArray($joinColumn);
466
                    }
467
468 2
                    $override['joinTable'] = $joinTable;
469
                }
470
471
                // Check for inversedBy
472 5
                if ($associationOverride->inversedBy) {
473 1
                    $override['inversedBy'] = $associationOverride->inversedBy;
474
                }
475
476
                // Check for `fetch`
477 5
                if ($associationOverride->fetch) {
478 1
                    $override['fetch'] = constant(Mapping\ClassMetadata::class . '::FETCH_' . $associationOverride->fetch);
479
                }
480
481 5
                $metadata->setAssociationOverride($fieldName, $override);
482
            }
483
        }
484
485
        // Evaluate AttributeOverrides annotation
486 429
        if (isset($classAnnotations[Mapping\AttributeOverrides::class])) {
487 3
            $attributeOverridesAnnot = $classAnnotations[Mapping\AttributeOverrides::class];
488
489 3
            foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) {
490 3
                $attributeOverride = $this->columnToArray($attributeOverrideAnnot->name, $attributeOverrideAnnot->column);
491
492 3
                $metadata->setAttributeOverride($attributeOverrideAnnot->name, $attributeOverride);
493
            }
494
        }
495
496
        // Evaluate EntityListeners annotation
497 429
        if (isset($classAnnotations[Mapping\EntityListeners::class])) {
498 12
            $entityListenersAnnot = $classAnnotations[Mapping\EntityListeners::class];
499
500 12
            foreach ($entityListenersAnnot->value as $item) {
501 12
                $listenerClassName = $metadata->fullyQualifiedClassName($item);
502
503 12
                if ( ! class_exists($listenerClassName)) {
504
                    throw MappingException::entityListenerClassNotFound($listenerClassName, $className);
505
                }
506
507 12
                $hasMapping     = false;
508 12
                $listenerClass  = new \ReflectionClass($listenerClassName);
509
510
                /* @var $method \ReflectionMethod */
511 12
                foreach ($listenerClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
512
                    // find method callbacks.
513 12
                    $callbacks  = $this->getMethodCallbacks($method);
514 12
                    $hasMapping = $hasMapping ?: ( ! empty($callbacks));
515
516 12
                    foreach ($callbacks as $value) {
517 12
                        $metadata->addEntityListener($value[1], $listenerClassName, $value[0]);
518
                    }
519
                }
520
521
                // Evaluate the listener using naming convention.
522 12
                if ( ! $hasMapping ) {
523 12
                    EntityListenerBuilder::bindEntityListener($metadata, $listenerClassName);
524
                }
525
            }
526
        }
527
528
        // Evaluate @HasLifecycleCallbacks annotation
529 429
        if (isset($classAnnotations[Mapping\HasLifecycleCallbacks::class])) {
530
            /* @var $method \ReflectionMethod */
531 19
            foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
532 18
                foreach ($this->getMethodCallbacks($method) as $value) {
533 18
                    $metadata->addLifecycleCallback($value[0], $value[1]);
534
                }
535
            }
536
        }
537 429
    }
538
539
    /**
540
     * Attempts to resolve the fetch mode.
541
     *
542
     * @param string $className The class name.
543
     * @param string $fetchMode The fetch mode.
544
     *
545
     * @return integer The fetch mode as defined in ClassMetadata.
546
     *
547
     * @throws MappingException If the fetch mode is not valid.
548
     */
549 283
    private function getFetchMode($className, $fetchMode)
550
    {
551 283
        if ( ! defined('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode)) {
552
            throw MappingException::invalidFetchMode($className, $fetchMode);
553
        }
554
555 283
        return constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $fetchMode);
556
    }
557
558
    /**
559
     * Parses the given method.
560
     *
561
     * @param \ReflectionMethod $method
562
     *
563
     * @return array
564
     */
565 28
    private function getMethodCallbacks(\ReflectionMethod $method)
566
    {
567 28
        $callbacks   = [];
568 28
        $annotations = $this->reader->getMethodAnnotations($method);
569
570 28
        foreach ($annotations as $annot) {
571 22
            if ($annot instanceof Mapping\PrePersist) {
572 15
                $callbacks[] = [$method->name, Events::prePersist];
573
            }
574
575 22
            if ($annot instanceof Mapping\PostPersist) {
576 11
                $callbacks[] = [$method->name, Events::postPersist];
577
            }
578
579 22
            if ($annot instanceof Mapping\PreUpdate) {
580 11
                $callbacks[] = [$method->name, Events::preUpdate];
581
            }
582
583 22
            if ($annot instanceof Mapping\PostUpdate) {
584 7
                $callbacks[] = [$method->name, Events::postUpdate];
585
            }
586
587 22
            if ($annot instanceof Mapping\PreRemove) {
588 8
                $callbacks[] = [$method->name, Events::preRemove];
589
            }
590
591 22
            if ($annot instanceof Mapping\PostRemove) {
592 6
                $callbacks[] = [$method->name, Events::postRemove];
593
            }
594
595 22
            if ($annot instanceof Mapping\PostLoad) {
596 11
                $callbacks[] = [$method->name, Events::postLoad];
597
            }
598
599 22
            if ($annot instanceof Mapping\PreFlush) {
600 22
                $callbacks[] = [$method->name, Events::preFlush];
601
            }
602
        }
603
604 28
        return $callbacks;
605
    }
606
607
    /**
608
     * Parse the given JoinColumn as array
609
     *
610
     * @param Mapping\JoinColumn $joinColumn
611
     * @return array
612
     */
613 197
    private function joinColumnToArray(Mapping\JoinColumn $joinColumn)
614
    {
615
        return [
616 197
            'name' => $joinColumn->name,
617 197
            'unique' => $joinColumn->unique,
618 197
            'nullable' => $joinColumn->nullable,
619 197
            'onDelete' => $joinColumn->onDelete,
620 197
            'columnDefinition' => $joinColumn->columnDefinition,
621 197
            'referencedColumnName' => $joinColumn->referencedColumnName,
622
        ];
623
    }
624
625
    /**
626
     * Parse the given Column as array
627
     *
628
     * @param string $fieldName
629
     * @param Mapping\Column $column
630
     *
631
     * @return array
632
     */
633 419
    private function columnToArray($fieldName, Mapping\Column $column)
634
    {
635
        $mapping = [
636 419
            'fieldName' => $fieldName,
637 419
            'type'      => $column->type,
638 419
            'scale'     => $column->scale,
639 419
            'length'    => $column->length,
640 419
            'unique'    => $column->unique,
641 419
            'nullable'  => $column->nullable,
642 419
            'precision' => $column->precision
643
        ];
644
645 419
        if ($column->options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $column->options of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
646 11
            $mapping['options'] = $column->options;
647
        }
648
649 419
        if (isset($column->name)) {
650 87
            $mapping['columnName'] = $column->name;
651
        }
652
653 419
        if (isset($column->columnDefinition)) {
654 6
            $mapping['columnDefinition'] = $column->columnDefinition;
655
        }
656
657 419
        return $mapping;
658
    }
659
660
    /**
661
     * Factory method for the Annotation Driver.
662
     *
663
     * @param array|string          $paths
664
     * @param AnnotationReader|null $reader
665
     *
666
     * @return AnnotationDriver
667
     */
668
    static public function create($paths = [], AnnotationReader $reader = null)
669
    {
670
        if ($reader == null) {
671
            $reader = new AnnotationReader();
672
        }
673
674
        return new self($reader, $paths);
675
    }
676
}
677