Failed Conditions
Push — master ( c35142...f185a6 )
by Guilherme
08:59
created

AnnotationDriver::loadMetadataForClass()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 56
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 32
nc 8
nop 3
dl 0
loc 56
ccs 32
cts 32
cp 1
crap 7
rs 8.4746
c 0
b 0
f 0

How to fix   Long Method   

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
                ->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
                $this->attachDiscriminatorColumn($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext);
455
            }
456
        }
457
458 372
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
459 372
        $this->attachEntityListeners($classAnnotations, $metadata);
460
461 372
        return $metadata;
462
    }
463
464
    /**
465
     * @param Annotation\Annotation[] $classAnnotations
466
     *
467
     * @throws Mapping\MappingException
468
     * @throws ReflectionException
469
     */
470 23
    private function convertClassAnnotationsToMappedSuperClassMetadata(
471
        array $classAnnotations,
472
        ReflectionClass $reflectionClass,
473
        Mapping\ClassMetadata $metadata
474
    ) : Mapping\ClassMetadata {
475
        /** @var Annotation\MappedSuperclass $mappedSuperclassAnnot */
476 23
        $mappedSuperclassAnnot = $classAnnotations[Annotation\MappedSuperclass::class];
477
478 23
        if ($mappedSuperclassAnnot->repositoryClass !== null) {
479 2
            $metadata->setCustomRepositoryClassName($mappedSuperclassAnnot->repositoryClass);
480
        }
481
482 23
        $metadata->isMappedSuperclass = true;
483 23
        $metadata->isEmbeddedClass    = false;
484
485 23
        $this->attachLifecycleCallbacks($classAnnotations, $reflectionClass, $metadata);
486 23
        $this->attachEntityListeners($classAnnotations, $metadata);
487
488 23
        return $metadata;
489
    }
490
491
    /**
492
     * @param Annotation\Annotation[] $classAnnotations
493
     */
494
    private function convertClassAnnotationsToEmbeddableClassMetadata(
495
        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

495
        /** @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...
496
        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

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

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

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

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

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