Failed Conditions
Push — master ( f185a6...047620 )
by Guilherme
09:26
created

AnnotationDriver::attachDiscriminatorColumn()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 41
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 21
nc 18
nop 4
dl 0
loc 41
ccs 22
cts 22
cp 1
crap 6
rs 8.9617
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A AnnotationDriver::attachLifecycleCallbacks() 0 25 5
1
<?php /** @noinspection ALL */
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Mapping\Driver;
6
7
use Doctrine\Common\Annotations\AnnotationReader;
8
use Doctrine\Common\Annotations\Reader;
9
use Doctrine\DBAL\Types\Type;
10
use Doctrine\ORM\Annotation;
11
use Doctrine\ORM\Cache\Exception\CacheException;
12
use Doctrine\ORM\Events;
13
use Doctrine\ORM\Mapping;
14
use Doctrine\ORM\Mapping\Builder;
15
use FilesystemIterator;
16
use RecursiveDirectoryIterator;
17
use RecursiveIteratorIterator;
18
use RecursiveRegexIterator;
19
use ReflectionClass;
20
use ReflectionException;
21
use ReflectionMethod;
22
use ReflectionProperty;
23
use RegexIterator;
24
use RuntimeException;
25
use UnexpectedValueException;
26
use function array_diff;
27
use function array_intersect;
28
use function array_map;
29
use function array_merge;
30
use function array_unique;
31
use function class_exists;
32
use function constant;
33
use function count;
34
use function defined;
35
use function get_class;
36
use function get_declared_classes;
37
use function in_array;
38
use function is_dir;
39
use function is_numeric;
40
use function preg_match;
41
use function preg_quote;
42
use function realpath;
43
use function sprintf;
44
use function str_replace;
45
use function strpos;
46
use function strtoupper;
47
use function var_export;
48
49
/**
50
 * The AnnotationDriver reads the mapping metadata from docblock annotations.
51
 */
52
class AnnotationDriver implements MappingDriver
53
{
54
    /** @var int[] */
55
    protected $entityAnnotationClasses = [
56
        Annotation\Entity::class           => 1,
57
        Annotation\MappedSuperclass::class => 2,
58
    ];
59
60
    /**
61
     * The AnnotationReader.
62
     *
63
     * @var AnnotationReader
64
     */
65
    protected $reader;
66
67
    /**
68
     * The paths where to look for mapping files.
69
     *
70
     * @var string[]
71
     */
72
    protected $paths = [];
73
74
    /**
75
     * The paths excluded from path where to look for mapping files.
76
     *
77
     * @var string[]
78
     */
79
    protected $excludePaths = [];
80
81
    /**
82
     * The file extension of mapping documents.
83
     *
84
     * @var string
85
     */
86
    protected $fileExtension = '.php';
87
88
    /**
89
     * Cache for AnnotationDriver#getAllClassNames().
90
     *
91
     * @var string[]|null
92
     */
93
    protected $classNames;
94
95
    /**
96
     * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
97
     * docblock annotations.
98
     *
99
     * @param Reader               $reader The AnnotationReader to use, duck-typed.
100
     * @param string|string[]|null $paths  One or multiple paths where mapping classes can be found.
101
     */
102 2297
    public function __construct(Reader $reader, $paths = null)
103
    {
104 2297
        $this->reader = $reader;
0 ignored issues
show
Documentation Bug introduced by
$reader is of type Doctrine\Common\Annotations\Reader, but the property $reader was declared to be of type Doctrine\Common\Annotations\AnnotationReader. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
105
106 2297
        if ($paths) {
107 2211
            $this->addPaths((array) $paths);
108
        }
109 2297
    }
110
111
    /**
112
     * Appends lookup paths to metadata driver.
113
     *
114
     * @param string[] $paths
115
     */
116 2215
    public function addPaths(array $paths)
117
    {
118 2215
        $this->paths = array_unique(array_merge($this->paths, $paths));
119 2215
    }
120
121
    /**
122
     * Retrieves the defined metadata lookup paths.
123
     *
124
     * @return string[]
125
     */
126
    public function getPaths()
127
    {
128
        return $this->paths;
129
    }
130
131
    /**
132
     * Append exclude lookup paths to metadata driver.
133
     *
134
     * @param string[] $paths
135
     */
136
    public function addExcludePaths(array $paths)
137
    {
138
        $this->excludePaths = array_unique(array_merge($this->excludePaths, $paths));
139
    }
140
141
    /**
142
     * Retrieve the defined metadata lookup exclude paths.
143
     *
144
     * @return string[]
145
     */
146
    public function getExcludePaths()
147
    {
148
        return $this->excludePaths;
149
    }
150
151
    /**
152
     * Retrieve the current annotation reader
153
     *
154
     * @return Reader
155
     */
156 1
    public function getReader()
157
    {
158 1
        return $this->reader;
159
    }
160
161
    /**
162
     * Gets the file extension used to look for mapping files under.
163
     *
164
     * @return string
165
     */
166
    public function getFileExtension()
167
    {
168
        return $this->fileExtension;
169
    }
170
171
    /**
172
     * Sets the file extension used to look for mapping files under.
173
     *
174
     * @param string $fileExtension The file extension to set.
175
     */
176
    public function setFileExtension($fileExtension)
177
    {
178
        $this->fileExtension = $fileExtension;
179
    }
180
181
    /**
182
     * Returns whether the class with the specified name is transient. Only non-transient
183
     * classes, that is entities and mapped superclasses, should have their metadata loaded.
184
     *
185
     * A class is non-transient if it is annotated with an annotation
186
     * from the {@see AnnotationDriver::entityAnnotationClasses}.
187
     *
188
     * @param string $className
189
     *
190
     * @throws ReflectionException
191
     */
192 193
    public function isTransient($className) : bool
193
    {
194 193
        $classAnnotations = $this->reader->getClassAnnotations(new ReflectionClass($className));
195
196 193
        foreach ($classAnnotations as $annotation) {
197 188
            if (isset($this->entityAnnotationClasses[get_class($annotation)])) {
198 188
                return false;
199
            }
200
        }
201
202 12
        return true;
203
    }
204
205
    /**
206
     * {@inheritdoc}
207
     *
208
     * @throws ReflectionException
209
     */
210 60
    public function getAllClassNames() : array
211
    {
212 60
        if ($this->classNames !== null) {
213 45
            return $this->classNames;
214
        }
215
216 60
        if (! $this->paths) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->paths of type string[] 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...
217
            throw Mapping\MappingException::pathRequired();
218
        }
219
220 60
        $classes       = [];
221 60
        $includedFiles = [];
222
223 60
        foreach ($this->paths as $path) {
224 60
            if (! is_dir($path)) {
225
                throw Mapping\MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
226
            }
227
228 60
            $iterator = new RegexIterator(
229 60
                new RecursiveIteratorIterator(
230 60
                    new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
231 60
                    RecursiveIteratorIterator::LEAVES_ONLY
232
                ),
233 60
                '/^.+' . preg_quote($this->fileExtension) . '$/i',
234 60
                RecursiveRegexIterator::GET_MATCH
235
            );
236
237 60
            foreach ($iterator as $file) {
238 60
                $sourceFile = $file[0];
239
240 60
                if (! preg_match('(^phar:)i', $sourceFile)) {
241 60
                    $sourceFile = realpath($sourceFile);
242
                }
243
244 60
                foreach ($this->excludePaths as $excludePath) {
245
                    $exclude = str_replace('\\', '/', realpath($excludePath));
246
                    $current = str_replace('\\', '/', $sourceFile);
247
248
                    if (strpos($current, $exclude) !== false) {
249
                        continue 2;
250
                    }
251
                }
252
253 60
                require_once $sourceFile;
254
255 60
                $includedFiles[] = $sourceFile;
256
            }
257
        }
258
259 60
        $declared = get_declared_classes();
260
261 60
        foreach ($declared as $className) {
262 60
            $reflectionClass = new ReflectionClass($className);
263 60
            $sourceFile      = $reflectionClass->getFileName();
264
265 60
            if (in_array($sourceFile, $includedFiles, true) && ! $this->isTransient($className)) {
266 60
                $classes[] = $className;
267
            }
268
        }
269
270 60
        $this->classNames = $classes;
271
272 60
        return $classes;
273
    }
274
275
    /**
276
     * {@inheritDoc}
277
     *
278
     * @throws CacheException
279
     * @throws Mapping\MappingException
280
     * @throws ReflectionException
281
     * @throws RuntimeException
282
     * @throws UnexpectedValueException
283
     */
284 379
    public function loadMetadataForClass(
285
        string $className,
286
        ?Mapping\ComponentMetadata $parent,
287
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
288
    ) : Mapping\ComponentMetadata {
289 379
        $reflectionClass  = new ReflectionClass($className);
290 379
        $metadata         = new Mapping\ClassMetadata($className, $parent, $metadataBuildingContext);
291 379
        $classAnnotations = $this->getClassAnnotations($reflectionClass);
292 379
        $classMetadata    = $this->convertClassAnnotationsToClassMetadata(
293 379
            $classAnnotations,
294 379
            $reflectionClass,
295 379
            $metadata,
296 379
            $metadataBuildingContext
297
        );
298
299
        // Evaluate @Cache annotation
300 373
        if (isset($classAnnotations[Annotation\Cache::class])) {
301 18
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
302
303
            $cacheBuilder
304 18
                ->withComponentMetadata($metadata)
305 18
                ->withCacheAnnotation($classAnnotations[Annotation\Cache::class]);
306
307 18
            $metadata->setCache($cacheBuilder->build());
308
        }
309
310
        // Evaluate annotations on properties/fields
311
        /** @var ReflectionProperty $reflProperty */
312 373
        foreach ($reflectionClass->getProperties() as $reflectionProperty) {
313 373
            if ($reflectionProperty->getDeclaringClass()->getName() !== $reflectionClass->getName()) {
314 74
                continue;
315
            }
316
317 373
            $propertyAnnotations = $this->getPropertyAnnotations($reflectionProperty);
318 372
            $property            = $this->convertPropertyAnnotationsToProperty(
319 372
                $propertyAnnotations,
320 372
                $reflectionProperty,
321 372
                $classMetadata,
322 372
                $metadataBuildingContext
323
            );
324
325 372
            if ($classMetadata->isMappedSuperclass &&
326 372
                $property instanceof Mapping\ToManyAssociationMetadata &&
327 372
                ! $property->isOwningSide()) {
328 1
                throw Mapping\MappingException::illegalToManyAssociationOnMappedSuperclass(
329 1
                    $classMetadata->getClassName(),
330 1
                    $property->getName()
331
                );
332
            }
333
334 371
            $metadata->addProperty($property);
335
        }
336
337 370
        $this->attachPropertyOverrides($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext);
338
339 370
        return $classMetadata;
340
    }
341
342
    /**
343
     * @param Annotation\Annotation[] $classAnnotations
344
     *
345
     * @throws Mapping\MappingException
346
     * @throws UnexpectedValueException
347
     * @throws ReflectionException
348
     */
349 379
    private function convertClassAnnotationsToClassMetadata(
350
        array $classAnnotations,
351
        ReflectionClass $reflectionClass,
352
        Mapping\ClassMetadata $metadata,
353
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
354
    ) : Mapping\ClassMetadata {
355
        switch (true) {
356 379
            case isset($classAnnotations[Annotation\Entity::class]):
357 372
                return $this->convertClassAnnotationsToEntityClassMetadata(
358 372
                    $classAnnotations,
359 372
                    $reflectionClass,
360 372
                    $metadata,
361 372
                    $metadataBuildingContext
362
                );
363
364
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
365
366 29
            case isset($classAnnotations[Annotation\MappedSuperclass::class]):
367 23
                return $this->convertClassAnnotationsToMappedSuperClassMetadata(
368 23
                    $classAnnotations,
369 23
                    $reflectionClass,
370 23
                    $metadata
371
                );
372 6
            case isset($classAnnotations[Annotation\Embeddable::class]):
373
                return $this->convertClassAnnotationsToEmbeddableClassMetadata(
374
                    $classAnnotations,
375
                    $reflectionClass,
376
                    $metadata
377
                );
378
            default:
379 6
                throw Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass($reflectionClass->getName());
380
        }
381
    }
382
383
    /**
384
     * @param Annotation\Annotation[] $classAnnotations
385
     *
386
     * @return Mapping\ClassMetadata
387
     *
388
     * @throws Mapping\MappingException
389
     * @throws ReflectionException
390
     * @throws UnexpectedValueException
391
     */
392 372
    private function convertClassAnnotationsToEntityClassMetadata(
393
        array $classAnnotations,
394
        ReflectionClass $reflectionClass,
395
        Mapping\ClassMetadata $metadata,
396
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
397
    ) {
398
        /** @var Annotation\Entity $entityAnnot */
399 372
        $entityAnnot = $classAnnotations[Annotation\Entity::class];
400
401 372
        if ($entityAnnot->repositoryClass !== null) {
402 3
            $metadata->setCustomRepositoryClassName($entityAnnot->repositoryClass);
403
        }
404
405 372
        if ($entityAnnot->readOnly) {
406 1
            $metadata->asReadOnly();
407
        }
408
409 372
        $metadata->isMappedSuperclass = false;
410 372
        $metadata->isEmbeddedClass    = false;
411
412
        // Process table information
413 372
        $parent = $metadata->getParent();
414
415 372
        if ($parent && $parent->inheritanceType === Mapping\InheritanceType::SINGLE_TABLE) {
416
            // Handle the case where a middle mapped super class inherits from a single table inheritance tree.
417
            do {
418 29
                if (! $parent->isMappedSuperclass) {
419 29
                    $metadata->setTable($parent->table);
420
421 29
                    break;
422
                }
423
424 4
                $parent = $parent->getParent();
425 29
            } while ($parent !== null);
426
        } else {
427 372
            $tableBuilder = new Builder\TableMetadataBuilder($metadataBuildingContext);
428
429
            $tableBuilder
430 372
                ->withEntityClassMetadata($metadata)
431 372
                ->withTableAnnotation($classAnnotations[Annotation\Table::class] ?? null);
432
433 372
            $metadata->setTable($tableBuilder->build());
434
        }
435
436
        // Evaluate @ChangeTrackingPolicy annotation
437 372
        if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) {
438 6
            $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class];
439
440 6
            $metadata->setChangeTrackingPolicy(
441 6
                constant(sprintf('%s::%s', Mapping\ChangeTrackingPolicy::class, $changeTrackingAnnot->value))
0 ignored issues
show
Bug introduced by
Accessing value on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
442
            );
443
        }
444
445
        // Evaluate @InheritanceType annotation
446 372
        if (isset($classAnnotations[Annotation\InheritanceType::class])) {
447 80
            $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class];
448
449 80
            $metadata->setInheritanceType(
450 80
                constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value))
451
            );
452
453 80
            if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) {
454 80
                $discriminatorColumnBuilder = new Builder\DiscriminatorColumnMetadataBuilder($metadataBuildingContext);
455
456
                $discriminatorColumnBuilder
457 80
                    ->withComponentMetadata($metadata)
458 80
                    ->withDiscriminatorColumnAnnotation($classAnnotations[Annotation\DiscriminatorColumn::class] ?? null);
459
460 80
                $metadata->setDiscriminatorColumn($discriminatorColumnBuilder->build());
461
462
                // Evaluate DiscriminatorMap annotation
463 80
                if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) {
464 77
                    $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class];
465 77
                    $discriminatorMap           = $discriminatorMapAnnotation->value;
466
467 77
                    $metadata->setDiscriminatorMap($discriminatorMap);
468
                }
469
            }
470
        }
471
472 372
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
473 372
        $this->attachEntityListeners($classAnnotations, $metadata);
474
475 372
        return $metadata;
476
    }
477
478
    /**
479
     * @param Annotation\Annotation[] $classAnnotations
480
     *
481
     * @throws Mapping\MappingException
482
     * @throws ReflectionException
483
     */
484 23
    private function convertClassAnnotationsToMappedSuperClassMetadata(
485
        array $classAnnotations,
486
        ReflectionClass $reflectionClass,
487
        Mapping\ClassMetadata $metadata
488
    ) : Mapping\ClassMetadata {
489
        /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */
490 23
        $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class];
491
492 23
        if ($mappedSuperclassAnnot->repositoryClass !== null) {
493 2
            $metadata->setCustomRepositoryClassName($mappedSuperclassAnnot->repositoryClass);
494
        }
495
496 23
        $metadata->isMappedSuperclass = true;
497 23
        $metadata->isEmbeddedClass    = false;
498
499 23
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
500 23
        $this->attachEntityListeners($classAnnotations, $metadata);
501
502 23
        return $metadata;
503
    }
504
505
    /**
506
     * @param Annotation\Annotation[] $classAnnotations
507
     */
508
    private function convertClassAnnotationsToEmbeddableClassMetadata(
509
        array $classAnnotations,
0 ignored issues
show
Unused Code introduced by
The parameter $classAnnotations is not used and could be removed. ( Ignorable by Annotation )

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

509
        /** @scrutinizer ignore-unused */ array $classAnnotations,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
510
        ReflectionClass $reflectionClass,
0 ignored issues
show
Unused Code introduced by
The parameter $reflectionClass is not used and could be removed. ( Ignorable by Annotation )

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

510
        /** @scrutinizer ignore-unused */ ReflectionClass $reflectionClass,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
511
        Mapping\ClassMetadata $metadata
512
    ) : Mapping\ClassMetadata {
513
        $metadata->isMappedSuperclass = false;
514
        $metadata->isEmbeddedClass    = true;
515
516
        return $metadata;
517
    }
518
519
    /**
520
     * @param Annotation\Annotation[] $propertyAnnotations
521
     *
522
     * @todo guilhermeblanco Remove nullable typehint once embeddables are back
523
     */
524 372
    private function convertPropertyAnnotationsToProperty(
525
        array $propertyAnnotations,
526
        ReflectionProperty $reflectionProperty,
527
        Mapping\ClassMetadata $metadata,
528
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
529
    ) : ?Mapping\Property {
530
        switch (true) {
531 372
            case isset($propertyAnnotations[Annotation\Column::class]):
532 367
                return $this->convertReflectionPropertyToFieldMetadata(
533 367
                    $reflectionProperty,
534 367
                    $propertyAnnotations,
535 367
                    $metadata,
536 367
                    $metadataBuildingContext
537
                );
538 254
            case isset($propertyAnnotations[Annotation\OneToOne::class]):
539 111
                return $this->convertReflectionPropertyToOneToOneAssociationMetadata(
540 111
                    $reflectionProperty,
541 111
                    $propertyAnnotations,
542 111
                    $metadata,
543 111
                    $metadataBuildingContext
544
                );
545 202
            case isset($propertyAnnotations[Annotation\ManyToOne::class]):
546 141
                return $this->convertReflectionPropertyToManyToOneAssociationMetadata(
547 141
                    $reflectionProperty,
548 141
                    $propertyAnnotations,
549 141
                    $metadata,
550 141
                    $metadataBuildingContext
551
                );
552 163
            case isset($propertyAnnotations[Annotation\OneToMany::class]):
553 109
                return $this->convertReflectionPropertyToOneToManyAssociationMetadata(
554 109
                    $reflectionProperty,
555 109
                    $propertyAnnotations,
556 109
                    $metadata,
557 109
                    $metadataBuildingContext
558
                );
559 104
            case isset($propertyAnnotations[Annotation\ManyToMany::class]):
560 89
                return $this->convertReflectionPropertyToManyToManyAssociationMetadata(
561 89
                    $reflectionProperty,
562 89
                    $propertyAnnotations,
563 89
                    $metadata,
564 89
                    $metadataBuildingContext
565
                );
566 29
            case isset($propertyAnnotations[Annotation\Embedded::class]):
567
                return null;
568
            default:
569 29
                $transientBuilder = new Builder\TransientMetadataBuilder($metadataBuildingContext);
570
571
                $transientBuilder
572 29
                    ->withComponentMetadata($metadata)
573 29
                    ->withFieldName($reflectionProperty->getName());
574
575 29
                return $transientBuilder->build();
576
        }
577
    }
578
579
    /**
580
     * @param Annotation\Annotation[] $propertyAnnotations
581
     *
582
     * @throws Mapping\MappingException
583
     */
584 367
    private function convertReflectionPropertyToFieldMetadata(
585
        ReflectionProperty $reflectionProperty,
586
        array $propertyAnnotations,
587
        Mapping\ClassMetadata $metadata,
588
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
589
    ) : Mapping\FieldMetadata {
590 367
        $className   = $metadata->getClassName();
591 367
        $fieldName   = $reflectionProperty->getName();
592 367
        $isVersioned = isset($propertyAnnotations[Annotation\Version::class]);
593 367
        $columnAnnot = $propertyAnnotations[Annotation\Column::class];
594
595 367
        if ($columnAnnot->type === null) {
0 ignored issues
show
Bug introduced by
Accessing type on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
596
            throw Mapping\MappingException::propertyTypeIsRequired($className, $fieldName);
597
        }
598
599 367
        $fieldMetadata = new Mapping\FieldMetadata($fieldName);
600 367
        $columnName    = ! empty($columnAnnot->name)
0 ignored issues
show
Bug introduced by
Accessing name on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
601 77
            ? $columnAnnot->name
602 367
            : $metadataBuildingContext->getNamingStrategy()->propertyToColumnName($fieldName, $className);
603
604 367
        $fieldMetadata->setType(Type::getType($columnAnnot->type));
605 367
        $fieldMetadata->setVersioned($isVersioned);
606 367
        $fieldMetadata->setColumnName($columnName);
607
608 367
        if (! $metadata->isMappedSuperclass) {
609 360
            $fieldMetadata->setTableName($metadata->getTableName());
610
        }
611
612 367
        if (! empty($columnAnnot->columnDefinition)) {
0 ignored issues
show
Bug introduced by
Accessing columnDefinition on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
613 4
            $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition);
614
        }
615
616 367
        if (! empty($columnAnnot->length)) {
0 ignored issues
show
Bug introduced by
Accessing length on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
617 367
            $fieldMetadata->setLength($columnAnnot->length);
618
        }
619
620 367
        if ($columnAnnot->options) {
0 ignored issues
show
Bug introduced by
Accessing options on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
621 7
            $fieldMetadata->setOptions($columnAnnot->options);
622
        }
623
624 367
        $fieldMetadata->setScale($columnAnnot->scale);
0 ignored issues
show
Bug introduced by
Accessing scale on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
625 367
        $fieldMetadata->setPrecision($columnAnnot->precision);
0 ignored issues
show
Bug introduced by
Accessing precision on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
626 367
        $fieldMetadata->setNullable($columnAnnot->nullable);
0 ignored issues
show
Bug introduced by
Accessing nullable on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
627 367
        $fieldMetadata->setUnique($columnAnnot->unique);
0 ignored issues
show
Bug introduced by
Accessing unique on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
628
629
        // Check for Id
630 367
        if (isset($propertyAnnotations[Annotation\Id::class])) {
631 363
            $fieldMetadata->setPrimaryKey(true);
632
633 363
            if ($fieldMetadata->getType()->canRequireSQLConversion()) {
634
                throw Mapping\MappingException::sqlConversionNotAllowedForPrimaryKeyProperties($className, $fieldMetadata);
635
            }
636
        }
637
638
        // Prevent PK and version on same field
639 367
        if ($fieldMetadata->isPrimaryKey() && $fieldMetadata->isVersioned()) {
640
            throw Mapping\MappingException::cannotVersionIdField($className, $fieldName);
641
        }
642
643
        // Prevent column duplication
644 367
        if ($metadata->checkPropertyDuplication($columnName)) {
645
            throw Mapping\MappingException::duplicateColumnName($className, $columnName);
646
        }
647
648
        // Check for GeneratedValue strategy
649 367
        if (isset($propertyAnnotations[Annotation\GeneratedValue::class])) {
650 311
            $generatedValueAnnot = $propertyAnnotations[Annotation\GeneratedValue::class];
651 311
            $strategy            = strtoupper($generatedValueAnnot->strategy);
0 ignored issues
show
Bug introduced by
Accessing strategy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
652 311
            $idGeneratorType     = constant(sprintf('%s::%s', Mapping\GeneratorType::class, $strategy));
653
654 311
            if ($idGeneratorType !== Mapping\GeneratorType::NONE) {
655 291
                $idGeneratorDefinition = [];
656
657
                // Check for CustomGenerator/SequenceGenerator/TableGenerator definition
658
                switch (true) {
659 291
                    case isset($propertyAnnotations[Annotation\SequenceGenerator::class]):
660 9
                        $seqGeneratorAnnot = $propertyAnnotations[Annotation\SequenceGenerator::class];
661
662
                        $idGeneratorDefinition = [
663 9
                            'sequenceName' => $seqGeneratorAnnot->sequenceName,
0 ignored issues
show
Bug introduced by
Accessing sequenceName on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
664 9
                            'allocationSize' => $seqGeneratorAnnot->allocationSize,
0 ignored issues
show
Bug introduced by
Accessing allocationSize on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
665
                        ];
666
667 9
                        break;
668
669 282
                    case isset($propertyAnnotations[Annotation\CustomIdGenerator::class]):
670 3
                        $customGeneratorAnnot = $propertyAnnotations[Annotation\CustomIdGenerator::class];
671
672
                        $idGeneratorDefinition = [
673 3
                            'class' => $customGeneratorAnnot->class,
674 3
                            'arguments' => $customGeneratorAnnot->arguments,
675
                        ];
676
677 3
                        if (! isset($idGeneratorDefinition['class'])) {
678
                            throw new Mapping\MappingException(
679
                                sprintf('Cannot instantiate custom generator, no class has been defined')
680
                            );
681
                        }
682
683 3
                        if (! class_exists($idGeneratorDefinition['class'])) {
684
                            throw new Mapping\MappingException(
685
                                sprintf('Cannot instantiate custom generator : %s', var_export($idGeneratorDefinition, true))
686
                            );
687
                        }
688
689 3
                        break;
690
691
                    /** @todo If it is not supported, why does this exist? */
692 279
                    case isset($propertyAnnotations['Doctrine\ORM\Mapping\TableGenerator']):
693
                        throw Mapping\MappingException::tableIdGeneratorNotImplemented($className);
694
                }
695
696 291
                $fieldMetadata->setValueGenerator(
697 291
                    new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition)
698
                );
699
            }
700
        }
701
702 367
        return $fieldMetadata;
703
    }
704
705
    /**
706
     * @param Annotation\Annotation[] $propertyAnnotations
707
     */
708 111
    private function convertReflectionPropertyToOneToOneAssociationMetadata(
709
        ReflectionProperty $reflectionProperty,
710
        array $propertyAnnotations,
711
        Mapping\ClassMetadata $metadata,
712
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
713
    ) : Mapping\OneToOneAssociationMetadata {
714 111
        $className     = $metadata->getClassName();
715 111
        $fieldName     = $reflectionProperty->getName();
716 111
        $oneToOneAnnot = $propertyAnnotations[Annotation\OneToOne::class];
717 111
        $assocMetadata = new Mapping\OneToOneAssociationMetadata($fieldName);
718 111
        $targetEntity  = $oneToOneAnnot->targetEntity;
0 ignored issues
show
Bug introduced by
Accessing targetEntity on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
719
720 111
        $assocMetadata->setTargetEntity($targetEntity);
721 111
        $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToOneAnnot->cascade));
0 ignored issues
show
Bug introduced by
Accessing cascade on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
722 111
        $assocMetadata->setOrphanRemoval($oneToOneAnnot->orphanRemoval);
0 ignored issues
show
Bug introduced by
Accessing orphanRemoval on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
723 111
        $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToOneAnnot->fetch));
0 ignored issues
show
Bug introduced by
Accessing fetch on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
724
725 111
        if (! empty($oneToOneAnnot->mappedBy)) {
0 ignored issues
show
Bug introduced by
Accessing mappedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
726 40
            $assocMetadata->setMappedBy($oneToOneAnnot->mappedBy);
727 40
            $assocMetadata->setOwningSide(false);
728
        }
729
730 111
        if (! empty($oneToOneAnnot->inversedBy)) {
0 ignored issues
show
Bug introduced by
Accessing inversedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
731 51
            $assocMetadata->setInversedBy($oneToOneAnnot->inversedBy);
732
        }
733
734
        // Check for Id
735 111
        if (isset($propertyAnnotations[Annotation\Id::class])) {
736 12
            $assocMetadata->setPrimaryKey(true);
737
        }
738
739
        // Check for Cache
740 111
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
741 4
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
742
743
            $cacheBuilder
744 4
                ->withComponentMetadata($metadata)
745 4
                ->withFieldName($fieldName)
746 4
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
747
748 4
            $assocMetadata->setCache($cacheBuilder->build());
749
        }
750
751
        // Check for JoinColumn/JoinColumns annotations
752
        switch (true) {
753 111
            case isset($propertyAnnotations[Annotation\JoinColumn::class]):
754 79
                $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class];
755
756 79
                $assocMetadata->addJoinColumn(
757 79
                    $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
758
                );
759
760 79
                break;
761
762 53
            case isset($propertyAnnotations[Annotation\JoinColumns::class]):
763 3
                $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class];
764
765 3
                foreach ($joinColumnsAnnot->value as $joinColumnAnnot) {
766 3
                    $assocMetadata->addJoinColumn(
767 3
                        $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
768
                    );
769
                }
770
771 3
                break;
772
        }
773
774 111
        return $assocMetadata;
775
    }
776
777
    /**
778
     * @param Annotation\Annotation[] $propertyAnnotations
779
     */
780 141
    private function convertReflectionPropertyToManyToOneAssociationMetadata(
781
        ReflectionProperty $reflectionProperty,
782
        array $propertyAnnotations,
783
        Mapping\ClassMetadata $metadata,
784
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
785
    ) : Mapping\ManyToOneAssociationMetadata {
786 141
        $className      = $metadata->getClassName();
787 141
        $fieldName      = $reflectionProperty->getName();
788 141
        $manyToOneAnnot = $propertyAnnotations[Annotation\ManyToOne::class];
789 141
        $assocMetadata  = new Mapping\ManyToOneAssociationMetadata($fieldName);
790 141
        $targetEntity   = $manyToOneAnnot->targetEntity;
0 ignored issues
show
Bug introduced by
Accessing targetEntity on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
791
792 141
        $assocMetadata->setTargetEntity($targetEntity);
793 141
        $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToOneAnnot->cascade));
0 ignored issues
show
Bug introduced by
Accessing cascade on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
794 141
        $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToOneAnnot->fetch));
0 ignored issues
show
Bug introduced by
Accessing fetch on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
795
796 141
        if (! empty($manyToOneAnnot->inversedBy)) {
0 ignored issues
show
Bug introduced by
Accessing inversedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
797 94
            $assocMetadata->setInversedBy($manyToOneAnnot->inversedBy);
798
        }
799
800
        // Check for Id
801 141
        if (isset($propertyAnnotations[Annotation\Id::class])) {
802 34
            $assocMetadata->setPrimaryKey(true);
803
        }
804
805
        // Check for Cache
806 141
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
807 12
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
808
809
            $cacheBuilder
810 12
                ->withComponentMetadata($metadata)
811 12
                ->withFieldName($fieldName)
812 12
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
813
814 12
            $assocMetadata->setCache($cacheBuilder->build());
815
        }
816
817
        // Check for JoinColumn/JoinColumns annotations
818
        switch (true) {
819 141
            case isset($propertyAnnotations[Annotation\JoinColumn::class]):
820 81
                $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class];
821
822 81
                $assocMetadata->addJoinColumn(
823 81
                    $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
824
                );
825
826 81
                break;
827
828 69
            case isset($propertyAnnotations[Annotation\JoinColumns::class]):
829 16
                $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class];
830
831 16
                foreach ($joinColumnsAnnot->value as $joinColumnAnnot) {
832 16
                    $assocMetadata->addJoinColumn(
833 16
                        $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
834
                    );
835
                }
836
837 16
                break;
838
        }
839
840 141
        return $assocMetadata;
841
    }
842
843
    /**
844
     * @param Annotation\Annotation[] $propertyAnnotations
845
     *
846
     * @throws Mapping\MappingException
847
     */
848 109
    private function convertReflectionPropertyToOneToManyAssociationMetadata(
849
        ReflectionProperty $reflectionProperty,
850
        array $propertyAnnotations,
851
        Mapping\ClassMetadata $metadata,
852
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
853
    ) : Mapping\OneToManyAssociationMetadata {
854 109
        $className      = $metadata->getClassName();
855 109
        $fieldName      = $reflectionProperty->getName();
856 109
        $oneToManyAnnot = $propertyAnnotations[Annotation\OneToMany::class];
857 109
        $assocMetadata  = new Mapping\OneToManyAssociationMetadata($fieldName);
858 109
        $targetEntity   = $oneToManyAnnot->targetEntity;
0 ignored issues
show
Bug introduced by
Accessing targetEntity on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
859
860 109
        $assocMetadata->setTargetEntity($targetEntity);
861 109
        $assocMetadata->setCascade($this->getCascade($className, $fieldName, $oneToManyAnnot->cascade));
0 ignored issues
show
Bug introduced by
Accessing cascade on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
862 109
        $assocMetadata->setOrphanRemoval($oneToManyAnnot->orphanRemoval);
0 ignored issues
show
Bug introduced by
Accessing orphanRemoval on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
863 109
        $assocMetadata->setFetchMode($this->getFetchMode($className, $oneToManyAnnot->fetch));
0 ignored issues
show
Bug introduced by
Accessing fetch on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
864 109
        $assocMetadata->setOwningSide(false);
865 109
        $assocMetadata->setMappedBy($oneToManyAnnot->mappedBy);
0 ignored issues
show
Bug introduced by
Accessing mappedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
866
867 109
        if (! empty($oneToManyAnnot->indexBy)) {
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
868 8
            $assocMetadata->setIndexedBy($oneToManyAnnot->indexBy);
869
        }
870
871
        // Check for OrderBy
872 109
        if (isset($propertyAnnotations[Annotation\OrderBy::class])) {
873 14
            $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class];
874
875 14
            $assocMetadata->setOrderBy($orderByAnnot->value);
0 ignored issues
show
Bug introduced by
Accessing value on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
876
        }
877
878
        // Check for Id
879 109
        if (isset($propertyAnnotations[Annotation\Id::class])) {
880
            throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName);
881
        }
882
883
        // Check for Cache
884 109
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
885 9
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
886
887
            $cacheBuilder
888 9
                ->withComponentMetadata($metadata)
889 9
                ->withFieldName($fieldName)
890 9
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
891
892 9
            $assocMetadata->setCache($cacheBuilder->build());
893
        }
894
895 109
        return $assocMetadata;
896
    }
897
898
    /**
899
     * @param Annotation\Annotation[] $propertyAnnotations
900
     *
901
     * @throws Mapping\MappingException
902
     */
903 89
    private function convertReflectionPropertyToManyToManyAssociationMetadata(
904
        ReflectionProperty $reflectionProperty,
905
        array $propertyAnnotations,
906
        Mapping\ClassMetadata $metadata,
907
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
908
    ) : Mapping\ManyToManyAssociationMetadata {
909 89
        $className       = $metadata->getClassName();
910 89
        $fieldName       = $reflectionProperty->getName();
911 89
        $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class];
912 89
        $assocMetadata   = new Mapping\ManyToManyAssociationMetadata($fieldName);
913 89
        $targetEntity    = $manyToManyAnnot->targetEntity;
0 ignored issues
show
Bug introduced by
Accessing targetEntity on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
914
915 89
        $assocMetadata->setTargetEntity($targetEntity);
916 89
        $assocMetadata->setCascade($this->getCascade($className, $fieldName, $manyToManyAnnot->cascade));
0 ignored issues
show
Bug introduced by
Accessing cascade on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
917 89
        $assocMetadata->setOrphanRemoval($manyToManyAnnot->orphanRemoval);
0 ignored issues
show
Bug introduced by
Accessing orphanRemoval on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
918 89
        $assocMetadata->setFetchMode($this->getFetchMode($className, $manyToManyAnnot->fetch));
0 ignored issues
show
Bug introduced by
Accessing fetch on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
919
920 89
        if (! empty($manyToManyAnnot->mappedBy)) {
0 ignored issues
show
Bug introduced by
Accessing mappedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
921 36
            $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy);
922 36
            $assocMetadata->setOwningSide(false);
923
        }
924
925 89
        if (! empty($manyToManyAnnot->inversedBy)) {
0 ignored issues
show
Bug introduced by
Accessing inversedBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
926 45
            $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy);
927
        }
928
929 89
        if (! empty($manyToManyAnnot->indexBy)) {
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
930 3
            $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy);
931
        }
932
933
        // Check for JoinTable
934 89
        if (isset($propertyAnnotations[Annotation\JoinTable::class])) {
935 71
            $joinTableAnnot    = $propertyAnnotations[Annotation\JoinTable::class];
936 71
            $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot);
937
938 71
            $assocMetadata->setJoinTable($joinTableMetadata);
939
        }
940
941
        // Check for OrderBy
942 89
        if (isset($propertyAnnotations[Annotation\OrderBy::class])) {
943 3
            $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class];
944
945 3
            $assocMetadata->setOrderBy($orderByAnnot->value);
0 ignored issues
show
Bug introduced by
Accessing value on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
946
        }
947
948
        // Check for Id
949 89
        if (isset($propertyAnnotations[Annotation\Id::class])) {
950
            throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName);
951
        }
952
953
        // Check for Cache
954 89
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
955 2
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
956
957
            $cacheBuilder
958 2
                ->withComponentMetadata($metadata)
959 2
                ->withFieldName($fieldName)
960 2
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
961
962 2
            $assocMetadata->setCache($cacheBuilder->build());
963
        }
964
965 89
        return $assocMetadata;
966
    }
967
968
    /**
969
     * Parse the given Column as FieldMetadata
970
     */
971 3
    private function convertColumnAnnotationToFieldMetadata(
972
        Annotation\Column $columnAnnot,
973
        string $fieldName,
974
        bool $isVersioned
975
    ) : Mapping\FieldMetadata {
976 3
        $fieldMetadata = new Mapping\FieldMetadata($fieldName);
977
978 3
        $fieldMetadata->setType(Type::getType($columnAnnot->type));
979 3
        $fieldMetadata->setVersioned($isVersioned);
980
981 3
        if (! empty($columnAnnot->name)) {
982 3
            $fieldMetadata->setColumnName($columnAnnot->name);
983
        }
984
985 3
        if (! empty($columnAnnot->columnDefinition)) {
986
            $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition);
987
        }
988
989 3
        if (! empty($columnAnnot->length)) {
990 3
            $fieldMetadata->setLength($columnAnnot->length);
991
        }
992
993 3
        if ($columnAnnot->options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $columnAnnot->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...
994
            $fieldMetadata->setOptions($columnAnnot->options);
995
        }
996
997 3
        $fieldMetadata->setScale($columnAnnot->scale);
998 3
        $fieldMetadata->setPrecision($columnAnnot->precision);
999 3
        $fieldMetadata->setNullable($columnAnnot->nullable);
1000 3
        $fieldMetadata->setUnique($columnAnnot->unique);
1001
1002 3
        return $fieldMetadata;
1003
    }
1004
1005
    /**
1006
     * Parse the given JoinTable as JoinTableMetadata
1007
     */
1008 71
    private function convertJoinTableAnnotationToJoinTableMetadata(
1009
        Annotation\JoinTable $joinTableAnnot
1010
    ) : Mapping\JoinTableMetadata {
1011 71
        $joinTable = new Mapping\JoinTableMetadata();
1012
1013 71
        if (! empty($joinTableAnnot->name)) {
1014 69
            $joinTable->setName($joinTableAnnot->name);
1015
        }
1016
1017 71
        if (! empty($joinTableAnnot->schema)) {
1018
            $joinTable->setSchema($joinTableAnnot->schema);
1019
        }
1020
1021 71
        foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) {
1022 70
            $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1023
1024 70
            $joinTable->addJoinColumn($joinColumn);
1025
        }
1026
1027 71
        foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) {
1028 70
            $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1029
1030 70
            $joinTable->addInverseJoinColumn($joinColumn);
1031
        }
1032
1033 71
        return $joinTable;
1034
    }
1035
1036
    /**
1037
     * Parse the given JoinColumn as JoinColumnMetadata
1038
     */
1039 181
    private function convertJoinColumnAnnotationToJoinColumnMetadata(
1040
        Annotation\JoinColumn $joinColumnAnnot
1041
    ) : Mapping\JoinColumnMetadata {
1042 181
        $joinColumn = new Mapping\JoinColumnMetadata();
1043
1044
        // @todo Remove conditionals for name and referencedColumnName once naming strategy is brought into drivers
1045 181
        if (! empty($joinColumnAnnot->name)) {
1046 175
            $joinColumn->setColumnName($joinColumnAnnot->name);
1047
        }
1048
1049 181
        if (! empty($joinColumnAnnot->referencedColumnName)) {
1050 181
            $joinColumn->setReferencedColumnName($joinColumnAnnot->referencedColumnName);
1051
        }
1052
1053 181
        $joinColumn->setNullable($joinColumnAnnot->nullable);
1054 181
        $joinColumn->setUnique($joinColumnAnnot->unique);
1055
1056 181
        if (! empty($joinColumnAnnot->fieldName)) {
1057
            $joinColumn->setAliasedName($joinColumnAnnot->fieldName);
1058
        }
1059
1060 181
        if (! empty($joinColumnAnnot->columnDefinition)) {
1061 3
            $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition);
1062
        }
1063
1064 181
        if ($joinColumnAnnot->onDelete) {
1065 16
            $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete));
1066
        }
1067
1068 181
        return $joinColumn;
1069
    }
1070
1071
    /**
1072
     * @param Annotation\Annotation[] $classAnnotations
1073
     */
1074 373
    private function attachLifecycleCallbacks(
1075
        array $classAnnotations,
1076
        ReflectionClass $reflectionClass,
1077
        Mapping\ClassMetadata $metadata
1078
    ) : void {
1079
        // Evaluate @HasLifecycleCallbacks annotation
1080 373
        if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) {
1081
            $eventMap = [
1082 14
                Events::prePersist  => Annotation\PrePersist::class,
1083 14
                Events::postPersist => Annotation\PostPersist::class,
1084 14
                Events::preUpdate   => Annotation\PreUpdate::class,
1085 14
                Events::postUpdate  => Annotation\PostUpdate::class,
1086 14
                Events::preRemove   => Annotation\PreRemove::class,
1087 14
                Events::postRemove  => Annotation\PostRemove::class,
1088 14
                Events::postLoad    => Annotation\PostLoad::class,
1089 14
                Events::preFlush    => Annotation\PreFlush::class,
1090
            ];
1091
1092
            /** @var ReflectionMethod $reflectionMethod */
1093 14
            foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
1094 13
                $annotations = $this->getMethodAnnotations($reflectionMethod);
1095
1096 13
                foreach ($eventMap as $eventName => $annotationClassName) {
1097 13
                    if (isset($annotations[$annotationClassName])) {
1098 12
                        $metadata->addLifecycleCallback($eventName, $reflectionMethod->getName());
1099
                    }
1100
                }
1101
            }
1102
        }
1103 373
    }
1104
1105
    /**
1106
     * @param Annotation\Annotation[] $classAnnotations
1107
     *
1108
     * @throws ReflectionException
1109
     * @throws Mapping\MappingException
1110
     */
1111 373
    private function attachEntityListeners(
1112
        array $classAnnotations,
1113
        Mapping\ClassMetadata $metadata
1114
    ) : void {
1115
        // Evaluate @EntityListeners annotation
1116 373
        if (isset($classAnnotations[Annotation\EntityListeners::class])) {
1117
            /** @var Annotation\EntityListeners $entityListenersAnnot */
1118 8
            $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class];
1119
            $eventMap             = [
1120 8
                Events::prePersist  => Annotation\PrePersist::class,
1121 8
                Events::postPersist => Annotation\PostPersist::class,
1122 8
                Events::preUpdate   => Annotation\PreUpdate::class,
1123 8
                Events::postUpdate  => Annotation\PostUpdate::class,
1124 8
                Events::preRemove   => Annotation\PreRemove::class,
1125 8
                Events::postRemove  => Annotation\PostRemove::class,
1126 8
                Events::postLoad    => Annotation\PostLoad::class,
1127 8
                Events::preFlush    => Annotation\PreFlush::class,
1128
            ];
1129
1130 8
            foreach ($entityListenersAnnot->value as $listenerClassName) {
1131 8
                if (! class_exists($listenerClassName)) {
1132
                    throw Mapping\MappingException::entityListenerClassNotFound(
1133
                        $listenerClassName,
1134
                        $metadata->getClassName()
1135
                    );
1136
                }
1137
1138 8
                $listenerClass = new ReflectionClass($listenerClassName);
1139
1140
                /** @var ReflectionMethod $reflectionMethod */
1141 8
                foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
1142 8
                    $annotations = $this->getMethodAnnotations($reflectionMethod);
1143
1144 8
                    foreach ($eventMap as $eventName => $annotationClassName) {
1145 8
                        if (isset($annotations[$annotationClassName])) {
1146 6
                            $metadata->addEntityListener($eventName, $listenerClassName, $reflectionMethod->getName());
1147
                        }
1148
                    }
1149
                }
1150
            }
1151
        }
1152 373
    }
1153
1154
    /**
1155
     * @param Annotation\Annotation[] $classAnnotations
1156
     *
1157
     * @throws Mapping\MappingException
1158
     */
1159 370
    private function attachPropertyOverrides(
1160
        array $classAnnotations,
1161
        ReflectionClass $reflectionClass,
0 ignored issues
show
Unused Code introduced by
The parameter $reflectionClass is not used and could be removed. ( Ignorable by Annotation )

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

1161
        /** @scrutinizer ignore-unused */ ReflectionClass $reflectionClass,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1162
        Mapping\ClassMetadata $metadata,
1163
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
0 ignored issues
show
Unused Code introduced by
The parameter $metadataBuildingContext is not used and could be removed. ( Ignorable by Annotation )

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

1163
        /** @scrutinizer ignore-unused */ Mapping\ClassMetadataBuildingContext $metadataBuildingContext

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1164
    ) : void {
1165
        // Evaluate AssociationOverrides annotation
1166 370
        if (isset($classAnnotations[Annotation\AssociationOverrides::class])) {
1167 5
            $associationOverridesAnnot = $classAnnotations[Annotation\AssociationOverrides::class];
1168
1169 5
            foreach ($associationOverridesAnnot->value as $associationOverride) {
0 ignored issues
show
Bug introduced by
Accessing value on the interface Doctrine\ORM\Annotation\Annotation suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1170 5
                $fieldName = $associationOverride->name;
1171 5
                $property  = $metadata->getProperty($fieldName);
1172
1173 5
                if (! $property) {
1174
                    throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName);
1175
                }
1176
1177 5
                $existingClass = get_class($property);
1178 5
                $override      = new $existingClass($fieldName);
1179
1180
                // Check for JoinColumn/JoinColumns annotations
1181 5
                if ($associationOverride->joinColumns) {
1182 3
                    $joinColumns = [];
1183
1184 3
                    foreach ($associationOverride->joinColumns as $joinColumnAnnot) {
1185 3
                        $joinColumns[] = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1186
                    }
1187
1188 3
                    $override->setJoinColumns($joinColumns);
1189
                }
1190
1191
                // Check for JoinTable annotations
1192 5
                if ($associationOverride->joinTable) {
1193 2
                    $joinTableAnnot    = $associationOverride->joinTable;
1194 2
                    $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot);
1195
1196 2
                    $override->setJoinTable($joinTableMetadata);
1197
                }
1198
1199
                // Check for inversedBy
1200 5
                if ($associationOverride->inversedBy) {
1201 1
                    $override->setInversedBy($associationOverride->inversedBy);
1202
                }
1203
1204
                // Check for fetch
1205 5
                if ($associationOverride->fetch) {
1206 1
                    $override->setFetchMode(
1207 1
                        constant(Mapping\FetchMode::class . '::' . $associationOverride->fetch)
1208
                    );
1209
                }
1210
1211 5
                $metadata->setPropertyOverride($override);
1212
            }
1213
        }
1214
1215
        // Evaluate AttributeOverrides annotation
1216 370
        if (isset($classAnnotations[Annotation\AttributeOverrides::class])) {
1217 3
            $attributeOverridesAnnot = $classAnnotations[Annotation\AttributeOverrides::class];
1218
1219 3
            foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) {
1220 3
                $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata(
1221 3
                    $attributeOverrideAnnot->column,
1222 3
                    $attributeOverrideAnnot->name,
1223 3
                    false
1224
                );
1225
1226 3
                $metadata->setPropertyOverride($fieldMetadata);
1227
            }
1228
        }
1229 370
    }
1230
1231
    /**
1232
     * Attempts to resolve the cascade modes.
1233
     *
1234
     * @param string   $className        The class name.
1235
     * @param string   $fieldName        The field name.
1236
     * @param string[] $originalCascades The original unprocessed field cascades.
1237
     *
1238
     * @return string[] The processed field cascades.
1239
     *
1240
     * @throws Mapping\MappingException If a cascade option is not valid.
1241
     */
1242 251
    private function getCascade(string $className, string $fieldName, array $originalCascades) : array
1243
    {
1244 251
        $cascadeTypes = ['remove', 'persist', 'refresh'];
1245 251
        $cascades     = array_map('strtolower', $originalCascades);
1246
1247 251
        if (in_array('all', $cascades, true)) {
1248 23
            $cascades = $cascadeTypes;
1249
        }
1250
1251 251
        if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) {
1252
            $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes));
1253
1254
            throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName);
1255
        }
1256
1257 251
        return $cascades;
1258
    }
1259
1260
    /**
1261
     * Attempts to resolve the fetch mode.
1262
     *
1263
     * @param string $className The class name.
1264
     * @param string $fetchMode The fetch mode.
1265
     *
1266
     * @return string The fetch mode as defined in ClassMetadata.
1267
     *
1268
     * @throws Mapping\MappingException If the fetch mode is not valid.
1269
     */
1270 251
    private function getFetchMode($className, $fetchMode) : string
1271
    {
1272 251
        $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode);
1273
1274 251
        if (! defined($fetchModeConstant)) {
1275
            throw Mapping\MappingException::invalidFetchMode($className, $fetchMode);
1276
        }
1277
1278 251
        return constant($fetchModeConstant);
1279
    }
1280
1281
    /**
1282
     * @return Annotation\Annotation[]
1283
     */
1284 379
    private function getClassAnnotations(ReflectionClass $reflectionClass) : array
1285
    {
1286 379
        $classAnnotations = $this->reader->getClassAnnotations($reflectionClass);
1287
1288 379
        foreach ($classAnnotations as $key => $annot) {
1289 373
            if (! is_numeric($key)) {
1290
                continue;
1291
            }
1292
1293 373
            $classAnnotations[get_class($annot)] = $annot;
1294
        }
1295
1296 379
        return $classAnnotations;
1297
    }
1298
1299
    /**
1300
     * @return Annotation\Annotation[]
1301
     */
1302 373
    private function getPropertyAnnotations(ReflectionProperty $reflectionProperty) : array
1303
    {
1304 373
        $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty);
1305
1306 372
        foreach ($propertyAnnotations as $key => $annot) {
1307 372
            if (! is_numeric($key)) {
1308
                continue;
1309
            }
1310
1311 372
            $propertyAnnotations[get_class($annot)] = $annot;
1312
        }
1313
1314 372
        return $propertyAnnotations;
1315
    }
1316
1317
    /**
1318
     * @return Annotation\Annotation[]
1319
     */
1320 21
    private function getMethodAnnotations(ReflectionMethod $reflectionMethod) : array
1321
    {
1322 21
        $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod);
1323
1324 21
        foreach ($methodAnnotations as $key => $annot) {
1325 18
            if (! is_numeric($key)) {
1326
                continue;
1327
            }
1328
1329 18
            $methodAnnotations[get_class($annot)] = $annot;
1330
        }
1331
1332 21
        return $methodAnnotations;
1333
    }
1334
}
1335