-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
UnitOfWork.php
4084 lines (3428 loc) · 144 KB
/
UnitOfWork.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;
use BackedEnum;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
use Doctrine\DBAL\LockMode;
use Doctrine\Deprecations\Deprecation;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Event\ListenersInvoker;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreRemoveEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Exception\EntityIdentityCollisionException;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\Exception\UnexpectedAssociationValue;
use Doctrine\ORM\Id\AssignedGenerator;
use Doctrine\ORM\Internal\HydrationCompleteHandler;
use Doctrine\ORM\Internal\StronglyConnectedComponents;
use Doctrine\ORM\Internal\TopologicalSort;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
use Doctrine\ORM\Proxy\InternalProxy;
use Doctrine\ORM\Utility\IdentifierFlattener;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\ObjectManagerAware;
use Doctrine\Persistence\PropertyChangedListener;
use Exception;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
use UnexpectedValueException;
use function array_chunk;
use function array_combine;
use function array_diff_key;
use function array_filter;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_sum;
use function array_values;
use function assert;
use function current;
use function func_get_arg;
use function func_num_args;
use function get_class;
use function get_debug_type;
use function implode;
use function in_array;
use function is_array;
use function is_object;
use function method_exists;
use function reset;
use function spl_object_id;
use function sprintf;
use function strtolower;
/**
* The UnitOfWork is responsible for tracking changes to objects during an
* "object-level" transaction and for writing out changes to the database
* in the correct order.
*
* Internal note: This class contains highly performance-sensitive code.
*
* @psalm-import-type AssociationMapping from ClassMetadata
*/
class UnitOfWork implements PropertyChangedListener
{
/**
* An entity is in MANAGED state when its persistence is managed by an EntityManager.
*/
public const STATE_MANAGED = 1;
/**
* An entity is new if it has just been instantiated (i.e. using the "new" operator)
* and is not (yet) managed by an EntityManager.
*/
public const STATE_NEW = 2;
/**
* A detached entity is an instance with persistent state and identity that is not
* (or no longer) associated with an EntityManager (and a UnitOfWork).
*/
public const STATE_DETACHED = 3;
/**
* A removed entity instance is an instance with a persistent identity,
* associated with an EntityManager, whose persistent state will be deleted
* on commit.
*/
public const STATE_REMOVED = 4;
/**
* Hint used to collect all primary keys of associated entities during hydration
* and execute it in a dedicated query afterwards
*
* @see https://www.doctrine-project.org/projects/doctrine-orm/en/stable/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql
*/
public const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
/**
* The identity map that holds references to all managed entities that have
* an identity. The entities are grouped by their class name.
* Since all classes in a hierarchy must share the same identifier set,
* we always take the root class name of the hierarchy.
*
* @var mixed[]
* @psalm-var array<class-string, array<string, object>>
*/
private $identityMap = [];
/**
* Map of all identifiers of managed entities.
* Keys are object ids (spl_object_id).
*
* @var mixed[]
* @psalm-var array<int, array<string, mixed>>
*/
private $entityIdentifiers = [];
/**
* Map of the original entity data of managed entities.
* Keys are object ids (spl_object_id). This is used for calculating changesets
* at commit time.
*
* Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
* A value will only really be copied if the value in the entity is modified
* by the user.
*
* @psalm-var array<int, array<string, mixed>>
*/
private $originalEntityData = [];
/**
* Map of entity changes. Keys are object ids (spl_object_id).
* Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
*
* @psalm-var array<int, array<string, array{mixed, mixed}>>
*/
private $entityChangeSets = [];
/**
* The (cached) states of any known entities.
* Keys are object ids (spl_object_id).
*
* @psalm-var array<int, self::STATE_*>
*/
private $entityStates = [];
/**
* Map of entities that are scheduled for dirty checking at commit time.
* This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
* Keys are object ids (spl_object_id).
*
* @psalm-var array<class-string, array<int, mixed>>
*/
private $scheduledForSynchronization = [];
/**
* A list of all pending entity insertions.
*
* @psalm-var array<int, object>
*/
private $entityInsertions = [];
/**
* A list of all pending entity updates.
*
* @psalm-var array<int, object>
*/
private $entityUpdates = [];
/**
* Any pending extra updates that have been scheduled by persisters.
*
* @psalm-var array<int, array{object, array<string, array{mixed, mixed}>}>
*/
private $extraUpdates = [];
/**
* A list of all pending entity deletions.
*
* @psalm-var array<int, object>
*/
private $entityDeletions = [];
/**
* New entities that were discovered through relationships that were not
* marked as cascade-persist. During flush, this array is populated and
* then pruned of any entities that were discovered through a valid
* cascade-persist path. (Leftovers cause an error.)
*
* Keys are OIDs, payload is a two-item array describing the association
* and the entity.
*
* @var array<int, array{AssociationMapping, object}> indexed by respective object spl_object_id()
*/
private $nonCascadedNewDetectedEntities = [];
/**
* All pending collection deletions.
*
* @psalm-var array<int, PersistentCollection<array-key, object>>
*/
private $collectionDeletions = [];
/**
* All pending collection updates.
*
* @psalm-var array<int, PersistentCollection<array-key, object>>
*/
private $collectionUpdates = [];
/**
* List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
* At the end of the UnitOfWork all these collections will make new snapshots
* of their data.
*
* @psalm-var array<int, PersistentCollection<array-key, object>>
*/
private $visitedCollections = [];
/**
* List of collections visited during the changeset calculation that contain to-be-removed
* entities and need to have keys removed post commit.
*
* Indexed by Collection object ID, which also serves as the key in self::$visitedCollections;
* values are the key names that need to be removed.
*
* @psalm-var array<int, array<array-key, true>>
*/
private $pendingCollectionElementRemovals = [];
/**
* The EntityManager that "owns" this UnitOfWork instance.
*
* @var EntityManagerInterface
*/
private $em;
/**
* The entity persister instances used to persist entity instances.
*
* @psalm-var array<string, EntityPersister>
*/
private $persisters = [];
/**
* The collection persister instances used to persist collections.
*
* @psalm-var array<array-key, CollectionPersister>
*/
private $collectionPersisters = [];
/**
* The EventManager used for dispatching events.
*
* @var EventManager
*/
private $evm;
/**
* The ListenersInvoker used for dispatching events.
*
* @var ListenersInvoker
*/
private $listenersInvoker;
/**
* The IdentifierFlattener used for manipulating identifiers
*
* @var IdentifierFlattener
*/
private $identifierFlattener;
/**
* Orphaned entities that are scheduled for removal.
*
* @psalm-var array<int, object>
*/
private $orphanRemovals = [];
/**
* Read-Only objects are never evaluated
*
* @var array<int, true>
*/
private $readOnlyObjects = [];
/**
* Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
*
* @psalm-var array<class-string, array<string, mixed>>
*/
private $eagerLoadingEntities = [];
/** @var array<string, array<string, mixed>> */
private $eagerLoadingCollections = [];
/** @var bool */
protected $hasCache = false;
/**
* Helper for handling completion of hydration
*
* @var HydrationCompleteHandler
*/
private $hydrationCompleteHandler;
/** @var ReflectionPropertiesGetter */
private $reflectionPropertiesGetter;
/**
* Initializes a new UnitOfWork instance, bound to the given EntityManager.
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->evm = $em->getEventManager();
$this->listenersInvoker = new ListenersInvoker($em);
$this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
$this->identifierFlattener = new IdentifierFlattener($this, $em->getMetadataFactory());
$this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
$this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
}
/**
* Commits the UnitOfWork, executing all operations that have been postponed
* up to this point. The state of all managed entities will be synchronized with
* the database.
*
* The operations are executed in the following order:
*
* 1) All entity insertions
* 2) All entity updates
* 3) All collection deletions
* 4) All collection updates
* 5) All entity deletions
*
* @param object|mixed[]|null $entity
*
* @return void
*
* @throws Exception
*/
public function commit($entity = null)
{
if ($entity !== null) {
Deprecation::triggerIfCalledFromOutside(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8459',
'Calling %s() with any arguments to commit specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
__METHOD__
);
}
$connection = $this->em->getConnection();
if ($connection instanceof PrimaryReadReplicaConnection) {
$connection->ensureConnectedToPrimary();
}
// Raise preFlush
if ($this->evm->hasListeners(Events::preFlush)) {
$this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
}
// Compute changes done since last commit.
if ($entity === null) {
$this->computeChangeSets();
} elseif (is_object($entity)) {
$this->computeSingleEntityChangeSet($entity);
} elseif (is_array($entity)) {
foreach ($entity as $object) {
$this->computeSingleEntityChangeSet($object);
}
}
if (
! ($this->entityInsertions ||
$this->entityDeletions ||
$this->entityUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)
) {
$this->dispatchOnFlushEvent();
$this->dispatchPostFlushEvent();
$this->postCommitCleanup($entity);
return; // Nothing to do.
}
$this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $orphan) {
$this->remove($orphan);
}
}
$this->dispatchOnFlushEvent();
$conn = $this->em->getConnection();
$conn->beginTransaction();
try {
// Collection deletions (deletions of complete collections)
foreach ($this->collectionDeletions as $collectionToDelete) {
// Deferred explicit tracked collections can be removed only when owning relation was persisted
$owner = $collectionToDelete->getOwner();
if ($this->em->getClassMetadata(get_class($owner))->isChangeTrackingDeferredImplicit() || $this->isScheduledForDirtyCheck($owner)) {
$this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
}
}
if ($this->entityInsertions) {
// Perform entity insertions first, so that all new entities have their rows in the database
// and can be referred to by foreign keys. The commit order only needs to take new entities
// into account (new entities referring to other new entities), since all other types (entities
// with updates or scheduled deletions) are currently not a problem, since they are already
// in the database.
$this->executeInserts();
}
if ($this->entityUpdates) {
// Updates do not need to follow a particular order
$this->executeUpdates();
}
// Extra updates that were requested by persisters.
// This may include foreign keys that could not be set when an entity was inserted,
// which may happen in the case of circular foreign key relationships.
if ($this->extraUpdates) {
$this->executeExtraUpdates();
}
// Collection updates (deleteRows, updateRows, insertRows)
// No particular order is necessary, since all entities themselves are already
// in the database
foreach ($this->collectionUpdates as $collectionToUpdate) {
$this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
}
// Entity deletions come last. Their order only needs to take care of other deletions
// (first delete entities depending upon others, before deleting depended-upon entities).
if ($this->entityDeletions) {
$this->executeDeletions();
}
// Commit failed silently
if ($conn->commit() === false) {
$object = is_object($entity) ? $entity : null;
throw new OptimisticLockException('Commit failed', $object);
}
} catch (Throwable $e) {
$this->em->close();
if ($conn->isTransactionActive()) {
$conn->rollBack();
}
$this->afterTransactionRolledBack();
throw $e;
}
$this->afterTransactionComplete();
// Unset removed entities from collections, and take new snapshots from
// all visited collections.
foreach ($this->visitedCollections as $coid => $coll) {
if (isset($this->pendingCollectionElementRemovals[$coid])) {
foreach ($this->pendingCollectionElementRemovals[$coid] as $key => $valueIgnored) {
unset($coll[$key]);
}
}
$coll->takeSnapshot();
}
$this->dispatchPostFlushEvent();
$this->postCommitCleanup($entity);
}
/** @param object|object[]|null $entity */
private function postCommitCleanup($entity): void
{
$this->entityInsertions =
$this->entityUpdates =
$this->entityDeletions =
$this->extraUpdates =
$this->collectionUpdates =
$this->nonCascadedNewDetectedEntities =
$this->collectionDeletions =
$this->pendingCollectionElementRemovals =
$this->visitedCollections =
$this->orphanRemovals = [];
if ($entity === null) {
$this->entityChangeSets = $this->scheduledForSynchronization = [];
return;
}
$entities = is_object($entity)
? [$entity]
: $entity;
foreach ($entities as $object) {
$oid = spl_object_id($object);
$this->clearEntityChangeSet($oid);
unset($this->scheduledForSynchronization[$this->em->getClassMetadata(get_class($object))->rootEntityName][$oid]);
}
}
/**
* Computes the changesets of all entities scheduled for insertion.
*/
private function computeScheduleInsertsChangeSets(): void
{
foreach ($this->entityInsertions as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
$this->computeChangeSet($class, $entity);
}
}
/**
* Only flushes the given entity according to a ruleset that keeps the UoW consistent.
*
* 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
* 2. Read Only entities are skipped.
* 3. Proxies are skipped.
* 4. Only if entity is properly managed.
*
* @param object $entity
*
* @throws InvalidArgumentException
*/
private function computeSingleEntityChangeSet($entity): void
{
$state = $this->getEntityState($entity);
if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
throw new InvalidArgumentException('Entity has to be managed or scheduled for removal for single computation ' . self::objToStr($entity));
}
$class = $this->em->getClassMetadata(get_class($entity));
if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
$this->persist($entity);
}
// Compute changes for INSERTed entities first. This must always happen even in this case.
$this->computeScheduleInsertsChangeSets();
if ($class->isReadOnly) {
return;
}
// Ignore uninitialized proxy objects
if ($this->isUninitializedObject($entity)) {
return;
}
// Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
$oid = spl_object_id($entity);
if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
$this->computeChangeSet($class, $entity);
}
}
/**
* Executes any extra updates that have been scheduled.
*/
private function executeExtraUpdates(): void
{
foreach ($this->extraUpdates as $oid => $update) {
[$entity, $changeset] = $update;
$this->entityChangeSets[$oid] = $changeset;
$this->getEntityPersister(get_class($entity))->update($entity);
}
$this->extraUpdates = [];
}
/**
* Gets the changeset for an entity.
*
* @param object $entity
*
* @return mixed[][]
* @psalm-return array<string, array{mixed, mixed}|PersistentCollection>
*/
public function & getEntityChangeSet($entity)
{
$oid = spl_object_id($entity);
$data = [];
if (! isset($this->entityChangeSets[$oid])) {
return $data;
}
return $this->entityChangeSets[$oid];
}
/**
* Computes the changes that happened to a single entity.
*
* Modifies/populates the following properties:
*
* {@link _originalEntityData}
* If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
* then it was not fetched from the database and therefore we have no original
* entity data yet. All of the current entity data is stored as the original entity data.
*
* {@link _entityChangeSets}
* The changes detected on all properties of the entity are stored there.
* A change is a tuple array where the first entry is the old value and the second
* entry is the new value of the property. Changesets are used by persisters
* to INSERT/UPDATE the persistent entity state.
*
* {@link _entityUpdates}
* If the entity is already fully MANAGED (has been fetched from the database before)
* and any changes to its properties are detected, then a reference to the entity is stored
* there to mark it for an update.
*
* {@link _collectionDeletions}
* If a PersistentCollection has been de-referenced in a fully MANAGED entity,
* then this collection is marked for deletion.
*
* @param ClassMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to compute the changes.
* @psalm-param ClassMetadata<T> $class
* @psalm-param T $entity
*
* @return void
*
* @template T of object
*
* @ignore
*/
public function computeChangeSet(ClassMetadata $class, $entity)
{
$oid = spl_object_id($entity);
if (isset($this->readOnlyObjects[$oid])) {
return;
}
if (! $class->isInheritanceTypeNone()) {
$class = $this->em->getClassMetadata(get_class($entity));
}
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
}
$actualData = [];
foreach ($class->reflFields as $name => $refProp) {
$value = $refProp->getValue($entity);
if ($class->isCollectionValuedAssociation($name) && $value !== null) {
if ($value instanceof PersistentCollection) {
if ($value->getOwner() === $entity) {
$actualData[$name] = $value;
continue;
}
$value = new ArrayCollection($value->getValues());
}
// If $value is not a Collection then use an ArrayCollection.
if (! $value instanceof Collection) {
$value = new ArrayCollection($value);
}
$assoc = $class->associationMappings[$name];
// Inject PersistentCollection
$value = new PersistentCollection(
$this->em,
$this->em->getClassMetadata($assoc['targetEntity']),
$value
);
$value->setOwner($entity, $assoc);
$value->setDirty(! $value->isEmpty());
$refProp->setValue($entity, $value);
$actualData[$name] = $value;
continue;
}
if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
$actualData[$name] = $value;
}
}
if (! isset($this->originalEntityData[$oid])) {
// Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
// These result in an INSERT.
$this->originalEntityData[$oid] = $actualData;
$changeSet = [];
foreach ($actualData as $propName => $actualValue) {
if (! isset($class->associationMappings[$propName])) {
$changeSet[$propName] = [null, $actualValue];
continue;
}
$assoc = $class->associationMappings[$propName];
if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
$changeSet[$propName] = [null, $actualValue];
}
}
$this->entityChangeSets[$oid] = $changeSet;
} else {
// Entity is "fully" MANAGED: it was already fully persisted before
// and we have a copy of the original data
$originalData = $this->originalEntityData[$oid];
$isChangeTrackingNotify = $class->isChangeTrackingNotify();
$changeSet = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid])
? $this->entityChangeSets[$oid]
: [];
foreach ($actualData as $propName => $actualValue) {
// skip field, its a partially omitted one!
if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
continue;
}
$orgValue = $originalData[$propName];
if (! empty($class->fieldMappings[$propName]['enumType'])) {
if (is_array($orgValue)) {
foreach ($orgValue as $id => $val) {
if ($val instanceof BackedEnum) {
$orgValue[$id] = $val->value;
}
}
} else {
if ($orgValue instanceof BackedEnum) {
$orgValue = $orgValue->value;
}
}
}
// skip if value haven't changed
if ($orgValue === $actualValue) {
continue;
}
// if regular field
if (! isset($class->associationMappings[$propName])) {
if ($isChangeTrackingNotify) {
continue;
}
$changeSet[$propName] = [$orgValue, $actualValue];
continue;
}
$assoc = $class->associationMappings[$propName];
// Persistent collection was exchanged with the "originally"
// created one. This can only mean it was cloned and replaced
// on another entity.
if ($actualValue instanceof PersistentCollection) {
$owner = $actualValue->getOwner();
if ($owner === null) { // cloned
$actualValue->setOwner($entity, $assoc);
} elseif ($owner !== $entity) { // no clone, we have to fix
if (! $actualValue->isInitialized()) {
$actualValue->initialize(); // we have to do this otherwise the cols share state
}
$newValue = clone $actualValue;
$newValue->setOwner($entity, $assoc);
$class->reflFields[$propName]->setValue($entity, $newValue);
}
}
if ($orgValue instanceof PersistentCollection) {
// A PersistentCollection was de-referenced, so delete it.
$coid = spl_object_id($orgValue);
if (isset($this->collectionDeletions[$coid])) {
continue;
}
$this->collectionDeletions[$coid] = $orgValue;
$changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
continue;
}
if ($assoc['type'] & ClassMetadata::TO_ONE) {
if ($assoc['isOwningSide']) {
$changeSet[$propName] = [$orgValue, $actualValue];
}
if ($orgValue !== null && $assoc['orphanRemoval']) {
assert(is_object($orgValue));
$this->scheduleOrphanRemoval($orgValue);
}
}
}
if ($changeSet) {
$this->entityChangeSets[$oid] = $changeSet;
$this->originalEntityData[$oid] = $actualData;
$this->entityUpdates[$oid] = $entity;
}
}
// Look for changes in associations of the entity
foreach ($class->associationMappings as $field => $assoc) {
$val = $class->reflFields[$field]->getValue($entity);
if ($val === null) {
continue;
}
$this->computeAssociationChanges($assoc, $val);
if (
! isset($this->entityChangeSets[$oid]) &&
$assoc['isOwningSide'] &&
$assoc['type'] === ClassMetadata::MANY_TO_MANY &&
$val instanceof PersistentCollection &&
$val->isDirty()
) {
$this->entityChangeSets[$oid] = [];
$this->originalEntityData[$oid] = $actualData;
$this->entityUpdates[$oid] = $entity;
}
}
}
/**
* Computes all the changes that have been done to entities and collections
* since the last commit and stores these changes in the _entityChangeSet map
* temporarily for access by the persisters, until the UoW commit is finished.
*
* @return void
*/
public function computeChangeSets()
{
// Compute changes for INSERTed entities first. This must always happen.
$this->computeScheduleInsertsChangeSets();
// Compute changes for other MANAGED entities. Change tracking policies take effect here.
foreach ($this->identityMap as $className => $entities) {
$class = $this->em->getClassMetadata($className);
// Skip class if instances are read-only
if ($class->isReadOnly) {
continue;
}
// If change tracking is explicit or happens through notification, then only compute
// changes on entities of that type that are explicitly marked for synchronization.
switch (true) {
case $class->isChangeTrackingDeferredImplicit():
$entitiesToProcess = $entities;
break;
case isset($this->scheduledForSynchronization[$className]):
$entitiesToProcess = $this->scheduledForSynchronization[$className];
break;
default:
$entitiesToProcess = [];
}
foreach ($entitiesToProcess as $entity) {
// Ignore uninitialized proxy objects
if ($this->isUninitializedObject($entity)) {
continue;
}
// Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
$oid = spl_object_id($entity);
if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
$this->computeChangeSet($class, $entity);
}
}
}
}
/**
* Computes the changes of an association.
*
* @param mixed $value The value of the association.
* @psalm-param AssociationMapping $assoc The association mapping.
*
* @throws ORMInvalidArgumentException
* @throws ORMException
*/
private function computeAssociationChanges(array $assoc, $value): void
{
if ($this->isUninitializedObject($value)) {
return;
}
// If this collection is dirty, schedule it for updates
if ($value instanceof PersistentCollection && $value->isDirty()) {
$coid = spl_object_id($value);
$this->collectionUpdates[$coid] = $value;
$this->visitedCollections[$coid] = $value;
}
// Look through the entities, and in any of their associations,
// for transient (new) entities, recursively. ("Persistence by reachability")
// Unwrap. Uninitialized collections will simply be empty.
$unwrappedValue = $assoc['type'] & ClassMetadata::TO_ONE ? [$value] : $value->unwrap();
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
foreach ($unwrappedValue as $key => $entry) {
if (! ($entry instanceof $targetClass->name)) {
throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry);
}
$state = $this->getEntityState($entry, self::STATE_NEW);
if (! ($entry instanceof $assoc['targetEntity'])) {
throw UnexpectedAssociationValue::create(
$assoc['sourceEntity'],
$assoc['fieldName'],
get_debug_type($entry),
$assoc['targetEntity']
);
}
switch ($state) {
case self::STATE_NEW:
if (! $assoc['isCascadePersist']) {
/*
* For now just record the details, because this may
* not be an issue if we later discover another pathway
* through the object-graph where cascade-persistence
* is enabled for this object.
*/
$this->nonCascadedNewDetectedEntities[spl_object_id($entry)] = [$assoc, $entry];
break;
}
$this->persistNew($targetClass, $entry);
$this->computeChangeSet($targetClass, $entry);
break;
case self::STATE_REMOVED:
// Consume the $value as array (it's either an array or an ArrayAccess)
// and remove the element from Collection.
if (! ($assoc['type'] & ClassMetadata::TO_MANY)) {
break;
}