Failed Conditions
Push — master ( 6971e7...b11528 )
by Guilherme
08:44
created

adata()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

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

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

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

class Alien {}

class Dalek extends Alien {}

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

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
105
106 2297
        if ($paths) {
107 2211
            $this->addPaths((array) $paths);
108
        }
109 2297
    }
110
111
    /**
112
     * Appends lookup paths to metadata driver.
113
     *
114
     * @param string[] $paths
115
     */
116 2215
    public function addPaths(array $paths)
117
    {
118 2215
        $this->paths = array_unique(array_merge($this->paths, $paths));
119 2215
    }
120
121
    /**
122
     * Retrieves the defined metadata lookup paths.
123
     *
124
     * @return string[]
125
     */
126
    public function getPaths()
127
    {
128
        return $this->paths;
129
    }
130
131
    /**
132
     * Append exclude lookup paths to metadata driver.
133
     *
134
     * @param string[] $paths
135
     */
136
    public function addExcludePaths(array $paths)
137
    {
138
        $this->excludePaths = array_unique(array_merge($this->excludePaths, $paths));
139
    }
140
141
    /**
142
     * Retrieve the defined metadata lookup exclude paths.
143
     *
144
     * @return string[]
145
     */
146
    public function getExcludePaths()
147
    {
148
        return $this->excludePaths;
149
    }
150
151
    /**
152
     * Retrieve the current annotation reader
153
     *
154
     * @return Reader
155
     */
156 1
    public function getReader()
157
    {
158 1
        return $this->reader;
159
    }
160
161
    /**
162
     * Gets the file extension used to look for mapping files under.
163
     *
164
     * @return string
165
     */
166
    public function getFileExtension()
167
    {
168
        return $this->fileExtension;
169
    }
170
171
    /**
172
     * Sets the file extension used to look for mapping files under.
173
     *
174
     * @param string $fileExtension The file extension to set.
175
     */
176
    public function setFileExtension($fileExtension)
177
    {
178
        $this->fileExtension = $fileExtension;
179
    }
180
181
    /**
182
     * Returns whether the class with the specified name is transient. Only non-transient
183
     * classes, that is entities and mapped superclasses, should have their metadata loaded.
184
     *
185
     * A class is non-transient if it is annotated with an annotation
186
     * from the {@see AnnotationDriver::entityAnnotationClasses}.
187
     *
188
     * @param string $className
189
     *
190
     * @throws ReflectionException
191
     */
192 193
    public function isTransient($className) : bool
193
    {
194 193
        $classAnnotations = $this->reader->getClassAnnotations(new ReflectionClass($className));
195
196 193
        foreach ($classAnnotations as $annotation) {
197 188
            if (isset($this->entityAnnotationClasses[get_class($annotation)])) {
198 188
                return false;
199
            }
200
        }
201
202 12
        return true;
203
    }
204
205
    /**
206
     * {@inheritdoc}
207
     *
208
     * @throws ReflectionException
209
     */
210 60
    public function getAllClassNames() : array
211
    {
212 60
        if ($this->classNames !== null) {
213 45
            return $this->classNames;
214
        }
215
216 60
        if (! $this->paths) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->paths of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
217
            throw Mapping\MappingException::pathRequired();
218
        }
219
220 60
        $classes       = [];
221 60
        $includedFiles = [];
222
223 60
        foreach ($this->paths as $path) {
224 60
            if (! is_dir($path)) {
225
                throw Mapping\MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
226
            }
227
228 60
            $iterator = new RegexIterator(
229 60
                new RecursiveIteratorIterator(
230 60
                    new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
231 60
                    RecursiveIteratorIterator::LEAVES_ONLY
232
                ),
233 60
                '/^.+' . preg_quote($this->fileExtension) . '$/i',
234 60
                RecursiveRegexIterator::GET_MATCH
235
            );
236
237 60
            foreach ($iterator as $file) {
238 60
                $sourceFile = $file[0];
239
240 60
                if (! preg_match('(^phar:)i', $sourceFile)) {
241 60
                    $sourceFile = realpath($sourceFile);
242
                }
243
244 60
                foreach ($this->excludePaths as $excludePath) {
245
                    $exclude = str_replace('\\', '/', realpath($excludePath));
246
                    $current = str_replace('\\', '/', $sourceFile);
247
248
                    if (strpos($current, $exclude) !== false) {
249
                        continue 2;
250
                    }
251
                }
252
253 60
                require_once $sourceFile;
254
255 60
                $includedFiles[] = $sourceFile;
256
            }
257
        }
258
259 60
        $declared = get_declared_classes();
260
261 60
        foreach ($declared as $className) {
262 60
            $reflectionClass = new ReflectionClass($className);
263 60
            $sourceFile      = $reflectionClass->getFileName();
264
265 60
            if (in_array($sourceFile, $includedFiles, true) && ! $this->isTransient($className)) {
266 60
                $classes[] = $className;
267
            }
268
        }
269
270 60
        $this->classNames = $classes;
271
272 60
        return $classes;
273
    }
274
275
    /**
276
     * {@inheritDoc}
277
     *
278
     * @throws CacheException
279
     * @throws Mapping\MappingException
280
     * @throws ReflectionException
281
     * @throws RuntimeException
282
     * @throws UnexpectedValueException
283
     */
284 379
    public function loadMetadataForClass(
285
        string $className,
286
        ?Mapping\ComponentMetadata $parent,
287
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
288
    ) : Mapping\ComponentMetadata {
289 379
        $reflectionClass  = new ReflectionClass($className);
290 379
        $metadata         = new Mapping\ClassMetadata($className, $parent, $metadataBuildingContext);
291 379
        $classAnnotations = $this->getClassAnnotations($reflectionClass);
292 379
        $classMetadata    = $this->convertClassAnnotationsToClassMetadata(
293 379
            $classAnnotations,
294 379
            $reflectionClass,
295 379
            $metadata,
296 379
            $metadataBuildingContext
297
        );
298
299
        // Evaluate @Cache annotation
300 373
        if (isset($classAnnotations[Annotation\Cache::class])) {
301 18
            $cacheBuilder = new Builder\CacheMetadataBuilder($metadataBuildingContext);
302
303
            $cacheBuilder
304 18
                ->withComponentMetadata($metadata)
305 18
                ->withCacheAnnotation($classAnnotations[Annotation\Cache::class]);
306
307 18
            $metadata->setCache($cacheBuilder->build());
308
        }
309
310
        // Evaluate annotations on properties/fields
311
        /** @var ReflectionProperty $reflProperty */
312 373
        foreach ($reflectionClass->getProperties() as $reflectionProperty) {
313 373
            if ($reflectionProperty->getDeclaringClass()->getName() !== $reflectionClass->getName()) {
314 74
                continue;
315
            }
316
317 373
            $propertyAnnotations = $this->getPropertyAnnotations($reflectionProperty);
318 372
            $property            = $this->convertPropertyAnnotationsToProperty(
319 372
                $propertyAnnotations,
320 372
                $reflectionProperty,
321 372
                $classMetadata,
322 372
                $metadataBuildingContext
323
            );
324
325 372
            if ($classMetadata->isMappedSuperclass &&
326 372
                $property instanceof Mapping\ToManyAssociationMetadata &&
327 372
                ! $property->isOwningSide()) {
328 1
                throw Mapping\MappingException::illegalToManyAssociationOnMappedSuperclass(
329 1
                    $classMetadata->getClassName(),
330 1
                    $property->getName()
331
                );
332
            }
333
334 371
            $metadata->addProperty($property);
335
        }
336
337 370
        $this->attachPropertyOverrides($classAnnotations, $reflectionClass, $metadata, $metadataBuildingContext);
338
339 370
        return $classMetadata;
340
    }
341
342
    /**
343
     * @param Annotation\Annotation[] $classAnnotations
344
     *
345
     * @throws Mapping\MappingException
346
     * @throws UnexpectedValueException
347
     * @throws ReflectionException
348
     */
349 379
    private function convertClassAnnotationsToClassMetadata(
350
        array $classAnnotations,
351
        ReflectionClass $reflectionClass,
352
        Mapping\ClassMetadata $metadata,
353
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
354
    ) : Mapping\ClassMetadata {
355
        switch (true) {
356 379
            case isset($classAnnotations[Annotation\Entity::class]):
357 372
                return $this->convertClassAnnotationsToEntityClassMetadata(
358 372
                    $classAnnotations,
359 372
                    $reflectionClass,
360 372
                    $metadata,
361 372
                    $metadataBuildingContext
362
                );
363
364
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

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

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

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

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

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

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

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

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

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

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

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

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

1127
        /** @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...
1128
        Mapping\ClassMetadata $metadata,
1129
        Mapping\ClassMetadataBuildingContext $metadataBuildingContext
1130
    ) : void {
1131
        // Evaluate AssociationOverrides annotation
1132 370
        if (isset($classAnnotations[Annotation\AssociationOverrides::class])) {
1133 5
            $associationOverridesAnnot = $classAnnotations[Annotation\AssociationOverrides::class];
1134
1135 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...
1136 5
                $fieldName = $associationOverride->name;
1137 5
                $property  = $metadata->getProperty($fieldName);
1138
1139 5
                if (! $property) {
1140
                    throw Mapping\MappingException::invalidOverrideFieldName($metadata->getClassName(), $fieldName);
1141
                }
1142
1143 5
                $existingClass = get_class($property);
1144 5
                $override      = new $existingClass($fieldName);
1145
1146 5
                $override->setTargetEntity($property->getTargetEntity());
0 ignored issues
show
Bug introduced by
The method getTargetEntity() does not exist on Doctrine\ORM\Mapping\Property. It seems like you code against a sub-type of Doctrine\ORM\Mapping\Property such as Doctrine\ORM\Mapping\AssociationMetadata. ( Ignorable by Annotation )

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

1146
                $override->setTargetEntity($property->/** @scrutinizer ignore-call */ getTargetEntity());
Loading history...
1147
1148
                // Check for JoinColumn/JoinColumns annotations
1149 5
                if ($associationOverride->joinColumns) {
1150 3
                    $joinColumnBuilder = new Builder\JoinColumnMetadataBuilder($metadataBuildingContext);
1151
1152
                    $joinColumnBuilder
1153 3
                        ->withComponentMetadata($metadata)
1154 3
                        ->withFieldName($fieldName);
1155
1156 3
                    $joinColumns = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $joinColumns is dead and can be removed.
Loading history...
1157
1158 3
                    foreach ($associationOverride->joinColumns as $joinColumnAnnotation) {
1159 3
                        $joinColumnBuilder->withJoinColumnAnnotation($joinColumnAnnotation);
1160
1161 3
                        $override->addJoinColumn($joinColumnBuilder->build());
1162
                    }
1163
                }
1164
1165
                // Check for JoinTable annotations
1166 5
                if ($associationOverride->joinTable) {
1167 2
                    $joinTableBuilder = new Builder\JoinTableMetadataBuilder($metadataBuildingContext);
1168
1169
                    $joinTableBuilder
1170 2
                        ->withComponentMetadata($metadata)
1171 2
                        ->withFieldName($fieldName)
1172 2
                        ->withTargetEntity($property->getTargetEntity())
1173 2
                        ->withJoinTableAnnotation($associationOverride->joinTable);
1174
1175 2
                    $override->setJoinTable($joinTableBuilder->build());
1176
                }
1177
1178
                // Check for inversedBy
1179 5
                if ($associationOverride->inversedBy) {
1180 1
                    $override->setInversedBy($associationOverride->inversedBy);
1181
                }
1182
1183
                // Check for fetch
1184 5
                if ($associationOverride->fetch) {
1185 1
                    $override->setFetchMode(
1186 1
                        constant(Mapping\FetchMode::class . '::' . $associationOverride->fetch)
1187
                    );
1188
                }
1189
1190 5
                $metadata->setPropertyOverride($override);
1191
            }
1192
        }
1193
1194
        // Evaluate AttributeOverrides annotation
1195 370
        if (isset($classAnnotations[Annotation\AttributeOverrides::class])) {
1196 3
            $attributeOverridesAnnot = $classAnnotations[Annotation\AttributeOverrides::class];
1197
1198 3
            foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) {
1199 3
                $fieldMetadata = $this->convertColumnAnnotationToFieldMetadata(
1200 3
                    $attributeOverrideAnnot->column,
1201 3
                    $attributeOverrideAnnot->name,
1202 3
                    false
1203
                );
1204
1205 3
                $metadata->setPropertyOverride($fieldMetadata);
1206
            }
1207
        }
1208 370
    }
1209
1210
    /**
1211
     * Attempts to resolve the cascade modes.
1212
     *
1213
     * @param string   $className        The class name.
1214
     * @param string   $fieldName        The field name.
1215
     * @param string[] $originalCascades The original unprocessed field cascades.
1216
     *
1217
     * @return string[] The processed field cascades.
1218
     *
1219
     * @throws Mapping\MappingException If a cascade option is not valid.
1220
     */
1221 251
    private function getCascade(string $className, string $fieldName, array $originalCascades) : array
1222
    {
1223 251
        $cascadeTypes = ['remove', 'persist', 'refresh'];
1224 251
        $cascades     = array_map('strtolower', $originalCascades);
1225
1226 251
        if (in_array('all', $cascades, true)) {
1227 23
            $cascades = $cascadeTypes;
1228
        }
1229
1230 251
        if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) {
1231
            $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes));
1232
1233
            throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName);
1234
        }
1235
1236 251
        return $cascades;
1237
    }
1238
1239
    /**
1240
     * Attempts to resolve the fetch mode.
1241
     *
1242
     * @param string $className The class name.
1243
     * @param string $fetchMode The fetch mode.
1244
     *
1245
     * @return string The fetch mode as defined in ClassMetadata.
1246
     *
1247
     * @throws Mapping\MappingException If the fetch mode is not valid.
1248
     */
1249 251
    private function getFetchMode($className, $fetchMode) : string
1250
    {
1251 251
        $fetchModeConstant = sprintf('%s::%s', Mapping\FetchMode::class, $fetchMode);
1252
1253 251
        if (! defined($fetchModeConstant)) {
1254
            throw Mapping\MappingException::invalidFetchMode($className, $fetchMode);
1255
        }
1256
1257 251
        return constant($fetchModeConstant);
1258
    }
1259
1260
    /**
1261
     * @return Annotation\Annotation[]
1262
     */
1263 379
    private function getClassAnnotations(ReflectionClass $reflectionClass) : array
1264
    {
1265 379
        $classAnnotations = $this->reader->getClassAnnotations($reflectionClass);
1266
1267 379
        foreach ($classAnnotations as $key => $annot) {
1268 373
            if (! is_numeric($key)) {
1269
                continue;
1270
            }
1271
1272 373
            $classAnnotations[get_class($annot)] = $annot;
1273
        }
1274
1275 379
        return $classAnnotations;
1276
    }
1277
1278
    /**
1279
     * @return Annotation\Annotation[]
1280
     */
1281 373
    private function getPropertyAnnotations(ReflectionProperty $reflectionProperty) : array
1282
    {
1283 373
        $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty);
1284
1285 372
        foreach ($propertyAnnotations as $key => $annot) {
1286 372
            if (! is_numeric($key)) {
1287
                continue;
1288
            }
1289
1290 372
            $propertyAnnotations[get_class($annot)] = $annot;
1291
        }
1292
1293 372
        return $propertyAnnotations;
1294
    }
1295
1296
    /**
1297
     * @return Annotation\Annotation[]
1298
     */
1299 21
    private function getMethodAnnotations(ReflectionMethod $reflectionMethod) : array
1300
    {
1301 21
        $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod);
1302
1303 21
        foreach ($methodAnnotations as $key => $annot) {
1304 18
            if (! is_numeric($key)) {
1305
                continue;
1306
            }
1307
1308 18
            $methodAnnotations[get_class($annot)] = $annot;
1309
        }
1310
1311 21
        return $methodAnnotations;
1312
    }
1313
}
1314