-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
ClassMetadata.php
2649 lines (2267 loc) · 85 KB
/
ClassMetadata.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Doctrine\ORM\Mapping;
use BackedEnum;
use BadMethodCallException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\Deprecations\Deprecation;
use Doctrine\Instantiator\Instantiator;
use Doctrine\Instantiator\InstantiatorInterface;
use Doctrine\ORM\Cache\Exception\NonCacheableEntityAssociation;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Doctrine\Persistence\Mapping\ClassMetadata as PersistenceClassMetadata;
use Doctrine\Persistence\Mapping\ReflectionService;
use Doctrine\Persistence\Reflection\EnumReflectionProperty;
use InvalidArgumentException;
use LogicException;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
use Stringable;
use function array_diff;
use function array_intersect;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_pop;
use function array_values;
use function assert;
use function class_exists;
use function count;
use function enum_exists;
use function explode;
use function in_array;
use function interface_exists;
use function is_string;
use function is_subclass_of;
use function ltrim;
use function method_exists;
use function spl_object_id;
use function sprintf;
use function str_contains;
use function str_replace;
use function strtolower;
use function trait_exists;
use function trim;
/**
* A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
* of an entity and its associations.
*
* Once populated, ClassMetadata instances are usually cached in a serialized form.
*
* <b>IMPORTANT NOTE:</b>
*
* The fields of this class are only public for 2 reasons:
* 1) To allow fast READ access.
* 2) To drastically reduce the size of a serialized instance (private/protected members
* get the whole class name, namespace inclusive, prepended to every property in
* the serialized representation).
*
* @psalm-type ConcreteAssociationMapping = OneToOneOwningSideMapping|OneToOneInverseSideMapping|ManyToOneAssociationMapping|OneToManyAssociationMapping|ManyToManyOwningSideMapping|ManyToManyInverseSideMapping
* @template-covariant T of object
* @template-implements PersistenceClassMetadata<T>
*/
class ClassMetadata implements PersistenceClassMetadata, Stringable
{
/* The inheritance mapping types */
/**
* NONE means the class does not participate in an inheritance hierarchy
* and therefore does not need an inheritance mapping type.
*/
public const INHERITANCE_TYPE_NONE = 1;
/**
* JOINED means the class will be persisted according to the rules of
* <tt>Class Table Inheritance</tt>.
*/
public const INHERITANCE_TYPE_JOINED = 2;
/**
* SINGLE_TABLE means the class will be persisted according to the rules of
* <tt>Single Table Inheritance</tt>.
*/
public const INHERITANCE_TYPE_SINGLE_TABLE = 3;
/* The Id generator types. */
/**
* AUTO means the generator type will depend on what the used platform prefers.
* Offers full portability.
*/
public const GENERATOR_TYPE_AUTO = 1;
/**
* SEQUENCE means a separate sequence object will be used. Platforms that do
* not have native sequence support may emulate it. Full portability is currently
* not guaranteed.
*/
public const GENERATOR_TYPE_SEQUENCE = 2;
/**
* IDENTITY means an identity column is used for id generation. The database
* will fill in the id column on insertion. Platforms that do not support
* native identity columns may emulate them. Full portability is currently
* not guaranteed.
*/
public const GENERATOR_TYPE_IDENTITY = 4;
/**
* NONE means the class does not have a generated id. That means the class
* must have a natural, manually assigned id.
*/
public const GENERATOR_TYPE_NONE = 5;
/**
* CUSTOM means that customer will use own ID generator that supposedly work
*/
public const GENERATOR_TYPE_CUSTOM = 7;
/**
* DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
* by doing a property-by-property comparison with the original data. This will
* be done for all entities that are in MANAGED state at commit-time.
*
* This is the default change tracking policy.
*/
public const CHANGETRACKING_DEFERRED_IMPLICIT = 1;
/**
* DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
* by doing a property-by-property comparison with the original data. This will
* be done only for entities that were explicitly saved (through persist() or a cascade).
*/
public const CHANGETRACKING_DEFERRED_EXPLICIT = 2;
/**
* Specifies that an association is to be fetched when it is first accessed.
*/
public const FETCH_LAZY = 2;
/**
* Specifies that an association is to be fetched when the owner of the
* association is fetched.
*/
public const FETCH_EAGER = 3;
/**
* Specifies that an association is to be fetched lazy (on first access) and that
* commands such as Collection#count, Collection#slice are issued directly against
* the database if the collection is not yet initialized.
*/
public const FETCH_EXTRA_LAZY = 4;
/**
* Identifies a one-to-one association.
*/
public const ONE_TO_ONE = 1;
/**
* Identifies a many-to-one association.
*/
public const MANY_TO_ONE = 2;
/**
* Identifies a one-to-many association.
*/
public const ONE_TO_MANY = 4;
/**
* Identifies a many-to-many association.
*/
public const MANY_TO_MANY = 8;
/**
* Combined bitmask for to-one (single-valued) associations.
*/
public const TO_ONE = 3;
/**
* Combined bitmask for to-many (collection-valued) associations.
*/
public const TO_MANY = 12;
/**
* ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks,
*/
public const CACHE_USAGE_READ_ONLY = 1;
/**
* Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes.
*/
public const CACHE_USAGE_NONSTRICT_READ_WRITE = 2;
/**
* Read Write Attempts to lock the entity before update/delete.
*/
public const CACHE_USAGE_READ_WRITE = 3;
/**
* The value of this column is never generated by the database.
*/
public const GENERATED_NEVER = 0;
/**
* The value of this column is generated by the database on INSERT, but not on UPDATE.
*/
public const GENERATED_INSERT = 1;
/**
* The value of this column is generated by the database on both INSERT and UDPATE statements.
*/
public const GENERATED_ALWAYS = 2;
/**
* READ-ONLY: The namespace the entity class is contained in.
*
* @todo Not really needed. Usage could be localized.
*/
public string|null $namespace = null;
/**
* READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance
* hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same
* as {@link $name}.
*
* @psalm-var class-string
*/
public string $rootEntityName;
/**
* READ-ONLY: The definition of custom generator. Only used for CUSTOM
* generator type
*
* The definition has the following structure:
* <code>
* array(
* 'class' => 'ClassName',
* )
* </code>
*
* @todo Merge with tableGeneratorDefinition into generic generatorDefinition
* @var array<string, string>|null
*/
public array|null $customGeneratorDefinition = null;
/**
* The name of the custom repository class used for the entity class.
* (Optional).
*
* @psalm-var ?class-string<EntityRepository>
*/
public string|null $customRepositoryClassName = null;
/**
* READ-ONLY: Whether this class describes the mapping of a mapped superclass.
*/
public bool $isMappedSuperclass = false;
/**
* READ-ONLY: Whether this class describes the mapping of an embeddable class.
*/
public bool $isEmbeddedClass = false;
/**
* READ-ONLY: The names of the parent <em>entity</em> classes (ancestors), starting with the
* nearest one and ending with the root entity class.
*
* @psalm-var list<class-string>
*/
public array $parentClasses = [];
/**
* READ-ONLY: For classes in inheritance mapping hierarchies, this field contains the names of all
* <em>entity</em> subclasses of this class. These may also be abstract classes.
*
* This list is used, for example, to enumerate all necessary tables in JTI when querying for root
* or subclass entities, or to gather all fields comprised in an entity inheritance tree.
*
* For classes that do not use STI/JTI, this list is empty.
*
* Implementation note:
*
* In PHP, there is no general way to discover all subclasses of a given class at runtime. For that
* reason, the list of classes given in the discriminator map at the root entity is considered
* authoritative. The discriminator map must contain all <em>concrete</em> classes that can
* appear in the particular inheritance hierarchy tree. Since there can be no instances of abstract
* entity classes, users are not required to list such classes with a discriminator value.
*
* The possibly remaining "gaps" for abstract entity classes are filled after the class metadata for the
* root entity has been loaded.
*
* For subclasses of such root entities, the list can be reused/passed downwards, it only needs to
* be filtered accordingly (only keep remaining subclasses)
*
* @psalm-var list<class-string>
*/
public array $subClasses = [];
/**
* READ-ONLY: The names of all embedded classes based on properties.
*
* @psalm-var array<string, EmbeddedClassMapping>
*/
public array $embeddedClasses = [];
/**
* READ-ONLY: The field names of all fields that are part of the identifier/primary key
* of the mapped entity class.
*
* @psalm-var list<string>
*/
public array $identifier = [];
/**
* READ-ONLY: The inheritance mapping type used by the class.
*
* @psalm-var self::INHERITANCE_TYPE_*
*/
public int $inheritanceType = self::INHERITANCE_TYPE_NONE;
/**
* READ-ONLY: The Id generator type used by the class.
*
* @psalm-var self::GENERATOR_TYPE_*
*/
public int $generatorType = self::GENERATOR_TYPE_NONE;
/**
* READ-ONLY: The field mappings of the class.
* Keys are field names and values are FieldMapping instances
*
* @var array<string, FieldMapping>
*/
public array $fieldMappings = [];
/**
* READ-ONLY: An array of field names. Used to look up field names from column names.
* Keys are column names and values are field names.
*
* @psalm-var array<string, string>
*/
public array $fieldNames = [];
/**
* READ-ONLY: A map of field names to column names. Keys are field names and values column names.
* Used to look up column names from field names.
* This is the reverse lookup map of $_fieldNames.
*
* @deprecated 3.0 Remove this.
*
* @var mixed[]
*/
public array $columnNames = [];
/**
* READ-ONLY: The discriminator value of this class.
*
* <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
* where a discriminator column is used.</b>
*
* @see discriminatorColumn
*/
public mixed $discriminatorValue = null;
/**
* READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
*
* <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
* where a discriminator column is used.</b>
*
* @see discriminatorColumn
*
* @var array<int|string, string>
*
* @psalm-var array<int|string, class-string>
*/
public array $discriminatorMap = [];
/**
* READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
* inheritance mappings.
*/
public DiscriminatorColumnMapping|null $discriminatorColumn = null;
/**
* READ-ONLY: The primary table definition. The definition is an array with the
* following entries:
*
* name => <tableName>
* schema => <schemaName>
* indexes => array
* uniqueConstraints => array
*
* @var mixed[]
* @psalm-var array{
* name: string,
* schema?: string,
* indexes?: array,
* uniqueConstraints?: array,
* options?: array<string, mixed>,
* quoted?: bool
* }
*/
public array $table;
/**
* READ-ONLY: The registered lifecycle callbacks for entities of this class.
*
* @psalm-var array<string, list<string>>
*/
public array $lifecycleCallbacks = [];
/**
* READ-ONLY: The registered entity listeners.
*
* @psalm-var array<string, list<array{class: class-string, method: string}>>
*/
public array $entityListeners = [];
/**
* READ-ONLY: The association mappings of this class.
*
* A join table definition has the following structure:
* <pre>
* array(
* 'name' => <join table name>,
* 'joinColumns' => array(<join column mapping from join table to source table>),
* 'inverseJoinColumns' => array(<join column mapping from join table to target table>)
* )
* </pre>
*
* @psalm-var array<string, ConcreteAssociationMapping>
*/
public array $associationMappings = [];
/**
* READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite.
*/
public bool $isIdentifierComposite = false;
/**
* READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association.
*
* This flag is necessary because some code blocks require special treatment of this cases.
*/
public bool $containsForeignIdentifier = false;
/**
* READ-ONLY: Flag indicating whether the identifier/primary key contains at least one ENUM type.
*
* This flag is necessary because some code blocks require special treatment of this cases.
*/
public bool $containsEnumIdentifier = false;
/**
* READ-ONLY: The ID generator used for generating IDs for this class.
*
* @todo Remove!
*/
public AbstractIdGenerator $idGenerator;
/**
* READ-ONLY: The definition of the sequence generator of this class. Only used for the
* SEQUENCE generation strategy.
*
* The definition has the following structure:
* <code>
* array(
* 'sequenceName' => 'name',
* 'allocationSize' => '20',
* 'initialValue' => '1'
* )
* </code>
*
* @var array<string, mixed>|null
* @psalm-var array{sequenceName: string, allocationSize: string, initialValue: string, quoted?: mixed}|null
* @todo Merge with tableGeneratorDefinition into generic generatorDefinition
*/
public array|null $sequenceGeneratorDefinition = null;
/**
* READ-ONLY: The policy used for change-tracking on entities of this class.
*/
public int $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT;
/**
* READ-ONLY: A Flag indicating whether one or more columns of this class
* have to be reloaded after insert / update operations.
*/
public bool $requiresFetchAfterChange = false;
/**
* READ-ONLY: A flag for whether or not instances of this class are to be versioned
* with optimistic locking.
*/
public bool $isVersioned = false;
/**
* READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
*/
public string|null $versionField = null;
/** @var mixed[]|null */
public array|null $cache = null;
/**
* The ReflectionClass instance of the mapped class.
*
* @var ReflectionClass<T>|null
*/
public ReflectionClass|null $reflClass = null;
/**
* Is this entity marked as "read-only"?
*
* That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance
* optimization for entities that are immutable, either in your domain or through the relation database
* (coming from a view, or a history table for example).
*/
public bool $isReadOnly = false;
/**
* NamingStrategy determining the default column and table names.
*/
protected NamingStrategy $namingStrategy;
/**
* The ReflectionProperty instances of the mapped class.
*
* @var array<string, ReflectionProperty|null>
*/
public array $reflFields = [];
private InstantiatorInterface|null $instantiator = null;
private readonly TypedFieldMapper $typedFieldMapper;
/**
* Initializes a new ClassMetadata instance that will hold the object-relational mapping
* metadata of the class with the given name.
*
* @param string $name The name of the entity class the new instance is used for.
* @psalm-param class-string<T> $name
*/
public function __construct(public string $name, NamingStrategy|null $namingStrategy = null, TypedFieldMapper|null $typedFieldMapper = null)
{
$this->rootEntityName = $name;
$this->namingStrategy = $namingStrategy ?? new DefaultNamingStrategy();
$this->instantiator = new Instantiator();
$this->typedFieldMapper = $typedFieldMapper ?? new DefaultTypedFieldMapper();
}
/**
* Gets the ReflectionProperties of the mapped class.
*
* @return ReflectionProperty[]|null[] An array of ReflectionProperty instances.
* @psalm-return array<ReflectionProperty|null>
*/
public function getReflectionProperties(): array
{
return $this->reflFields;
}
/**
* Gets a ReflectionProperty for a specific field of the mapped class.
*/
public function getReflectionProperty(string $name): ReflectionProperty|null
{
return $this->reflFields[$name];
}
/**
* Gets the ReflectionProperty for the single identifier field.
*
* @throws BadMethodCallException If the class has a composite identifier.
*/
public function getSingleIdReflectionProperty(): ReflectionProperty|null
{
if ($this->isIdentifierComposite) {
throw new BadMethodCallException('Class ' . $this->name . ' has a composite identifier.');
}
return $this->reflFields[$this->identifier[0]];
}
/**
* Extracts the identifier values of an entity of this class.
*
* For composite identifiers, the identifier values are returned as an array
* with the same order as the field order in {@link identifier}.
*
* @return array<string, mixed>
*/
public function getIdentifierValues(object $entity): array
{
if ($this->isIdentifierComposite) {
$id = [];
foreach ($this->identifier as $idField) {
$value = $this->reflFields[$idField]->getValue($entity);
if ($value !== null) {
$id[$idField] = $value;
}
}
return $id;
}
$id = $this->identifier[0];
$value = $this->reflFields[$id]->getValue($entity);
if ($value === null) {
return [];
}
return [$id => $value];
}
/**
* Populates the entity identifier of an entity.
*
* @psalm-param array<string, mixed> $id
*
* @todo Rename to assignIdentifier()
*/
public function setIdentifierValues(object $entity, array $id): void
{
foreach ($id as $idField => $idValue) {
$this->reflFields[$idField]->setValue($entity, $idValue);
}
}
/**
* Sets the specified field to the specified value on the given entity.
*/
public function setFieldValue(object $entity, string $field, mixed $value): void
{
$this->reflFields[$field]->setValue($entity, $value);
}
/**
* Gets the specified field's value off the given entity.
*/
public function getFieldValue(object $entity, string $field): mixed
{
return $this->reflFields[$field]->getValue($entity);
}
/**
* Creates a string representation of this instance.
*
* @return string The string representation of this instance.
*
* @todo Construct meaningful string representation.
*/
public function __toString(): string
{
return self::class . '@' . spl_object_id($this);
}
/**
* Determines which fields get serialized.
*
* It is only serialized what is necessary for best unserialization performance.
* That means any metadata properties that are not set or empty or simply have
* their default value are NOT serialized.
*
* Parts that are also NOT serialized because they can not be properly unserialized:
* - reflClass (ReflectionClass)
* - reflFields (ReflectionProperty array)
*
* @return string[] The names of all the fields that should be serialized.
*/
public function __sleep(): array
{
// This metadata is always serialized/cached.
$serialized = [
'associationMappings',
'columnNames', //TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName']
'fieldMappings',
'fieldNames',
'embeddedClasses',
'identifier',
'isIdentifierComposite', // TODO: REMOVE
'name',
'namespace', // TODO: REMOVE
'table',
'rootEntityName',
'idGenerator', //TODO: Does not really need to be serialized. Could be moved to runtime.
];
// The rest of the metadata is only serialized if necessary.
if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) {
$serialized[] = 'changeTrackingPolicy';
}
if ($this->customRepositoryClassName) {
$serialized[] = 'customRepositoryClassName';
}
if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE) {
$serialized[] = 'inheritanceType';
$serialized[] = 'discriminatorColumn';
$serialized[] = 'discriminatorValue';
$serialized[] = 'discriminatorMap';
$serialized[] = 'parentClasses';
$serialized[] = 'subClasses';
}
if ($this->generatorType !== self::GENERATOR_TYPE_NONE) {
$serialized[] = 'generatorType';
if ($this->generatorType === self::GENERATOR_TYPE_SEQUENCE) {
$serialized[] = 'sequenceGeneratorDefinition';
}
}
if ($this->isMappedSuperclass) {
$serialized[] = 'isMappedSuperclass';
}
if ($this->isEmbeddedClass) {
$serialized[] = 'isEmbeddedClass';
}
if ($this->containsForeignIdentifier) {
$serialized[] = 'containsForeignIdentifier';
}
if ($this->containsEnumIdentifier) {
$serialized[] = 'containsEnumIdentifier';
}
if ($this->isVersioned) {
$serialized[] = 'isVersioned';
$serialized[] = 'versionField';
}
if ($this->lifecycleCallbacks) {
$serialized[] = 'lifecycleCallbacks';
}
if ($this->entityListeners) {
$serialized[] = 'entityListeners';
}
if ($this->isReadOnly) {
$serialized[] = 'isReadOnly';
}
if ($this->customGeneratorDefinition) {
$serialized[] = 'customGeneratorDefinition';
}
if ($this->cache) {
$serialized[] = 'cache';
}
if ($this->requiresFetchAfterChange) {
$serialized[] = 'requiresFetchAfterChange';
}
return $serialized;
}
/**
* Creates a new instance of the mapped class, without invoking the constructor.
*/
public function newInstance(): object
{
return $this->instantiator->instantiate($this->name);
}
/**
* Restores some state that can not be serialized/unserialized.
*/
public function wakeupReflection(ReflectionService $reflService): void
{
// Restore ReflectionClass and properties
$this->reflClass = $reflService->getClass($this->name);
$this->instantiator = $this->instantiator ?: new Instantiator();
$parentReflFields = [];
foreach ($this->embeddedClasses as $property => $embeddedClass) {
if (isset($embeddedClass->declaredField)) {
assert($embeddedClass->originalField !== null);
$childProperty = $this->getAccessibleProperty(
$reflService,
$this->embeddedClasses[$embeddedClass->declaredField]->class,
$embeddedClass->originalField,
);
assert($childProperty !== null);
$parentReflFields[$property] = new ReflectionEmbeddedProperty(
$parentReflFields[$embeddedClass->declaredField],
$childProperty,
$this->embeddedClasses[$embeddedClass->declaredField]->class,
);
continue;
}
$fieldRefl = $this->getAccessibleProperty(
$reflService,
$embeddedClass->declared ?? $this->name,
$property,
);
$parentReflFields[$property] = $fieldRefl;
$this->reflFields[$property] = $fieldRefl;
}
foreach ($this->fieldMappings as $field => $mapping) {
if (isset($mapping->declaredField) && isset($parentReflFields[$mapping->declaredField])) {
assert($mapping->originalField !== null);
assert($mapping->originalClass !== null);
$childProperty = $this->getAccessibleProperty($reflService, $mapping->originalClass, $mapping->originalField);
assert($childProperty !== null);
if (isset($mapping->enumType)) {
$childProperty = new EnumReflectionProperty(
$childProperty,
$mapping->enumType,
);
}
$this->reflFields[$field] = new ReflectionEmbeddedProperty(
$parentReflFields[$mapping->declaredField],
$childProperty,
$mapping->originalClass,
);
continue;
}
$this->reflFields[$field] = isset($mapping->declared)
? $this->getAccessibleProperty($reflService, $mapping->declared, $field)
: $this->getAccessibleProperty($reflService, $this->name, $field);
if (isset($mapping->enumType) && $this->reflFields[$field] !== null) {
$this->reflFields[$field] = new EnumReflectionProperty(
$this->reflFields[$field],
$mapping->enumType,
);
}
}
foreach ($this->associationMappings as $field => $mapping) {
$this->reflFields[$field] = isset($mapping->declared)
? $this->getAccessibleProperty($reflService, $mapping->declared, $field)
: $this->getAccessibleProperty($reflService, $this->name, $field);
}
}
/**
* Initializes a new ClassMetadata instance that will hold the object-relational mapping
* metadata of the class with the given name.
*
* @param ReflectionService $reflService The reflection service.
*/
public function initializeReflection(ReflectionService $reflService): void
{
$this->reflClass = $reflService->getClass($this->name);
$this->namespace = $reflService->getClassNamespace($this->name);
if ($this->reflClass) {
$this->name = $this->rootEntityName = $this->reflClass->name;
}
$this->table['name'] = $this->namingStrategy->classToTableName($this->name);
}
/**
* Validates Identifier.
*
* @throws MappingException
*/
public function validateIdentifier(): void
{
if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
return;
}
// Verify & complete identifier mapping
if (! $this->identifier) {
throw MappingException::identifierRequired($this->name);
}
if ($this->usesIdGenerator() && $this->isIdentifierComposite) {
throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name);
}
}
/**
* Validates association targets actually exist.
*
* @throws MappingException
*/
public function validateAssociations(): void
{
foreach ($this->associationMappings as $mapping) {
if (
! class_exists($mapping->targetEntity)
&& ! interface_exists($mapping->targetEntity)
&& ! trait_exists($mapping->targetEntity)
) {
throw MappingException::invalidTargetEntityClass($mapping->targetEntity, $this->name, $mapping->fieldName);
}
}
}
/**
* Validates lifecycle callbacks.
*
* @throws MappingException
*/
public function validateLifecycleCallbacks(ReflectionService $reflService): void
{
foreach ($this->lifecycleCallbacks as $callbacks) {
foreach ($callbacks as $callbackFuncName) {
if (! $reflService->hasPublicMethod($this->name, $callbackFuncName)) {
throw MappingException::lifecycleCallbackMethodNotFound($this->name, $callbackFuncName);
}
}
}
}
/**
* {@inheritDoc}
*
* Can return null when using static reflection, in violation of the LSP
*/
public function getReflectionClass(): ReflectionClass|null
{
return $this->reflClass;
}
/** @psalm-param array{usage?: mixed, region?: mixed} $cache */
public function enableCache(array $cache): void
{
if (! isset($cache['usage'])) {
$cache['usage'] = self::CACHE_USAGE_READ_ONLY;
}
if (! isset($cache['region'])) {
$cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName));
}
$this->cache = $cache;
}
/** @psalm-param array{usage?: int, region?: string} $cache */
public function enableAssociationCache(string $fieldName, array $cache): void
{
$this->associationMappings[$fieldName]->cache = $this->getAssociationCacheDefaults($fieldName, $cache);
}
/**
* @psalm-param array{usage?: int, region?: string|null} $cache
*
* @return int[]|string[]
* @psalm-return array{usage: int, region: string|null}
*/
public function getAssociationCacheDefaults(string $fieldName, array $cache): array
{
if (! isset($cache['usage'])) {
$cache['usage'] = $this->cache['usage'] ?? self::CACHE_USAGE_READ_ONLY;
}
if (! isset($cache['region'])) {
$cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)) . '__' . $fieldName;
}
return $cache;
}
/**
* Sets the change tracking policy used by this class.
*/
public function setChangeTrackingPolicy(int $policy): void
{
$this->changeTrackingPolicy = $policy;
}
/**
* Whether the change tracking policy of this class is "deferred explicit".
*/
public function isChangeTrackingDeferredExplicit(): bool
{
return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT;
}
/**
* Whether the change tracking policy of this class is "deferred implicit".
*/
public function isChangeTrackingDeferredImplicit(): bool