Failed Conditions
Pull Request — master (#7799)
by Guilherme
09:17
created

ClassMetadata::getTableName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Mapping;
6
7
use ArrayIterator;
8
use Doctrine\ORM\Cache\Exception\CacheException;
9
use Doctrine\ORM\Cache\Exception\NonCacheableEntityAssociation;
0 ignored issues
show
introduced by
Type Doctrine\ORM\Cache\Exception\NonCacheableEntityAssociation is not used in this file.
Loading history...
10
use Doctrine\ORM\EntityManagerInterface;
11
use Doctrine\ORM\Reflection\ReflectionService;
12
use Doctrine\ORM\Sequencing\Planning\ValueGenerationPlan;
13
use Doctrine\ORM\Utility\PersisterHelper;
14
use ReflectionException;
15
use RuntimeException;
16
use function array_diff;
0 ignored issues
show
introduced by
Type array_diff is not used in this file.
Loading history...
17
use function array_filter;
18
use function array_intersect;
0 ignored issues
show
introduced by
Type array_intersect is not used in this file.
Loading history...
19
use function array_map;
0 ignored issues
show
introduced by
Type array_map is not used in this file.
Loading history...
20
use function array_merge;
21
use function class_exists;
22
use function count;
0 ignored issues
show
introduced by
Type count is not used in this file.
Loading history...
23
use function get_class;
24
use function in_array;
25
use function interface_exists;
26
use function is_subclass_of;
27
use function method_exists;
28
use function spl_object_id;
29
use function sprintf;
0 ignored issues
show
introduced by
Type sprintf is not used in this file.
Loading history...
30
31
/**
32
 * A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
33
 * of an entity and its associations.
34
 */
35
class ClassMetadata extends ComponentMetadata implements TableOwner
36
{
37
    /**
38
     * The name of the custom repository class used for the entity class.
39
     * (Optional).
40
     *
41
     * @var string
42
     */
43
    protected $customRepositoryClassName;
44
45
    /**
46
     * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
47
     *
48
     * @var bool
49
     */
50
    public $isMappedSuperclass = false;
51
52
    /**
53
     * READ-ONLY: Whether this class describes the mapping of an embeddable class.
54
     *
55
     * @var bool
56
     */
57
    public $isEmbeddedClass = false;
58
59
    /**
60
     * Whether this class describes the mapping of a read-only class.
61
     * That means it is never considered for change-tracking in the UnitOfWork.
62
     * It is a very helpful performance optimization for entities that are immutable,
63
     * either in your domain or through the relation database (coming from a view,
64
     * or a history table for example).
65
     *
66
     * @var bool
67
     */
68
    private $readOnly = false;
69
70
    /**
71
     * The names of all subclasses (descendants).
72
     *
73
     * @var string[]
74
     */
75
    protected $subClasses = [];
76
77
    /**
78
     * READ-ONLY: The names of all embedded classes based on properties.
79
     *
80
     * @var string[]
81
     */
82
    //public $embeddedClasses = [];
83
84
    /**
85
     * READ-ONLY: The registered lifecycle callbacks for entities of this class.
86
     *
87
     * @var string[][]
88
     */
89
    public $lifecycleCallbacks = [];
90
91
    /**
92
     * READ-ONLY: The registered entity listeners.
93
     *
94
     * @var mixed[][]
95
     */
96
    public $entityListeners = [];
97
98
    /**
99
     * READ-ONLY: The field names of all fields that are part of the identifier/primary key
100
     * of the mapped entity class.
101
     *
102
     * @var string[]
103
     */
104
    public $identifier = [];
105
106
    /**
107
     * READ-ONLY: The inheritance mapping type used by the class.
108
     *
109
     * @var string
110
     */
111
    public $inheritanceType = InheritanceType::NONE;
112
113
    /**
114
     * READ-ONLY: The policy used for change-tracking on entities of this class.
115
     *
116
     * @var string
117
     */
118
    public $changeTrackingPolicy = ChangeTrackingPolicy::DEFERRED_IMPLICIT;
119
120
    /**
121
     * READ-ONLY: The discriminator value of this class.
122
     *
123
     * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
124
     * where a discriminator column is used.</b>
125
     *
126
     * @see discriminatorColumn
127
     *
128
     * @var mixed
129
     */
130
    public $discriminatorValue;
131
132
    /**
133
     * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
134
     *
135
     * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
136
     * where a discriminator column is used.</b>
137
     *
138
     * @see discriminatorColumn
139
     *
140
     * @var string[]
141
     */
142
    public $discriminatorMap = [];
143
144
    /**
145
     * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
146
     * inheritance mappings.
147
     *
148
     * @var DiscriminatorColumnMetadata
149
     */
150
    public $discriminatorColumn;
151
152
    /**
153
     * READ-ONLY: The primary table metadata.
154
     *
155
     * @var TableMetadata
156
     */
157
    public $table;
158
159
    /**
160
     * READ-ONLY: An array of field names. Used to look up field names from column names.
161
     * Keys are column names and values are field names.
162
     *
163
     * @var string[]
164
     */
165
    public $fieldNames = [];
166
167
    /**
168
     * READ-ONLY: The field which is used for versioning in optimistic locking (if any).
169
     *
170
     * @var FieldMetadata|null
171
     */
172
    public $versionProperty;
173
174
    /**
175
     * Value generation plan is responsible for generating values for auto-generated fields.
176
     *
177
     * @var ValueGenerationPlan
178
     */
179
    protected $valueGenerationPlan;
180
181
    /**
182
     * Initializes a new ClassMetadata instance that will hold the object-relational mapping
183
     * metadata of the class with the given name.
184
     *
185
     * @param string             $entityName The name of the entity class.
186
     * @param ClassMetadata|null $parent     Optional parent class metadata.
187
     */
188 452
    public function __construct(
189
        string $entityName,
190
        ?ComponentMetadata $parent,
191
        ClassMetadataBuildingContext $metadataBuildingContext
192
    ) {
193 452
        parent::__construct($entityName, $metadataBuildingContext);
194
195 452
        if ($parent) {
196 98
            $this->setParent($parent);
197
        }
198 452
    }
199
200
    /**
201
     * {@inheritdoc}
202
     *
203
     * @throws MappingException
204
     */
205 98
    public function setParent(ComponentMetadata $parent) : void
206
    {
207 98
        parent::setParent($parent);
208
209 98
        foreach ($parent->getPropertiesIterator() as $fieldName => $property) {
210 95
            $this->addInheritedProperty($property);
211
        }
212
213
        // @todo guilhermeblanco Assume to be a ClassMetadata temporarily until ClassMetadata split is complete.
214
        /** @var ClassMetadata $parent */
215 98
        $this->setInheritanceType($parent->inheritanceType);
0 ignored issues
show
Bug introduced by
$parent->inheritanceType of type string is incompatible with the type integer expected by parameter $type of Doctrine\ORM\Mapping\Cla...a::setInheritanceType(). ( Ignorable by Annotation )

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

215
        $this->setInheritanceType(/** @scrutinizer ignore-type */ $parent->inheritanceType);
Loading history...
216 98
        $this->setIdentifier($parent->identifier);
217 98
        $this->setChangeTrackingPolicy($parent->changeTrackingPolicy);
218
219 98
        if ($parent->discriminatorColumn) {
220 70
            $this->setDiscriminatorColumn($parent->discriminatorColumn);
221 70
            $this->setDiscriminatorMap($parent->discriminatorMap);
222
        }
223
224 98
        if ($parent->isMappedSuperclass) {
225 27
            $this->setCustomRepositoryClassName($parent->getCustomRepositoryClassName());
226
        }
227
228 98
        if ($parent->cache) {
229 3
            $this->setCache(clone $parent->cache);
230
        }
231
232 98
        if (! empty($parent->lifecycleCallbacks)) {
233 5
            $this->lifecycleCallbacks = $parent->lifecycleCallbacks;
234
        }
235
236 98
        if (! empty($parent->entityListeners)) {
237 7
            $this->entityListeners = $parent->entityListeners;
238
        }
239 98
    }
240
241
    public function setClassName(string $className)
242
    {
243
        $this->className = $className;
244
    }
245
246
    public function getColumnsIterator() : ArrayIterator
247
    {
248
        $iterator = parent::getColumnsIterator();
249
250
        if ($this->discriminatorColumn) {
251
            $iterator->offsetSet($this->discriminatorColumn->getColumnName(), $this->discriminatorColumn);
0 ignored issues
show
Bug introduced by
$this->discriminatorColumn of type Doctrine\ORM\Mapping\DiscriminatorColumnMetadata is incompatible with the type string expected by parameter $newval of ArrayIterator::offsetSet(). ( Ignorable by Annotation )

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

251
            $iterator->offsetSet($this->discriminatorColumn->getColumnName(), /** @scrutinizer ignore-type */ $this->discriminatorColumn);
Loading history...
252
        }
253
254
        return $iterator;
255
    }
256
257 11
    public function getAncestorsIterator() : ArrayIterator
258
    {
259 11
        $ancestors = new ArrayIterator();
260 11
        $parent    = $this;
261
262 11
        while (($parent = $parent->parent) !== null) {
263 8
            if ($parent instanceof ClassMetadata && $parent->isMappedSuperclass) {
264 1
                continue;
265
            }
266
267 7
            $ancestors->append($parent);
268
        }
269
270 11
        return $ancestors;
271
    }
272
273 1260
    public function getRootClassName() : string
274
    {
275 1260
        return $this->parent instanceof ClassMetadata && ! $this->parent->isMappedSuperclass
276 402
            ? $this->parent->getRootClassName()
277 1260
            : $this->className;
278
    }
279
280
    /**
281
     * Handles metadata cloning nicely.
282
     */
283 13
    public function __clone()
284
    {
285 13
        if ($this->cache) {
286 12
            $this->cache = clone $this->cache;
287
        }
288
289 13
        foreach ($this->properties as $name => $property) {
290 13
            $this->properties[$name] = clone $property;
291
        }
292 13
    }
293
294
    /**
295
     * Creates a string representation of this instance.
296
     *
297
     * @return string The string representation of this instance.
298
     *
299
     * @todo Construct meaningful string representation.
300
     */
301
    public function __toString()
302
    {
303
        return self::class . '@' . spl_object_id($this);
304
    }
305
306
    /**
307
     * Determines which fields get serialized.
308
     *
309
     * It is only serialized what is necessary for best unserialization performance.
310
     * That means any metadata properties that are not set or empty or simply have
311
     * their default value are NOT serialized.
312
     *
313
     * Parts that are also NOT serialized because they can not be properly unserialized:
314
     * - reflectionClass
315
     *
316
     * @return string[] The names of all the fields that should be serialized.
317
     */
318 4
    public function __sleep()
319
    {
320 4
        $serialized = [];
321
322
        // This metadata is always serialized/cached.
323 4
        $serialized = array_merge($serialized, [
324 4
            'properties',
325
            'fieldNames',
326
            //'embeddedClasses',
327
            'identifier',
328
            'className',
329
            'parent',
330
            'table',
331
            'valueGenerationPlan',
332
        ]);
333
334
        // The rest of the metadata is only serialized if necessary.
335 4
        if ($this->changeTrackingPolicy !== ChangeTrackingPolicy::DEFERRED_IMPLICIT) {
336
            $serialized[] = 'changeTrackingPolicy';
337
        }
338
339 4
        if ($this->customRepositoryClassName) {
340 1
            $serialized[] = 'customRepositoryClassName';
341
        }
342
343 4
        if ($this->inheritanceType !== InheritanceType::NONE) {
344 1
            $serialized[] = 'inheritanceType';
345 1
            $serialized[] = 'discriminatorColumn';
346 1
            $serialized[] = 'discriminatorValue';
347 1
            $serialized[] = 'discriminatorMap';
348 1
            $serialized[] = 'subClasses';
349
        }
350
351 4
        if ($this->isMappedSuperclass) {
352
            $serialized[] = 'isMappedSuperclass';
353
        }
354
355 4
        if ($this->isEmbeddedClass) {
356
            $serialized[] = 'isEmbeddedClass';
357
        }
358
359 4
        if ($this->isVersioned()) {
360
            $serialized[] = 'versionProperty';
361
        }
362
363 4
        if ($this->lifecycleCallbacks) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->lifecycleCallbacks of type array<mixed,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...
364
            $serialized[] = 'lifecycleCallbacks';
365
        }
366
367 4
        if ($this->entityListeners) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityListeners of type array<mixed,array<mixed,mixed>> 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...
368 1
            $serialized[] = 'entityListeners';
369
        }
370
371 4
        if ($this->cache) {
372
            $serialized[] = 'cache';
373
        }
374
375 4
        if ($this->readOnly) {
376 1
            $serialized[] = 'readOnly';
377
        }
378
379 4
        return $serialized;
380
    }
381
382
    /**
383
     * Restores some state that can not be serialized/unserialized.
384
     */
385 1634
    public function wakeupReflection(ReflectionService $reflectionService) : void
386
    {
387
        // Restore ReflectionClass and properties
388 1634
        $this->reflectionClass = $reflectionService->getClass($this->className);
389
390 1634
        if (! $this->reflectionClass) {
391
            return;
392
        }
393
394 1634
        $this->className = $this->reflectionClass->getName();
395
396 1634
        foreach ($this->properties as $property) {
397
            /** @var Property $property */
398 1633
            $property->wakeupReflection($reflectionService);
399
        }
400 1634
    }
401
402
    /**
403
     * Sets the change tracking policy used by this class.
404
     */
405 104
    public function setChangeTrackingPolicy(string $policy) : void
406
    {
407 104
        $this->changeTrackingPolicy = $policy;
408 104
    }
409
410
    /**
411
     * Checks whether a field is part of the identifier/primary key field(s).
412
     *
413
     * @param string $fieldName The field name.
414
     *
415
     * @return bool TRUE if the field is part of the table identifier/primary key field(s), FALSE otherwise.
416
     */
417 1027
    public function isIdentifier(string $fieldName) : bool
418
    {
419 1027
        if (! $this->identifier) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->identifier 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...
420 1
            return false;
421
        }
422
423 1026
        if (! $this->isIdentifierComposite()) {
424 1022
            return $fieldName === $this->identifier[0];
425
        }
426
427 93
        return in_array($fieldName, $this->identifier, true);
428
    }
429
430 1213
    public function isIdentifierComposite() : bool
431
    {
432 1213
        return isset($this->identifier[1]);
433
    }
434
435
    /**
436
     * Validates Identifier.
437
     *
438
     * @throws MappingException
439
     */
440 367
    public function validateIdentifier() : void
441
    {
442 367
        if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
443 27
            return;
444
        }
445
446
        // Verify & complete identifier mapping
447 367
        if (! $this->identifier) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->identifier 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...
448 2
            throw MappingException::identifierRequired($this->className);
449
        }
450
451
        $explicitlyGeneratedProperties = array_filter($this->properties, static function (Property $property) : bool {
452 365
            return $property instanceof FieldMetadata
453 365
                && $property->isPrimaryKey()
454 365
                && $property->hasValueGenerator();
455 365
        });
456
457 365
        if ($explicitlyGeneratedProperties && $this->isIdentifierComposite()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $explicitlyGeneratedProperties 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...
458
            throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->className);
459
        }
460 365
    }
461
462
    /**
463
     * Validates lifecycle callbacks.
464
     *
465
     * @throws MappingException
466
     */
467 368
    public function validateLifecycleCallbacks(ReflectionService $reflectionService) : void
468
    {
469 368
        foreach ($this->lifecycleCallbacks as $callbacks) {
470
            /** @var array $callbacks */
471 10
            foreach ($callbacks as $callbackFuncName) {
472 10
                if (! $reflectionService->hasPublicMethod($this->className, $callbackFuncName)) {
473 1
                    throw MappingException::lifecycleCallbackMethodNotFound($this->className, $callbackFuncName);
474
                }
475
            }
476
        }
477 367
    }
478
479
    /**
480
     * {@inheritDoc}
481
     */
482 401
    public function getIdentifierFieldNames()
483
    {
484 401
        return $this->identifier;
485
    }
486
487
    /**
488
     * Gets the name of the single id field. Note that this only works on
489
     * entity classes that have a single-field pk.
490
     *
491
     * @return string
492
     *
493
     * @throws MappingException If the class has a composite primary key.
494
     */
495 151
    public function getSingleIdentifierFieldName()
496
    {
497 151
        if ($this->isIdentifierComposite()) {
498 1
            throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->className);
499
        }
500
501 150
        if (! isset($this->identifier[0])) {
502 1
            throw MappingException::noIdDefined($this->className);
503
        }
504
505 149
        return $this->identifier[0];
506
    }
507
508
    /**
509
     * INTERNAL:
510
     * Sets the mapped identifier/primary key fields of this class.
511
     * Mainly used by the ClassMetadataFactory to assign inherited identifiers.
512
     *
513
     * @param mixed[] $identifier
514
     */
515 100
    public function setIdentifier(array $identifier)
516
    {
517 100
        $this->identifier = $identifier;
518 100
    }
519
520
    /**
521
     * {@inheritDoc}
522
     */
523 1053
    public function getIdentifier()
524
    {
525 1053
        return $this->identifier;
526
    }
527
528
    /**
529
     * {@inheritDoc}
530
     */
531 189
    public function hasField($fieldName)
532
    {
533 189
        return isset($this->properties[$fieldName])
534 189
            && $this->properties[$fieldName] instanceof FieldMetadata;
535
    }
536
537
    /**
538
     * Returns an array with identifier column names and their corresponding ColumnMetadata.
539
     *
540
     * @return ColumnMetadata[]
541
     */
542 441
    public function getIdentifierColumns(EntityManagerInterface $em) : array
543
    {
544 441
        $columns = [];
545
546 441
        foreach ($this->identifier as $idProperty) {
547 441
            $property = $this->getProperty($idProperty);
548
549 441
            if ($property instanceof FieldMetadata) {
550 435
                $columns[$property->getColumnName()] = $property;
551
552 435
                continue;
553
            }
554
555
            /** @var AssociationMetadata $property */
556
557
            // Association defined as Id field
558 25
            $targetClass = $em->getClassMetadata($property->getTargetEntity());
559
560 25
            if (! $property->isOwningSide()) {
561
                $property    = $targetClass->getProperty($property->getMappedBy());
0 ignored issues
show
Bug introduced by
The method getProperty() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. ( Ignorable by Annotation )

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

561
                /** @scrutinizer ignore-call */ 
562
                $property    = $targetClass->getProperty($property->getMappedBy());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
562
                $targetClass = $em->getClassMetadata($property->getTargetEntity());
563
            }
564
565 25
            $joinColumns = $property instanceof ManyToManyAssociationMetadata
566
                ? $property->getJoinTable()->getInverseJoinColumns()
567 25
                : $property->getJoinColumns();
568
569 25
            foreach ($joinColumns as $joinColumn) {
570
                /** @var JoinColumnMetadata $joinColumn */
571 25
                $columnName           = $joinColumn->getColumnName();
572 25
                $referencedColumnName = $joinColumn->getReferencedColumnName();
573
574 25
                if (! $joinColumn->getType()) {
575 13
                    $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $em));
0 ignored issues
show
Bug introduced by
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type Doctrine\ORM\Mapping\ClassMetadata expected by parameter $class of Doctrine\ORM\Utility\Per...lper::getTypeOfColumn(). ( Ignorable by Annotation )

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

575
                    $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, /** @scrutinizer ignore-type */ $targetClass, $em));
Loading history...
576
                }
577
578 25
                $columns[$columnName] = $joinColumn;
579
            }
580
        }
581
582 441
        return $columns;
583
    }
584
585
    /**
586
     * Gets the name of the primary table.
587
     */
588 1570
    public function getTableName() : ?string
589
    {
590 1570
        return $this->table->getName();
591
    }
592
593
    /**
594
     * Gets primary table's schema name.
595
     */
596 23
    public function getSchemaName() : ?string
597
    {
598 23
        return $this->table->getSchema();
599
    }
600
601
    /**
602
     * Gets the table name to use for temporary identifier tables of this class.
603
     */
604 7
    public function getTemporaryIdTableName() : string
605
    {
606 7
        $schema = $this->getSchemaName() === null
607 6
            ? ''
608 7
            : $this->getSchemaName() . '_';
609
610
        // replace dots with underscores because PostgreSQL creates temporary tables in a special schema
611 7
        return $schema . $this->getTableName() . '_id_tmp';
612
    }
613
614
    /**
615
     * Sets the mapped subclasses of this class.
616
     *
617
     * @param string[] $subclasses The names of all mapped subclasses.
618
     *
619
     * @todo guilhermeblanco Only used for ClassMetadataTest. Remove if possible!
620
     */
621 4
    public function setSubclasses(array $subclasses) : void
622
    {
623 4
        foreach ($subclasses as $subclass) {
624 3
            $this->subClasses[] = $subclass;
625
        }
626 4
    }
627
628
    /**
629
     * @return string[]
630
     */
631 1080
    public function getSubClasses() : array
632
    {
633 1080
        return $this->subClasses;
634
    }
635
636
    /**
637
     * Sets the inheritance type used by the class and its subclasses.
638
     *
639
     * @param int $type
640
     *
641
     * @throws MappingException
642
     */
643 120
    public function setInheritanceType($type) : void
644
    {
645 120
        if (! $this->isInheritanceType($type)) {
646
            throw MappingException::invalidInheritanceType($this->className, $type);
647
        }
648
649 120
        $this->inheritanceType = $type;
650 120
    }
651
652
    /**
653
     * Sets the override property mapping for an entity relationship.
654
     *
655
     * @throws RuntimeException
656
     * @throws MappingException
657
     * @throws CacheException
658
     */
659 12
    public function setPropertyOverride(Property $property) : void
660
    {
661 12
        $fieldName = $property->getName();
662
663 12
        if (! isset($this->properties[$fieldName])) {
664 2
            throw MappingException::invalidOverrideFieldName($this->className, $fieldName);
665
        }
666
667 10
        $originalProperty          = $this->getProperty($fieldName);
668 10
        $originalPropertyClassName = get_class($originalProperty);
669
670
        // If moving from transient to persistent, assume it's a new property
671 10
        if ($originalPropertyClassName === TransientMetadata::class) {
672 1
            unset($this->properties[$fieldName]);
673
674 1
            $this->addProperty($property);
675
676 1
            return;
677
        }
678
679
        // Do not allow to change property type
680 9
        if ($originalPropertyClassName !== get_class($property)) {
681
            throw MappingException::invalidOverridePropertyType($this->className, $fieldName);
682
        }
683
684
        // Do not allow to change version property
685 9
        if ($originalProperty instanceof FieldMetadata && $originalProperty->isVersioned()) {
686
            throw MappingException::invalidOverrideVersionField($this->className, $fieldName);
687
        }
688
689 9
        unset($this->properties[$fieldName]);
690
691 9
        if ($property instanceof FieldMetadata) {
692
            // Unset defined fieldName prior to override
693 5
            unset($this->fieldNames[$originalProperty->getColumnName()]);
0 ignored issues
show
Bug introduced by
The method getColumnName() 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\FieldMetadata. ( Ignorable by Annotation )

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

693
            unset($this->fieldNames[$originalProperty->/** @scrutinizer ignore-call */ getColumnName()]);
Loading history...
694
695
            // Revert what should not be allowed to change
696 5
            $property->setDeclaringClass($originalProperty->getDeclaringClass());
697 5
            $property->setPrimaryKey($originalProperty->isPrimaryKey());
698 9
        } elseif ($property instanceof AssociationMetadata) {
699
            // Unset all defined fieldNames prior to override
700 9
            if ($originalProperty instanceof ToOneAssociationMetadata && $originalProperty->isOwningSide()) {
701 5
                foreach ($originalProperty->getJoinColumns() as $joinColumn) {
702 5
                    unset($this->fieldNames[$joinColumn->getColumnName()]);
703
                }
704
            }
705
706
            // Override what it should be allowed to change
707 9
            if ($property->getInversedBy()) {
708 8
                $originalProperty->setInversedBy($property->getInversedBy());
0 ignored issues
show
Bug introduced by
The method setInversedBy() 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

708
                $originalProperty->/** @scrutinizer ignore-call */ 
709
                                   setInversedBy($property->getInversedBy());
Loading history...
709
            }
710
711 9
            if ($property->getFetchMode() !== $originalProperty->getFetchMode()) {
0 ignored issues
show
Bug introduced by
The method getFetchMode() 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

711
            if ($property->getFetchMode() !== $originalProperty->/** @scrutinizer ignore-call */ getFetchMode()) {
Loading history...
712 2
                $originalProperty->setFetchMode($property->getFetchMode());
0 ignored issues
show
Bug introduced by
The method setFetchMode() 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

712
                $originalProperty->/** @scrutinizer ignore-call */ 
713
                                   setFetchMode($property->getFetchMode());
Loading history...
713
            }
714
715 9
            if ($originalProperty instanceof ToOneAssociationMetadata && $property->getJoinColumns()) {
0 ignored issues
show
Bug introduced by
The method getJoinColumns() does not exist on Doctrine\ORM\Mapping\AssociationMetadata. It seems like you code against a sub-type of Doctrine\ORM\Mapping\AssociationMetadata such as Doctrine\ORM\Mapping\ToOneAssociationMetadata. ( Ignorable by Annotation )

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

715
            if ($originalProperty instanceof ToOneAssociationMetadata && $property->/** @scrutinizer ignore-call */ getJoinColumns()) {
Loading history...
716 5
                $originalProperty->setJoinColumns($property->getJoinColumns());
717 8
            } elseif ($originalProperty instanceof ManyToManyAssociationMetadata && $property->getJoinTable()) {
0 ignored issues
show
Bug introduced by
The method getJoinTable() does not exist on Doctrine\ORM\Mapping\AssociationMetadata. It seems like you code against a sub-type of Doctrine\ORM\Mapping\AssociationMetadata such as Doctrine\ORM\Mapping\ManyToManyAssociationMetadata. ( Ignorable by Annotation )

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

717
            } elseif ($originalProperty instanceof ManyToManyAssociationMetadata && $property->/** @scrutinizer ignore-call */ getJoinTable()) {
Loading history...
718 8
                $originalProperty->setJoinTable($property->getJoinTable());
719
            }
720
721 9
            $property = $originalProperty;
722
        }
723
724 9
        $this->addProperty($property);
0 ignored issues
show
Bug introduced by
It seems like $property can also be of type null; however, parameter $property of Doctrine\ORM\Mapping\ClassMetadata::addProperty() does only seem to accept Doctrine\ORM\Mapping\Property, maybe add an additional type check? ( Ignorable by Annotation )

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

724
        $this->addProperty(/** @scrutinizer ignore-type */ $property);
Loading history...
725 9
    }
726
727
    /**
728
     * Checks if this entity is the root in any entity-inheritance-hierarchy.
729
     *
730
     * @return bool
731
     */
732 336
    public function isRootEntity()
733
    {
734 336
        return $this->className === $this->getRootClassName();
735
    }
736
737
    /**
738
     * Checks whether a mapped field is inherited from a superclass.
739
     *
740
     * @param string $fieldName
741
     *
742
     * @return bool TRUE if the field is inherited, FALSE otherwise.
743
     */
744 622
    public function isInheritedProperty($fieldName)
745
    {
746 622
        $declaringClass = $this->properties[$fieldName]->getDeclaringClass();
747
748 622
        return $declaringClass->className !== $this->className;
749
    }
750
751
    /**
752
     * {@inheritdoc}
753
     */
754 431
    public function setTable(TableMetadata $table) : void
755
    {
756 431
        $this->table = $table;
757
758
        // Make sure inherited and declared properties reflect newly defined table
759 431
        foreach ($this->properties as $property) {
760
            switch (true) {
761 95
                case $property instanceof FieldMetadata:
762 95
                    $property->setTableName($property->getTableName() ?? $table->getName());
763 95
                    break;
764
765 42
                case $property instanceof ToOneAssociationMetadata:
766
                    // Resolve association join column table names
767 34
                    foreach ($property->getJoinColumns() as $joinColumn) {
768
                        /** @var JoinColumnMetadata $joinColumn */
769 34
                        $joinColumn->setTableName($joinColumn->getTableName() ?? $table->getName());
770
                    }
771
772 34
                    break;
773
            }
774
        }
775 431
    }
776
777
    /**
778
     * Checks whether the given type identifies an inheritance type.
779
     *
780
     * @param int $type
781
     *
782
     * @return bool TRUE if the given type identifies an inheritance type, FALSe otherwise.
783
     */
784 120
    private function isInheritanceType($type)
785
    {
786 120
        return $type === InheritanceType::NONE
787 93
            || $type === InheritanceType::SINGLE_TABLE
788 51
            || $type === InheritanceType::JOINED
789 120
            || $type === InheritanceType::TABLE_PER_CLASS;
790
    }
791
792 916
    public function getColumn(string $columnName) : ?LocalColumnMetadata
793
    {
794 916
        foreach ($this->properties as $property) {
795 916
            if ($property instanceof LocalColumnMetadata && $property->getColumnName() === $columnName) {
796 916
                return $property;
797
            }
798
        }
799
800
        return null;
801
    }
802
803
    /**
804
     * Add a property mapping.
805
     *
806
     * @throws RuntimeException
807
     * @throws MappingException
808
     * @throws CacheException
809
     * @throws ReflectionException
810
     */
811 417
    public function addProperty(Property $property) : void
812
    {
813 417
        $fieldName = $property->getName();
814
815
        // Check for empty field name
816 417
        if (empty($fieldName)) {
817 1
            throw MappingException::missingFieldName($this->className);
818
        }
819
820 416
        $property->setDeclaringClass($this);
821
822
        switch (true) {
823 416
            case $property instanceof FieldMetadata:
824 406
                if ($property->isVersioned()) {
825 20
                    $this->versionProperty = $property;
826
                }
827
828 406
                break;
829
830
            default:
831
                // Transient properties are ignored on purpose here! =)
832 275
                break;
833
        }
834
835 416
        if ($property->isPrimaryKey() && ! in_array($fieldName, $this->identifier, true)) {
836 395
            $this->identifier[] = $fieldName;
837
        }
838
839 416
        parent::addProperty($property);
840 416
    }
841
842
    /**
843
     * INTERNAL:
844
     * Adds a property mapping without completing/validating it.
845
     * This is mainly used to add inherited property mappings to derived classes.
846
     */
847 96
    public function addInheritedProperty(Property $property)
848
    {
849 96
        if (isset($this->properties[$property->getName()])) {
850 1
            throw MappingException::duplicateProperty($this->className, $this->getProperty($property->getName()));
0 ignored issues
show
Bug introduced by
It seems like $this->getProperty($property->getName()) can also be of type null; however, parameter $property of Doctrine\ORM\Mapping\Map...on::duplicateProperty() does only seem to accept Doctrine\ORM\Mapping\Property, maybe add an additional type check? ( Ignorable by Annotation )

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

850
            throw MappingException::duplicateProperty($this->className, /** @scrutinizer ignore-type */ $this->getProperty($property->getName()));
Loading history...
851
        }
852
853 96
        $declaringClass    = $property->getDeclaringClass();
854 96
        $inheritedProperty = $declaringClass->isMappedSuperclass ? clone $property : $property;
855
856 96
        if ($inheritedProperty instanceof FieldMetadata) {
857 95
            if (! $declaringClass->isMappedSuperclass) {
858 73
                $inheritedProperty->setTableName($property->getTableName());
0 ignored issues
show
Bug introduced by
The method getTableName() 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\FieldMetadata. ( Ignorable by Annotation )

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

858
                $inheritedProperty->setTableName($property->/** @scrutinizer ignore-call */ getTableName());
Loading history...
859
            }
860
861 95
            if ($inheritedProperty->isVersioned()) {
862 4
                $this->versionProperty = $inheritedProperty;
863
            }
864
865 95
            $this->fieldNames[$property->getColumnName()] = $property->getName();
866 43
        } elseif ($inheritedProperty instanceof AssociationMetadata) {
867 42
            if ($declaringClass->isMappedSuperclass) {
868 10
                $inheritedProperty->setSourceEntity($this->className);
869
            }
870
871
            // Need to add inherited fieldNames
872 42
            if ($inheritedProperty instanceof ToOneAssociationMetadata && $inheritedProperty->isOwningSide()) {
873 35
                foreach ($inheritedProperty->getJoinColumns() as $joinColumn) {
874
                    /** @var JoinColumnMetadata $joinColumn */
875 34
                    $this->fieldNames[$joinColumn->getColumnName()] = $property->getName();
876
                }
877
            }
878
        }
879
880 96
        $this->properties[$property->getName()] = $inheritedProperty;
881 96
    }
882
883
    /**
884
     * Registers a custom repository class for the entity class.
885
     *
886
     * @param string|null $repositoryClassName The class name of the custom mapper.
887
     */
888 30
    public function setCustomRepositoryClassName(?string $repositoryClassName)
889
    {
890 30
        $this->customRepositoryClassName = $repositoryClassName;
891 30
    }
892
893 163
    public function getCustomRepositoryClassName() : ?string
894
    {
895 163
        return $this->customRepositoryClassName;
896
    }
897
898
    /**
899
     * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event.
900
     *
901
     * @param string $lifecycleEvent
902
     *
903
     * @return bool
904
     */
905
    public function hasLifecycleCallbacks($lifecycleEvent)
906
    {
907
        return isset($this->lifecycleCallbacks[$lifecycleEvent]);
908
    }
909
910
    /**
911
     * Gets the registered lifecycle callbacks for an event.
912
     *
913
     * @param string $event
914
     *
915
     * @return string[]
916
     */
917
    public function getLifecycleCallbacks($event) : array
918
    {
919
        return $this->lifecycleCallbacks[$event] ?? [];
920
    }
921
922
    /**
923
     * Adds a lifecycle callback for entities of this class.
924
     */
925 16
    public function addLifecycleCallback(string $eventName, string $methodName)
926
    {
927 16
        if (in_array($methodName, $this->lifecycleCallbacks[$eventName] ?? [], true)) {
928 3
            return;
929
        }
930
931 16
        $this->lifecycleCallbacks[$eventName][] = $methodName;
932 16
    }
933
934
    /**
935
     * Adds a entity listener for entities of this class.
936
     *
937
     * @param string $eventName The entity lifecycle event.
938
     * @param string $class     The listener class.
939
     * @param string $method    The listener callback method.
940
     *
941
     * @throws MappingException
942
     */
943 13
    public function addEntityListener(string $eventName, string $class, string $methodName) : void
944
    {
945
        $listener = [
946 13
            'class'  => $class,
947 13
            'method' => $methodName,
948
        ];
949
950 13
        if (! class_exists($class)) {
951 1
            throw MappingException::entityListenerClassNotFound($class, $this->className);
952
        }
953
954 12
        if (! method_exists($class, $methodName)) {
955 1
            throw MappingException::entityListenerMethodNotFound($class, $methodName, $this->className);
956
        }
957
958
        // Check if entity listener already got registered and ignore it if positive
959 11
        if (in_array($listener, $this->entityListeners[$eventName] ?? [], true)) {
960 5
            return;
961
        }
962
963 11
        $this->entityListeners[$eventName][] = $listener;
964 11
    }
965
966
    /**
967
     * Sets the discriminator column definition.
968
     *
969
     * @see getDiscriminatorColumn()
970
     *
971
     * @throws MappingException
972
     */
973 94
    public function setDiscriminatorColumn(DiscriminatorColumnMetadata $discriminatorColumn) : void
974
    {
975 94
        if (isset($this->fieldNames[$discriminatorColumn->getColumnName()])) {
976
            throw MappingException::duplicateColumnName($this->className, $discriminatorColumn->getColumnName());
977
        }
978
979 94
        $discriminatorColumn->setTableName($discriminatorColumn->getTableName() ?? $this->getTableName());
980
981 94
        $allowedTypeList = ['boolean', 'array', 'object', 'datetime', 'time', 'date'];
982
983 94
        if (in_array($discriminatorColumn->getTypeName(), $allowedTypeList, true)) {
984
            throw MappingException::invalidDiscriminatorColumnType($discriminatorColumn->getTypeName());
985
        }
986
987 94
        $this->discriminatorColumn = $discriminatorColumn;
988 94
    }
989
990
    /**
991
     * Sets the discriminator values used by this class.
992
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
993
     *
994
     * @param string[] $map
995
     *
996
     * @throws MappingException
997
     */
998 89
    public function setDiscriminatorMap(array $map) : void
999
    {
1000 89
        foreach ($map as $value => $className) {
1001 89
            $this->addDiscriminatorMapClass($value, $className);
1002
        }
1003 89
    }
1004
1005
    /**
1006
     * Adds one entry of the discriminator map with a new class and corresponding name.
1007
     *
1008
     * @param string|int $name
1009
     *
1010
     * @throws MappingException
1011
     */
1012 89
    public function addDiscriminatorMapClass($name, string $className) : void
1013
    {
1014 89
        $this->discriminatorMap[$name] = $className;
1015
1016 89
        if ($this->className === $className) {
1017 75
            $this->discriminatorValue = $name;
1018
1019 75
            return;
1020
        }
1021
1022 88
        if (! (class_exists($className) || interface_exists($className))) {
1023
            throw MappingException::invalidClassInDiscriminatorMap($className, $this->className);
1024
        }
1025
1026 88
        if (is_subclass_of($className, $this->className) && ! in_array($className, $this->subClasses, true)) {
1027 83
            $this->subClasses[] = $className;
1028
        }
1029 88
    }
1030
1031 1031
    public function getValueGenerationPlan() : ValueGenerationPlan
1032
    {
1033 1031
        return $this->valueGenerationPlan;
1034
    }
1035
1036 367
    public function setValueGenerationPlan(ValueGenerationPlan $valueGenerationPlan) : void
1037
    {
1038 367
        $this->valueGenerationPlan = $valueGenerationPlan;
1039 367
    }
1040
1041 398
    public function checkPropertyDuplication(string $columnName) : bool
1042
    {
1043 398
        return isset($this->fieldNames[$columnName])
1044 398
            || ($this->discriminatorColumn !== null && $this->discriminatorColumn->getColumnName() === $columnName);
1045
    }
1046
1047
    /**
1048
     * Marks this class as read only, no change tracking is applied to it.
1049
     */
1050 2
    public function asReadOnly() : void
1051
    {
1052 2
        $this->readOnly = true;
1053 2
    }
1054
1055
    /**
1056
     * Whether this class is read only or not.
1057
     */
1058 446
    public function isReadOnly() : bool
1059
    {
1060 446
        return $this->readOnly;
1061
    }
1062
1063 1091
    public function isVersioned() : bool
1064
    {
1065 1091
        return $this->versionProperty !== null;
1066
    }
1067
1068
    /**
1069
     * Map Embedded Class
1070
     *
1071
     * @param mixed[] $mapping
1072
     *
1073
     * @throws MappingException
1074
     */
1075
    public function mapEmbedded(array $mapping) : void
0 ignored issues
show
Unused Code introduced by
The parameter $mapping 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

1075
    public function mapEmbedded(/** @scrutinizer ignore-unused */ array $mapping) : void

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...
1076
    {
1077
        /*if (isset($this->properties[$mapping['fieldName']])) {
1078
            throw MappingException::duplicateProperty($this->className, $this->getProperty($mapping['fieldName']));
1079
        }
1080
1081
        $this->embeddedClasses[$mapping['fieldName']] = [
1082
            'class'          => $this->fullyQualifiedClassName($mapping['class']),
1083
            'columnPrefix'   => $mapping['columnPrefix'],
1084
            'declaredField'  => $mapping['declaredField'] ?? null,
1085
            'originalField'  => $mapping['originalField'] ?? null,
1086
            'declaringClass' => $this,
1087
        ];*/
1088
    }
1089
1090
    /**
1091
     * Inline the embeddable class
1092
     *
1093
     * @param string $property
1094
     */
1095
    public function inlineEmbeddable($property, ClassMetadata $embeddable) : void
0 ignored issues
show
Unused Code introduced by
The parameter $embeddable 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

1095
    public function inlineEmbeddable($property, /** @scrutinizer ignore-unused */ ClassMetadata $embeddable) : void

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...
Unused Code introduced by
The parameter $property 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

1095
    public function inlineEmbeddable(/** @scrutinizer ignore-unused */ $property, ClassMetadata $embeddable) : void

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...
1096
    {
1097
        /*foreach ($embeddable->fieldMappings as $fieldName => $fieldMapping) {
1098
            $fieldMapping['fieldName']     = $property . "." . $fieldName;
1099
            $fieldMapping['originalClass'] = $fieldMapping['originalClass'] ?? $embeddable->getClassName();
1100
            $fieldMapping['originalField'] = $fieldMapping['originalField'] ?? $fieldName;
1101
            $fieldMapping['declaredField'] = isset($fieldMapping['declaredField'])
1102
                ? $property . '.' . $fieldMapping['declaredField']
1103
                : $property;
1104
1105
            if (! empty($this->embeddedClasses[$property]['columnPrefix'])) {
1106
                $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName'];
1107
            } elseif ($this->embeddedClasses[$property]['columnPrefix'] !== false) {
1108
                $fieldMapping['columnName'] = $this->namingStrategy->embeddedFieldToColumnName(
1109
                    $property,
1110
                    $fieldMapping['columnName'],
1111
                    $this->reflectionClass->getName(),
1112
                    $embeddable->reflectionClass->getName()
1113
                );
1114
            }
1115
1116
            $this->mapField($fieldMapping);
1117
        }*/
1118
    }
1119
}
1120