Passed
Push — master ( 3cda3f...c35142 )
by Guilherme
09:24
created

AnnotationDriver::attachPropertyOverrides()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 68
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 11.0033

Importance

Changes 0
Metric Value
cc 11
eloc 32
nc 7
nop 4
dl 0
loc 68
ccs 32
cts 33
cp 0.9697
crap 11.0033
rs 7.3166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php /** @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
                ->withEntityClassMetadata($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
432
            // Evaluate @Table annotation
433 372
            if (isset($classAnnotations[Annotation\Table::class])) {
434 191
                $tableBuilder->withTableAnnotation($classAnnotations[Annotation\Table::class]);
435
            }
436
437 372
            $metadata->setTable($tableBuilder->build());
438
        }
439
440
        // Evaluate @ChangeTrackingPolicy annotation
441 372
        if (isset($classAnnotations[Annotation\ChangeTrackingPolicy::class])) {
442 6
            $changeTrackingAnnot = $classAnnotations[Annotation\ChangeTrackingPolicy::class];
443
444 6
            $metadata->setChangeTrackingPolicy(
445 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...
446
            );
447
        }
448
449
        // Evaluate @InheritanceType annotation
450 372
        if (isset($classAnnotations[Annotation\InheritanceType::class])) {
451 80
            $inheritanceTypeAnnot = $classAnnotations[Annotation\InheritanceType::class];
452
453 80
            $metadata->setInheritanceType(
454 80
                constant(sprintf('%s::%s', Mapping\InheritanceType::class, $inheritanceTypeAnnot->value))
455
            );
456
457 80
            if ($metadata->inheritanceType !== Mapping\InheritanceType::NONE) {
458 80
                $this->attachDiscriminatorColumn($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext);
459
            }
460
        }
461
462 372
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
463 372
        $this->attachEntityListeners($classAnnotations, $metadata);
464
465 372
        return $metadata;
466
    }
467
468
    /**
469
     * @param Annotation\Annotation[] $classAnnotations
470
     *
471
     * @throws Mapping\MappingException
472
     * @throws ReflectionException
473
     */
474 23
    private function convertClassAnnotationsToMappedSuperClassMetadata(
475
        array $classAnnotations,
476
        ReflectionClass $reflectionClass,
477
        Mapping\ClassMetadata $metadata
478
    ) : Mapping\ClassMetadata {
479
        /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */
480 23
        $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class];
481
482 23
        if ($mappedSuperclassAnnot->repositoryClass !== null) {
483 2
            $metadata->setCustomRepositoryClassName($mappedSuperclassAnnot->repositoryClass);
484
        }
485
486 23
        $metadata->isMappedSuperclass = true;
487 23
        $metadata->isEmbeddedClass    = false;
488
489 23
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
490 23
        $this->attachEntityListeners($classAnnotations, $metadata);
491
492 23
        return $metadata;
493
    }
494
495
    /**
496
     * @param Annotation\Annotation[] $classAnnotations
497
     */
498
    private function convertClassAnnotationsToEmbeddableClassMetadata(
499
        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

499
        /** @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...
500
        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

500
        /** @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...
501
        Mapping\ClassMetadata $metadata
502
    ) : Mapping\ClassMetadata {
503
        $metadata->isMappedSuperclass = false;
504
        $metadata->isEmbeddedClass    = true;
505
506
        return $metadata;
507
    }
508
509
    /**
510
     * @param Annotation\Annotation[] $propertyAnnotations
511
     *
512
     * @todo guilhermeblanco Remove nullable typehint once embeddables are back
513
     */
514 372
    private function convertPropertyAnnotationsToProperty(
515
        array $propertyAnnotations,
516
        ReflectionProperty $reflectionProperty,
517
        Mapping\ClassMetadata $metadata,
518
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
519
    ) : ?Mapping\Property {
520
        switch (true) {
521 372
            case isset($propertyAnnotations[Annotation\Column::class]):
522 367
                return $this->convertReflectionPropertyToFieldMetadata(
523 367
                    $reflectionProperty,
524 367
                    $propertyAnnotations,
525 367
                    $metadata,
526 367
                    $metadataBuildingContext
527
                );
528 254
            case isset($propertyAnnotations[Annotation\OneToOne::class]):
529 111
                return $this->convertReflectionPropertyToOneToOneAssociationMetadata(
530 111
                    $reflectionProperty,
531 111
                    $propertyAnnotations,
532 111
                    $metadata,
533 111
                    $metadataBuildingContext
534
                );
535 202
            case isset($propertyAnnotations[Annotation\ManyToOne::class]):
536 141
                return $this->convertReflectionPropertyToManyToOneAssociationMetadata(
537 141
                    $reflectionProperty,
538 141
                    $propertyAnnotations,
539 141
                    $metadata,
540 141
                    $metadataBuildingContext
541
                );
542 163
            case isset($propertyAnnotations[Annotation\OneToMany::class]):
543 109
                return $this->convertReflectionPropertyToOneToManyAssociationMetadata(
544 109
                    $reflectionProperty,
545 109
                    $propertyAnnotations,
546 109
                    $metadata,
547 109
                    $metadataBuildingContext
548
                );
549 104
            case isset($propertyAnnotations[Annotation\ManyToMany::class]):
550 89
                return $this->convertReflectionPropertyToManyToManyAssociationMetadata(
551 89
                    $reflectionProperty,
552 89
                    $propertyAnnotations,
553 89
                    $metadata,
554 89
                    $metadataBuildingContext
555
                );
556 29
            case isset($propertyAnnotations[Annotation\Embedded::class]):
557
                return null;
558
            default:
559 29
                return new Mapping\TransientMetadata($reflectionProperty->getName());
560
        }
561
    }
562
563
    /**
564
     * @param Annotation\Annotation[] $propertyAnnotations
565
     *
566
     * @throws Mapping\MappingException
567
     */
568 367
    private function convertReflectionPropertyToFieldMetadata(
569
        ReflectionProperty $reflectionProperty,
570
        array $propertyAnnotations,
571
        Mapping\ClassMetadata $metadata,
572
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
573
    ) : Mapping\FieldMetadata {
574 367
        $className   = $metadata->getClassName();
575 367
        $fieldName   = $reflectionProperty->getName();
576 367
        $isVersioned = isset($propertyAnnotations[Annotation\Version::class]);
577 367
        $columnAnnot = $propertyAnnotations[Annotation\Column::class];
578
579 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...
580
            throw Mapping\MappingException::propertyTypeIsRequired($className, $fieldName);
581
        }
582
583 367
        $fieldMetadata = new Mapping\FieldMetadata($fieldName);
584 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...
585 77
            ? $columnAnnot->name
586 367
            : $metadataBuildingContext->getNamingStrategy()->propertyToColumnName($fieldName, $className);
587
588 367
        $fieldMetadata->setType(Type::getType($columnAnnot->type));
589 367
        $fieldMetadata->setVersioned($isVersioned);
590 367
        $fieldMetadata->setColumnName($columnName);
591
592 367
        if (! $metadata->isMappedSuperclass) {
593 360
            $fieldMetadata->setTableName($metadata->getTableName());
594
        }
595
596 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...
597 4
            $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition);
598
        }
599
600 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...
601 367
            $fieldMetadata->setLength($columnAnnot->length);
602
        }
603
604 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...
605 7
            $fieldMetadata->setOptions($columnAnnot->options);
606
        }
607
608 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...
609 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...
610 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...
611 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...
612
613
        // Check for Id
614 367
        if (isset($propertyAnnotations[Annotation\Id::class])) {
615 363
            $fieldMetadata->setPrimaryKey(true);
616
617 363
            if ($fieldMetadata->getType()->canRequireSQLConversion()) {
618
                throw Mapping\MappingException::sqlConversionNotAllowedForPrimaryKeyProperties($className, $fieldMetadata);
619
            }
620
        }
621
622
        // Prevent PK and version on same field
623 367
        if ($fieldMetadata->isPrimaryKey() && $fieldMetadata->isVersioned()) {
624
            throw Mapping\MappingException::cannotVersionIdField($className, $fieldName);
625
        }
626
627
        // Prevent column duplication
628 367
        if ($metadata->checkPropertyDuplication($columnName)) {
629
            throw Mapping\MappingException::duplicateColumnName($className, $columnName);
630
        }
631
632
        // Check for GeneratedValue strategy
633 367
        if (isset($propertyAnnotations[Annotation\GeneratedValue::class])) {
634 311
            $generatedValueAnnot = $propertyAnnotations[Annotation\GeneratedValue::class];
635 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...
636 311
            $idGeneratorType     = constant(sprintf('%s::%s', Mapping\GeneratorType::class, $strategy));
637
638 311
            if ($idGeneratorType !== Mapping\GeneratorType::NONE) {
639 291
                $idGeneratorDefinition = [];
640
641
                // Check for CustomGenerator/SequenceGenerator/TableGenerator definition
642
                switch (true) {
643 291
                    case isset($propertyAnnotations[Annotation\SequenceGenerator::class]):
644 9
                        $seqGeneratorAnnot = $propertyAnnotations[Annotation\SequenceGenerator::class];
645
646
                        $idGeneratorDefinition = [
647 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...
648 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...
649
                        ];
650
651 9
                        break;
652
653 282
                    case isset($propertyAnnotations[Annotation\CustomIdGenerator::class]):
654 3
                        $customGeneratorAnnot = $propertyAnnotations[Annotation\CustomIdGenerator::class];
655
656
                        $idGeneratorDefinition = [
657 3
                            'class' => $customGeneratorAnnot->class,
658 3
                            'arguments' => $customGeneratorAnnot->arguments,
659
                        ];
660
661 3
                        if (! isset($idGeneratorDefinition['class'])) {
662
                            throw new Mapping\MappingException(
663
                                sprintf('Cannot instantiate custom generator, no class has been defined')
664
                            );
665
                        }
666
667 3
                        if (! class_exists($idGeneratorDefinition['class'])) {
668
                            throw new Mapping\MappingException(
669
                                sprintf('Cannot instantiate custom generator : %s', var_export($idGeneratorDefinition, true))
670
                            );
671
                        }
672
673 3
                        break;
674
675
                    /** @todo If it is not supported, why does this exist? */
676 279
                    case isset($propertyAnnotations['Doctrine\ORM\Mapping\TableGenerator']):
677
                        throw Mapping\MappingException::tableIdGeneratorNotImplemented($className);
678
                }
679
680 291
                $fieldMetadata->setValueGenerator(
681 291
                    new Mapping\ValueGeneratorMetadata($idGeneratorType, $idGeneratorDefinition)
682
                );
683
            }
684
        }
685
686 367
        return $fieldMetadata;
687
    }
688
689
    /**
690
     * @param Annotation\Annotation[] $propertyAnnotations
691
     */
692 111
    private function convertReflectionPropertyToOneToOneAssociationMetadata(
693
        ReflectionProperty $reflectionProperty,
694
        array $propertyAnnotations,
695
        Mapping\ClassMetadata $metadata,
696
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
697
    ) : Mapping\OneToOneAssociationMetadata {
698 111
        $className     = $metadata->getClassName();
699 111
        $fieldName     = $reflectionProperty->getName();
700 111
        $oneToOneAnnot = $propertyAnnotations[Annotation\OneToOne::class];
701 111
        $assocMetadata = new Mapping\OneToOneAssociationMetadata($fieldName);
702 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...
703
704 111
        $assocMetadata->setTargetEntity($targetEntity);
705 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...
706 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...
707 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...
708
709 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...
710 40
            $assocMetadata->setMappedBy($oneToOneAnnot->mappedBy);
711 40
            $assocMetadata->setOwningSide(false);
712
        }
713
714 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...
715 51
            $assocMetadata->setInversedBy($oneToOneAnnot->inversedBy);
716
        }
717
718
        // Check for Id
719 111
        if (isset($propertyAnnotations[Annotation\Id::class])) {
720 12
            $assocMetadata->setPrimaryKey(true);
721
        }
722
723
        // Check for Cache
724 111
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
725 4
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
726
727
            $cacheBuilder
728 4
                ->withEntityClassMetadata($metadata)
729 4
                ->withFieldName($fieldName)
730 4
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
731
732 4
            $assocMetadata->setCache($cacheBuilder->build());
733
        }
734
735
        // Check for JoinColumn/JoinColumns annotations
736
        switch (true) {
737 111
            case isset($propertyAnnotations[Annotation\JoinColumn::class]):
738 79
                $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class];
739
740 79
                $assocMetadata->addJoinColumn(
741 79
                    $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
742
                );
743
744 79
                break;
745
746 53
            case isset($propertyAnnotations[Annotation\JoinColumns::class]):
747 3
                $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class];
748
749 3
                foreach ($joinColumnsAnnot->value as $joinColumnAnnot) {
750 3
                    $assocMetadata->addJoinColumn(
751 3
                        $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
752
                    );
753
                }
754
755 3
                break;
756
        }
757
758 111
        return $assocMetadata;
759
    }
760
761
    /**
762
     * @param Annotation\Annotation[] $propertyAnnotations
763
     */
764 141
    private function convertReflectionPropertyToManyToOneAssociationMetadata(
765
        ReflectionProperty $reflectionProperty,
766
        array $propertyAnnotations,
767
        Mapping\ClassMetadata $metadata,
768
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
769
    ) : Mapping\ManyToOneAssociationMetadata {
770 141
        $className      = $metadata->getClassName();
771 141
        $fieldName      = $reflectionProperty->getName();
772 141
        $manyToOneAnnot = $propertyAnnotations[Annotation\ManyToOne::class];
773 141
        $assocMetadata  = new Mapping\ManyToOneAssociationMetadata($fieldName);
774 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...
775
776 141
        $assocMetadata->setTargetEntity($targetEntity);
777 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...
778 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...
779
780 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...
781 94
            $assocMetadata->setInversedBy($manyToOneAnnot->inversedBy);
782
        }
783
784
        // Check for Id
785 141
        if (isset($propertyAnnotations[Annotation\Id::class])) {
786 34
            $assocMetadata->setPrimaryKey(true);
787
        }
788
789
        // Check for Cache
790 141
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
791 12
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
792
793
            $cacheBuilder
794 12
                ->withEntityClassMetadata($metadata)
795 12
                ->withFieldName($fieldName)
796 12
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
797
798 12
            $assocMetadata->setCache($cacheBuilder->build());
799
        }
800
801
        // Check for JoinColumn/JoinColumns annotations
802
        switch (true) {
803 141
            case isset($propertyAnnotations[Annotation\JoinColumn::class]):
804 81
                $joinColumnAnnot = $propertyAnnotations[Annotation\JoinColumn::class];
805
806 81
                $assocMetadata->addJoinColumn(
807 81
                    $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
808
                );
809
810 81
                break;
811
812 69
            case isset($propertyAnnotations[Annotation\JoinColumns::class]):
813 16
                $joinColumnsAnnot = $propertyAnnotations[Annotation\JoinColumns::class];
814
815 16
                foreach ($joinColumnsAnnot->value as $joinColumnAnnot) {
816 16
                    $assocMetadata->addJoinColumn(
817 16
                        $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot)
818
                    );
819
                }
820
821 16
                break;
822
        }
823
824 141
        return $assocMetadata;
825
    }
826
827
    /**
828
     * @param Annotation\Annotation[] $propertyAnnotations
829
     *
830
     * @throws Mapping\MappingException
831
     */
832 109
    private function convertReflectionPropertyToOneToManyAssociationMetadata(
833
        ReflectionProperty $reflectionProperty,
834
        array $propertyAnnotations,
835
        Mapping\ClassMetadata $metadata,
836
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
837
    ) : Mapping\OneToManyAssociationMetadata {
838 109
        $className      = $metadata->getClassName();
839 109
        $fieldName      = $reflectionProperty->getName();
840 109
        $oneToManyAnnot = $propertyAnnotations[Annotation\OneToMany::class];
841 109
        $assocMetadata  = new Mapping\OneToManyAssociationMetadata($fieldName);
842 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...
843
844 109
        $assocMetadata->setTargetEntity($targetEntity);
845 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...
846 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...
847 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...
848 109
        $assocMetadata->setOwningSide(false);
849 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...
850
851 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...
852 8
            $assocMetadata->setIndexedBy($oneToManyAnnot->indexBy);
853
        }
854
855
        // Check for OrderBy
856 109
        if (isset($propertyAnnotations[Annotation\OrderBy::class])) {
857 14
            $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class];
858
859 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...
860
        }
861
862
        // Check for Id
863 109
        if (isset($propertyAnnotations[Annotation\Id::class])) {
864
            throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName);
865
        }
866
867
        // Check for Cache
868 109
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
869 9
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
870
871
            $cacheBuilder
872 9
                ->withEntityClassMetadata($metadata)
873 9
                ->withFieldName($fieldName)
874 9
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
875
876 9
            $assocMetadata->setCache($cacheBuilder->build());
877
        }
878
879 109
        return $assocMetadata;
880
    }
881
882
    /**
883
     * @param Annotation\Annotation[] $propertyAnnotations
884
     *
885
     * @throws Mapping\MappingException
886
     */
887 89
    private function convertReflectionPropertyToManyToManyAssociationMetadata(
888
        ReflectionProperty $reflectionProperty,
889
        array $propertyAnnotations,
890
        Mapping\ClassMetadata $metadata,
891
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
892
    ) : Mapping\ManyToManyAssociationMetadata {
893 89
        $className       = $metadata->getClassName();
894 89
        $fieldName       = $reflectionProperty->getName();
895 89
        $manyToManyAnnot = $propertyAnnotations[Annotation\ManyToMany::class];
896 89
        $assocMetadata   = new Mapping\ManyToManyAssociationMetadata($fieldName);
897 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...
898
899 89
        $assocMetadata->setTargetEntity($targetEntity);
900 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...
901 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...
902 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...
903
904 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...
905 36
            $assocMetadata->setMappedBy($manyToManyAnnot->mappedBy);
906 36
            $assocMetadata->setOwningSide(false);
907
        }
908
909 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...
910 45
            $assocMetadata->setInversedBy($manyToManyAnnot->inversedBy);
911
        }
912
913 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...
914 3
            $assocMetadata->setIndexedBy($manyToManyAnnot->indexBy);
915
        }
916
917
        // Check for JoinTable
918 89
        if (isset($propertyAnnotations[Annotation\JoinTable::class])) {
919 71
            $joinTableAnnot    = $propertyAnnotations[Annotation\JoinTable::class];
920 71
            $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot);
921
922 71
            $assocMetadata->setJoinTable($joinTableMetadata);
923
        }
924
925
        // Check for OrderBy
926 89
        if (isset($propertyAnnotations[Annotation\OrderBy::class])) {
927 3
            $orderByAnnot = $propertyAnnotations[Annotation\OrderBy::class];
928
929 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...
930
        }
931
932
        // Check for Id
933 89
        if (isset($propertyAnnotations[Annotation\Id::class])) {
934
            throw Mapping\MappingException::illegalToManyIdentifierAssociation($className, $fieldName);
935
        }
936
937
        // Check for Cache
938 89
        if (isset($propertyAnnotations[Annotation\Cache::class])) {
939 2
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
940
941
            $cacheBuilder
942 2
                ->withEntityClassMetadata($metadata)
943 2
                ->withFieldName($fieldName)
944 2
                ->withCacheAnnotation($propertyAnnotations[Annotation\Cache::class]);
945
946 2
            $assocMetadata->setCache($cacheBuilder->build());
947
        }
948
949 89
        return $assocMetadata;
950
    }
951
952
    /**
953
     * Parse the given Column as FieldMetadata
954
     */
955 3
    private function convertColumnAnnotationToFieldMetadata(
956
        Annotation\Column $columnAnnot,
957
        string $fieldName,
958
        bool $isVersioned
959
    ) : Mapping\FieldMetadata {
960 3
        $fieldMetadata = new Mapping\FieldMetadata($fieldName);
961
962 3
        $fieldMetadata->setType(Type::getType($columnAnnot->type));
963 3
        $fieldMetadata->setVersioned($isVersioned);
964
965 3
        if (! empty($columnAnnot->name)) {
966 3
            $fieldMetadata->setColumnName($columnAnnot->name);
967
        }
968
969 3
        if (! empty($columnAnnot->columnDefinition)) {
970
            $fieldMetadata->setColumnDefinition($columnAnnot->columnDefinition);
971
        }
972
973 3
        if (! empty($columnAnnot->length)) {
974 3
            $fieldMetadata->setLength($columnAnnot->length);
975
        }
976
977 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...
978
            $fieldMetadata->setOptions($columnAnnot->options);
979
        }
980
981 3
        $fieldMetadata->setScale($columnAnnot->scale);
982 3
        $fieldMetadata->setPrecision($columnAnnot->precision);
983 3
        $fieldMetadata->setNullable($columnAnnot->nullable);
984 3
        $fieldMetadata->setUnique($columnAnnot->unique);
985
986 3
        return $fieldMetadata;
987
    }
988
989
    /**
990
     * Parse the given JoinTable as JoinTableMetadata
991
     */
992 71
    private function convertJoinTableAnnotationToJoinTableMetadata(
993
        Annotation\JoinTable $joinTableAnnot
994
    ) : Mapping\JoinTableMetadata {
995 71
        $joinTable = new Mapping\JoinTableMetadata();
996
997 71
        if (! empty($joinTableAnnot->name)) {
998 69
            $joinTable->setName($joinTableAnnot->name);
999
        }
1000
1001 71
        if (! empty($joinTableAnnot->schema)) {
1002
            $joinTable->setSchema($joinTableAnnot->schema);
1003
        }
1004
1005 71
        foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) {
1006 70
            $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1007
1008 70
            $joinTable->addJoinColumn($joinColumn);
1009
        }
1010
1011 71
        foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) {
1012 70
            $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1013
1014 70
            $joinTable->addInverseJoinColumn($joinColumn);
1015
        }
1016
1017 71
        return $joinTable;
1018
    }
1019
1020
    /**
1021
     * Parse the given JoinColumn as JoinColumnMetadata
1022
     */
1023 181
    private function convertJoinColumnAnnotationToJoinColumnMetadata(
1024
        Annotation\JoinColumn $joinColumnAnnot
1025
    ) : Mapping\JoinColumnMetadata {
1026 181
        $joinColumn = new Mapping\JoinColumnMetadata();
1027
1028
        // @todo Remove conditionals for name and referencedColumnName once naming strategy is brought into drivers
1029 181
        if (! empty($joinColumnAnnot->name)) {
1030 175
            $joinColumn->setColumnName($joinColumnAnnot->name);
1031
        }
1032
1033 181
        if (! empty($joinColumnAnnot->referencedColumnName)) {
1034 181
            $joinColumn->setReferencedColumnName($joinColumnAnnot->referencedColumnName);
1035
        }
1036
1037 181
        $joinColumn->setNullable($joinColumnAnnot->nullable);
1038 181
        $joinColumn->setUnique($joinColumnAnnot->unique);
1039
1040 181
        if (! empty($joinColumnAnnot->fieldName)) {
1041
            $joinColumn->setAliasedName($joinColumnAnnot->fieldName);
1042
        }
1043
1044 181
        if (! empty($joinColumnAnnot->columnDefinition)) {
1045 3
            $joinColumn->setColumnDefinition($joinColumnAnnot->columnDefinition);
1046
        }
1047
1048 181
        if ($joinColumnAnnot->onDelete) {
1049 16
            $joinColumn->setOnDelete(strtoupper($joinColumnAnnot->onDelete));
1050
        }
1051
1052 181
        return $joinColumn;
1053
    }
1054
1055
    /**
1056
     * @param Annotation\Annotation[] $classAnnotations
1057
     *
1058
     * @throws Mapping\MappingException
1059
     */
1060 80
    private function attachDiscriminatorColumn(
1061
        array $classAnnotations,
1062
        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

1062
        /** @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...
1063
        Mapping\ClassMetadata $metadata,
1064
        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

1064
        /** @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...
1065
    ) : void {
1066 80
        $discriminatorColumn = new Mapping\DiscriminatorColumnMetadata();
1067
1068 80
        $discriminatorColumn->setTableName($metadata->getTableName());
1069 80
        $discriminatorColumn->setColumnName('dtype');
1070 80
        $discriminatorColumn->setType(Type::getType('string'));
1071 80
        $discriminatorColumn->setLength(255);
1072
1073
        // Evaluate DiscriminatorColumn annotation
1074 80
        if (isset($classAnnotations[Annotation\DiscriminatorColumn::class])) {
1075
            /** @var Annotation\DiscriminatorColumn $discriminatorColumnAnnotation */
1076 62
            $discriminatorColumnAnnotation = $classAnnotations[Annotation\DiscriminatorColumn::class];
1077 62
            $typeName                      = ! empty($discriminatorColumnAnnotation->type)
1078 58
                ? $discriminatorColumnAnnotation->type
1079 62
                : 'string';
1080
1081 62
            $discriminatorColumn->setType(Type::getType($typeName));
1082 62
            $discriminatorColumn->setColumnName($discriminatorColumnAnnotation->name);
1083
1084 62
            if (! empty($discriminatorColumnAnnotation->columnDefinition)) {
1085 1
                $discriminatorColumn->setColumnDefinition($discriminatorColumnAnnotation->columnDefinition);
1086
            }
1087
1088 62
            if (! empty($discriminatorColumnAnnotation->length)) {
1089 5
                $discriminatorColumn->setLength($discriminatorColumnAnnotation->length);
1090
            }
1091
        }
1092
1093 80
        $metadata->setDiscriminatorColumn($discriminatorColumn);
1094
1095
        // Evaluate DiscriminatorMap annotation
1096 80
        if (isset($classAnnotations[Annotation\DiscriminatorMap::class])) {
1097 77
            $discriminatorMapAnnotation = $classAnnotations[Annotation\DiscriminatorMap::class];
1098 77
            $discriminatorMap           = $discriminatorMapAnnotation->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...
1099
1100 77
            $metadata->setDiscriminatorMap($discriminatorMap);
1101
        }
1102 80
    }
1103
1104
    /**
1105
     * @param Annotation\Annotation[] $classAnnotations
1106
     */
1107 373
    private function attachLifecycleCallbacks(
1108
        array $classAnnotations,
1109
        ReflectionClass $reflectionClass,
1110
        Mapping\ClassMetadata $metadata
1111
    ) : void {
1112
        // Evaluate @HasLifecycleCallbacks annotation
1113 373
        if (isset($classAnnotations[Annotation\HasLifecycleCallbacks::class])) {
1114
            $eventMap = [
1115 14
                Events::prePersist  => Annotation\PrePersist::class,
1116 14
                Events::postPersist => Annotation\PostPersist::class,
1117 14
                Events::preUpdate   => Annotation\PreUpdate::class,
1118 14
                Events::postUpdate  => Annotation\PostUpdate::class,
1119 14
                Events::preRemove   => Annotation\PreRemove::class,
1120 14
                Events::postRemove  => Annotation\PostRemove::class,
1121 14
                Events::postLoad    => Annotation\PostLoad::class,
1122 14
                Events::preFlush    => Annotation\PreFlush::class,
1123
            ];
1124
1125
            /** @var ReflectionMethod $reflectionMethod */
1126 14
            foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
1127 13
                $annotations = $this->getMethodAnnotations($reflectionMethod);
1128
1129 13
                foreach ($eventMap as $eventName => $annotationClassName) {
1130 13
                    if (isset($annotations[$annotationClassName])) {
1131 12
                        $metadata->addLifecycleCallback($eventName, $reflectionMethod->getName());
1132
                    }
1133
                }
1134
            }
1135
        }
1136 373
    }
1137
1138
    /**
1139
     * @param Annotation\Annotation[] $classAnnotations
1140
     *
1141
     * @throws ReflectionException
1142
     * @throws Mapping\MappingException
1143
     */
1144 373
    private function attachEntityListeners(
1145
        array $classAnnotations,
1146
        Mapping\ClassMetadata $metadata
1147
    ) : void {
1148
        // Evaluate @EntityListeners annotation
1149 373
        if (isset($classAnnotations[Annotation\EntityListeners::class])) {
1150
            /** @var Annotation\EntityListeners $entityListenersAnnot */
1151 8
            $entityListenersAnnot = $classAnnotations[Annotation\EntityListeners::class];
1152
            $eventMap             = [
1153 8
                Events::prePersist  => Annotation\PrePersist::class,
1154 8
                Events::postPersist => Annotation\PostPersist::class,
1155 8
                Events::preUpdate   => Annotation\PreUpdate::class,
1156 8
                Events::postUpdate  => Annotation\PostUpdate::class,
1157 8
                Events::preRemove   => Annotation\PreRemove::class,
1158 8
                Events::postRemove  => Annotation\PostRemove::class,
1159 8
                Events::postLoad    => Annotation\PostLoad::class,
1160 8
                Events::preFlush    => Annotation\PreFlush::class,
1161
            ];
1162
1163 8
            foreach ($entityListenersAnnot->value as $listenerClassName) {
1164 8
                if (! class_exists($listenerClassName)) {
1165
                    throw Mapping\MappingException::entityListenerClassNotFound(
1166
                        $listenerClassName,
1167
                        $metadata->getClassName()
1168
                    );
1169
                }
1170
1171 8
                $listenerClass = new ReflectionClass($listenerClassName);
1172
1173
                /** @var ReflectionMethod $reflectionMethod */
1174 8
                foreach ($listenerClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
1175 8
                    $annotations = $this->getMethodAnnotations($reflectionMethod);
1176
1177 8
                    foreach ($eventMap as $eventName => $annotationClassName) {
1178 8
                        if (isset($annotations[$annotationClassName])) {
1179 6
                            $metadata->addEntityListener($eventName, $listenerClassName, $reflectionMethod->getName());
1180
                        }
1181
                    }
1182
                }
1183
            }
1184
        }
1185 373
    }
1186
1187
    /**
1188
     * @param Annotation\Annotation[] $classAnnotations
1189
     *
1190
     * @throws Mapping\MappingException
1191
     */
1192 370
    private function attachPropertyOverrides(
1193
        array $classAnnotations,
1194
        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

1194
        /** @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...
1195
        Mapping\ClassMetadata $metadata,
1196
        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

1196
        /** @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...
1197
    ) : void {
1198
        // Evaluate AssociationOverrides annotation
1199 370
        if (isset($classAnnotations[Annotation\AssociationOverrides::class])) {
1200 5
            $associationOverridesAnnot = $classAnnotations[Annotation\AssociationOverrides::class];
1201
1202 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...
1203 5
                $fieldName = $associationOverride->name;
1204 5
                $property  = $metadata->getProperty($fieldName);
1205
1206 5
                if (! $property) {
1207
                    throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName);
1208
                }
1209
1210 5
                $existingClass = get_class($property);
1211 5
                $override      = new $existingClass($fieldName);
1212
1213
                // Check for JoinColumn/JoinColumns annotations
1214 5
                if ($associationOverride->joinColumns) {
1215 3
                    $joinColumns = [];
1216
1217 3
                    foreach ($associationOverride->joinColumns as $joinColumnAnnot) {
1218 3
                        $joinColumns[] = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot);
1219
                    }
1220
1221 3
                    $override->setJoinColumns($joinColumns);
1222
                }
1223
1224
                // Check for JoinTable annotations
1225 5
                if ($associationOverride->joinTable) {
1226 2
                    $joinTableAnnot    = $associationOverride->joinTable;
1227 2
                    $joinTableMetadata = $this->convertJoinTableAnnotationToJoinTableMetadata($joinTableAnnot);
1228
1229 2
                    $override->setJoinTable($joinTableMetadata);
1230
                }
1231
1232
                // Check for inversedBy
1233 5
                if ($associationOverride->inversedBy) {
1234 1
                    $override->setInversedBy($associationOverride->inversedBy);
1235
                }
1236
1237
                // Check for fetch
1238 5
                if ($associationOverride->fetch) {
1239 1
                    $override->setFetchMode(
1240 1
                        constant(Mapping\FetchMode::class . '::' . $associationOverride->fetch)
1241
                    );
1242
                }
1243
1244 5
                $metadata->setPropertyOverride($override);
1245
            }
1246
        }
1247
1248
        // Evaluate AttributeOverrides annotation
1249 370
        if (isset($classAnnotations[Annotation\AttributeOverrides::class])) {
1250 3
            $attributeOverridesAnnot = $classAnnotations[Annotation\AttributeOverrides::class];
1251
1252 3
            foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) {
1253 3
                $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata(
1254 3
                    $attributeOverrideAnnot->column,
1255 3
                    $attributeOverrideAnnot->name,
1256 3
                    false
1257
                );
1258
1259 3
                $metadata->setPropertyOverride($fieldMetadata);
1260
            }
1261
        }
1262 370
    }
1263
1264
    /**
1265
     * Attempts to resolve the cascade modes.
1266
     *
1267
     * @param string   $className        The class name.
1268
     * @param string   $fieldName        The field name.
1269
     * @param string[] $originalCascades The original unprocessed field cascades.
1270
     *
1271
     * @return string[] The processed field cascades.
1272
     *
1273
     * @throws Mapping\MappingException If a cascade option is not valid.
1274
     */
1275 251
    private function getCascade(string $className, string $fieldName, array $originalCascades) : array
1276
    {
1277 251
        $cascadeTypes = ['remove', 'persist', 'refresh'];
1278 251
        $cascades     = array_map('strtolower', $originalCascades);
1279
1280 251
        if (in_array('all', $cascades, true)) {
1281 23
            $cascades = $cascadeTypes;
1282
        }
1283
1284 251
        if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) {
1285
            $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes));
1286
1287
            throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName);
1288
        }
1289
1290 251
        return $cascades;
1291
    }
1292
1293
    /**
1294
     * Attempts to resolve the fetch mode.
1295
     *
1296
     * @param string $className The class name.
1297
     * @param string $fetchMode The fetch mode.
1298
     *
1299
     * @return string The fetch mode as defined in ClassMetadata.
1300
     *
1301
     * @throws Mapping\MappingException If the fetch mode is not valid.
1302
     */
1303 251
    private function getFetchMode($className, $fetchMode) : string
1304
    {
1305 251
        $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode);
1306
1307 251
        if (! defined($fetchModeConstant)) {
1308
            throw Mapping\MappingException::invalidFetchMode($className, $fetchMode);
1309
        }
1310
1311 251
        return constant($fetchModeConstant);
1312
    }
1313
1314
    /**
1315
     * @return Annotation\Annotation[]
1316
     */
1317 379
    private function getClassAnnotations(ReflectionClass $reflectionClass) : array
1318
    {
1319 379
        $classAnnotations = $this->reader->getClassAnnotations($reflectionClass);
1320
1321 379
        foreach ($classAnnotations as $key => $annot) {
1322 373
            if (! is_numeric($key)) {
1323
                continue;
1324
            }
1325
1326 373
            $classAnnotations[get_class($annot)] = $annot;
1327
        }
1328
1329 379
        return $classAnnotations;
1330
    }
1331
1332
    /**
1333
     * @return Annotation\Annotation[]
1334
     */
1335 373
    private function getPropertyAnnotations(ReflectionProperty $reflectionProperty) : array
1336
    {
1337 373
        $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty);
1338
1339 372
        foreach ($propertyAnnotations as $key => $annot) {
1340 372
            if (! is_numeric($key)) {
1341
                continue;
1342
            }
1343
1344 372
            $propertyAnnotations[get_class($annot)] = $annot;
1345
        }
1346
1347 372
        return $propertyAnnotations;
1348
    }
1349
1350
    /**
1351
     * @return Annotation\Annotation[]
1352
     */
1353 21
    private function getMethodAnnotations(ReflectionMethod $reflectionMethod) : array
1354
    {
1355 21
        $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod);
1356
1357 21
        foreach ($methodAnnotations as $key => $annot) {
1358 18
            if (! is_numeric($key)) {
1359
                continue;
1360
            }
1361
1362 18
            $methodAnnotations[get_class($annot)] = $annot;
1363
        }
1364
1365 21
        return $methodAnnotations;
1366
    }
1367
}
1368