-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
UnitOfWork.php
2944 lines (2443 loc) · 99.9 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 Doctrine\Common\Collections\Collection;
use Doctrine\Common\EventManager;
use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\DBAL\LockMode;
use Doctrine\Instantiator\Instantiator;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\ListenersInvoker;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Exception\UnexpectedAssociationValue;
use Doctrine\ORM\Internal\HydrationCompleteHandler;
use Doctrine\ORM\Mapping\AssociationMetadata;
use Doctrine\ORM\Mapping\ChangeTrackingPolicy;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\EmbeddedMetadata;
use Doctrine\ORM\Mapping\FetchMode;
use Doctrine\ORM\Mapping\FieldMetadata;
use Doctrine\ORM\Mapping\GeneratorType;
use Doctrine\ORM\Mapping\InheritanceType;
use Doctrine\ORM\Mapping\JoinColumnMetadata;
use Doctrine\ORM\Mapping\ManyToManyAssociationMetadata;
use Doctrine\ORM\Mapping\OneToManyAssociationMetadata;
use Doctrine\ORM\Mapping\OneToOneAssociationMetadata;
use Doctrine\ORM\Mapping\ToManyAssociationMetadata;
use Doctrine\ORM\Mapping\ToOneAssociationMetadata;
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\Utility\NormalizeIdentifier;
use Exception;
use InvalidArgumentException;
use ProxyManager\Proxy\GhostObjectInterface;
use RuntimeException;
use SplFixedArray;
use Throwable;
use UnexpectedValueException;
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_pop;
use function array_reverse;
use function array_sum;
use function array_values;
use function current;
use function get_class;
use function implode;
use function in_array;
use function is_array;
use function is_object;
use function method_exists;
use function spl_object_id;
use function sprintf;
/**
* 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 This class contains highly performance-sensitive code. }}
*/
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://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#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 object[]
*/
private $identityMap = [];
/**
* Map of all identifiers of managed entities.
* This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_id).
* Values are maps of entity identifiers, where its key is the column name and the value is the raw value.
*
* @var mixed[][]
*/
private $entityIdentifiers = [];
/**
* Map of the original entity data of managed entities.
* This is a 2-dimensional data structure (map of maps). Keys are object ids (spl_object_id).
* Values are maps of entity data, where its key is the field name and the value is the converted
* (convertToPHPValue) value.
* This structure is used for calculating changesets at commit time.
*
* Internal: 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.
*
* @var 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.
*
* @var mixed[][]
*/
private $entityChangeSets = [];
/**
* The (cached) states of any known entities.
* Keys are object ids (spl_object_id).
*
* @var int[]
*/
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).
*
* @var object[][]
*/
private $scheduledForSynchronization = [];
/**
* A list of all pending entity insertions.
*
* @var object[]
*/
private $entityInsertions = [];
/**
* A list of all pending entity updates.
*
* @var object[]
*/
private $entityUpdates = [];
/**
* Any pending extra updates that have been scheduled by persisters.
*
* @var object[]
*/
private $extraUpdates = [];
/**
* A list of all pending entity deletions.
*
* @var 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 object[][]|array[][] indexed by respective object spl_object_id()
*/
private $nonCascadedNewDetectedEntities = [];
/**
* All pending collection deletions.
*
* @var Collection[]|object[][]
*/
private $collectionDeletions = [];
/**
* All pending collection updates.
*
* @var Collection[]|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.
*
* @var Collection[]|object[][]
*/
private $visitedCollections = [];
/**
* The EntityManager that "owns" this UnitOfWork instance.
*
* @var EntityManagerInterface
*/
private $em;
/**
* The entity persister instances used to persist entity instances.
*
* @var EntityPersister[]
*/
private $entityPersisters = [];
/**
* The collection persister instances used to persist collections.
*
* @var CollectionPersister[]
*/
private $collectionPersisters = [];
/**
* The EventManager used for dispatching events.
*
* @var EventManager
*/
private $eventManager;
/**
* The ListenersInvoker used for dispatching events.
*
* @var ListenersInvoker
*/
private $listenersInvoker;
/** @var Instantiator */
private $instantiator;
/**
* Orphaned entities that are scheduled for removal.
*
* @var object[]
*/
private $orphanRemovals = [];
/**
* Read-Only objects are never evaluated
*
* @var object[]
*/
private $readOnlyObjects = [];
/**
* Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
*
* @var mixed[][][]
*/
private $eagerLoadingEntities = [];
/** @var bool */
protected $hasCache = false;
/**
* Helper for handling completion of hydration
*
* @var HydrationCompleteHandler
*/
private $hydrationCompleteHandler;
/** @var NormalizeIdentifier */
private $normalizeIdentifier;
/**
* Initializes a new UnitOfWork instance, bound to the given EntityManager.
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->eventManager = $em->getEventManager();
$this->listenersInvoker = new ListenersInvoker($em);
$this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
$this->instantiator = new Instantiator();
$this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
$this->normalizeIdentifier = new NormalizeIdentifier();
}
/**
* 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
*
* @throws Exception
*/
public function commit()
{
// Raise preFlush
if ($this->eventManager->hasListeners(Events::preFlush)) {
$this->eventManager->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
}
$this->computeChangeSets();
if (! ($this->entityInsertions ||
$this->entityDeletions ||
$this->entityUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)) {
$this->dispatchOnFlushEvent();
$this->dispatchPostFlushEvent();
$this->postCommitCleanup();
return; // Nothing to do.
}
$this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $orphan) {
$this->remove($orphan);
}
}
$this->dispatchOnFlushEvent();
// Now we need a commit order to maintain referential integrity
$commitOrder = $this->getCommitOrder();
$conn = $this->em->getConnection();
$conn->beginTransaction();
try {
// Collection deletions (deletions of complete collections)
foreach ($this->collectionDeletions as $collectionToDelete) {
$this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
}
if ($this->entityInsertions) {
foreach ($commitOrder as $class) {
$this->executeInserts($class);
}
}
if ($this->entityUpdates) {
foreach ($commitOrder as $class) {
$this->executeUpdates($class);
}
}
// Extra updates that were requested by persisters.
if ($this->extraUpdates) {
$this->executeExtraUpdates();
}
// Collection updates (deleteRows, updateRows, insertRows)
foreach ($this->collectionUpdates as $collectionToUpdate) {
$this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
}
// Entity deletions come last and need to be in reverse commit order
if ($this->entityDeletions) {
foreach (array_reverse($commitOrder) as $committedEntityName) {
if (! $this->entityDeletions) {
break; // just a performance optimisation
}
$this->executeDeletions($committedEntityName);
}
}
$conn->commit();
} catch (Throwable $e) {
$this->em->close();
$conn->rollBack();
$this->afterTransactionRolledBack();
throw $e;
}
$this->afterTransactionComplete();
// Take new snapshots from visited collections
foreach ($this->visitedCollections as $coll) {
$coll->takeSnapshot();
}
$this->dispatchPostFlushEvent();
$this->postCommitCleanup();
}
private function postCommitCleanup() : void
{
$this->entityInsertions =
$this->entityUpdates =
$this->entityDeletions =
$this->extraUpdates =
$this->entityChangeSets =
$this->collectionUpdates =
$this->collectionDeletions =
$this->visitedCollections =
$this->scheduledForSynchronization =
$this->orphanRemovals = [];
}
/**
* Computes the changesets of all entities scheduled for insertion.
*/
private function computeScheduleInsertsChangeSets()
{
foreach ($this->entityInsertions as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
$this->computeChangeSet($class, $entity);
}
}
/**
* Executes any extra updates that have been scheduled.
*/
private function executeExtraUpdates()
{
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[]
*/
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.
*
* @internal Don't call from the outside.
*
* @param ClassMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to compute the changes.
*
* @ignore
*/
public function computeChangeSet(ClassMetadata $class, $entity)
{
$oid = spl_object_id($entity);
if (isset($this->readOnlyObjects[$oid])) {
return;
}
if ($class->inheritanceType !== InheritanceType::NONE) {
$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->getPropertiesIterator() as $name => $property) {
$value = $property->getValue($entity);
if ($property instanceof ToManyAssociationMetadata && $value !== null) {
if ($value instanceof PersistentCollection && $value->getOwner() === $entity) {
continue;
}
$value = $property->wrap($entity, $value, $this->em);
$property->setValue($entity, $value);
$actualData[$name] = $value;
continue;
}
if (( ! $class->isIdentifier($name)
|| ! $class->getProperty($name) instanceof FieldMetadata
|| ! $class->getProperty($name)->hasValueGenerator()
|| $class->getProperty($name)->getValueGenerator()->getType() !== GeneratorType::IDENTITY
) && (! $class->isVersioned() || $name !== $class->versionProperty->getName())) {
$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) {
$property = $class->getProperty($propName);
if ($property instanceof FieldMetadata ||
$property instanceof EmbeddedMetadata ||
($property instanceof ToOneAssociationMetadata && $property->isOwningSide())) {
$change = new SplFixedArray(2);
$change[0] = null;
$change[1] = $actualValue;
$changeSet[$propName] = $change;
}
}
$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->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY;
$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];
// skip if value haven't changed
if ($orgValue === $actualValue) {
continue;
}
$property = $class->getProperty($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, $property);
} 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, $property);
$property->setValue($entity, $newValue);
}
}
switch (true) {
case $property instanceof FieldMetadata:
if ($isChangeTrackingNotify) {
// Continue inside switch behaves as break.
// We are required to use continue 2, since we need to continue to next $actualData item
continue 2;
}
$change = new SplFixedArray(2);
$change[0] = $orgValue;
$change[1] = $actualValue;
$changeSet[$propName] = $change;
break;
case $property instanceof ToOneAssociationMetadata:
if ($property->isOwningSide()) {
$change = new SplFixedArray(2);
$change[0] = $orgValue;
$change[1] = $actualValue;
$changeSet[$propName] = $change;
}
if ($orgValue !== null && $property->isOrphanRemoval()) {
$this->scheduleOrphanRemoval($orgValue);
}
break;
case $property instanceof ToManyAssociationMetadata:
// Check if original value exists
if ($orgValue instanceof PersistentCollection) {
// A PersistentCollection was de-referenced, so delete it.
if (! $this->isCollectionScheduledForDeletion($orgValue)) {
$this->scheduleCollectionDeletion($orgValue);
// Signal changeset, to-many associations will be ignored
$change = new SplFixedArray(2);
$change[0] = $orgValue;
$change[1] = $actualValue;
$changeSet[$propName] = $change;
}
}
break;
default:
// Do nothing
}
}
if ($changeSet) {
$this->entityChangeSets[$oid] = $changeSet;
$this->originalEntityData[$oid] = $actualData;
$this->entityUpdates[$oid] = $entity;
}
}
// Look for changes in associations of the entity
foreach ($class->getPropertiesIterator() as $property) {
if (! $property instanceof AssociationMetadata) {
continue;
}
$value = $property->getValue($entity);
if ($value === null) {
continue;
}
$this->computeAssociationChanges($property, $value);
if ($property instanceof ManyToManyAssociationMetadata &&
$value instanceof PersistentCollection &&
! isset($this->entityChangeSets[$oid]) &&
$property->isOwningSide() &&
$value->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.
*/
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->changeTrackingPolicy === ChangeTrackingPolicy::DEFERRED_IMPLICIT:
$entitiesToProcess = $entities;
break;
case isset($this->scheduledForSynchronization[$className]):
$entitiesToProcess = $this->scheduledForSynchronization[$className];
break;
default:
$entitiesToProcess = [];
}
foreach ($entitiesToProcess as $entity) {
// Ignore uninitialized proxy objects
if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
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 AssociationMetadata $association The association mapping.
* @param mixed $value The value of the association.
*
* @throws ORMInvalidArgumentException
* @throws ORMException
*/
private function computeAssociationChanges(AssociationMetadata $association, $value)
{
if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
return;
}
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 = $association instanceof ToOneAssociationMetadata ? [$value] : $value->unwrap();
$targetEntity = $association->getTargetEntity();
$targetClass = $this->em->getClassMetadata($targetEntity);
foreach ($unwrappedValue as $key => $entry) {
if (! ($entry instanceof $targetEntity)) {
throw ORMInvalidArgumentException::invalidAssociation($targetClass, $association, $entry);
}
$state = $this->getEntityState($entry, self::STATE_NEW);
if (! ($entry instanceof $targetEntity)) {
throw UnexpectedAssociationValue::create(
$association->getSourceEntity(),
$association->getName(),
get_class($entry),
$targetEntity
);
}
switch ($state) {
case self::STATE_NEW:
if (! in_array('persist', $association->getCascade(), true)) {
$this->nonCascadedNewDetectedEntities[spl_object_id($entry)] = [$association, $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 ($association instanceof ToManyAssociationMetadata) {
unset($value[$key]);
}
break;
case self::STATE_DETACHED:
// Can actually not happen right now as we assume STATE_NEW,
// so the exception will be raised from the DBAL layer (constraint violation).
throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($association, $entry);
break;
default:
// MANAGED associated entities are already taken into account
// during changeset calculation anyway, since they are in the identity map.
}
}
}
/**
* @param ClassMetadata $class
* @param object $entity
*/
private function persistNew($class, $entity)
{
$oid = spl_object_id($entity);
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
}
$generationPlan = $class->getValueGenerationPlan();
$persister = $this->getEntityPersister($class->getClassName());
$generationPlan->executeImmediate($this->em, $entity);
if (! $generationPlan->containsDeferred()) {
$id = $this->em->getIdentifierFlattener()->flattenIdentifier($class, $persister->getIdentifier($entity));
// Some identifiers may be foreign keys to new entities.
// In this case, we don't have the value yet and should treat it as if we have a post-insert generator
if (! $this->hasMissingIdsWhichAreForeignKeys($class, $id)) {
$this->entityIdentifiers[$oid] = $id;
}
}
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->scheduleForInsert($entity);
}
/**
* @param mixed[] $idValue
*/
private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool
{
foreach ($idValue as $idField => $idFieldValue) {
if ($idFieldValue === null && $class->getProperty($idField) instanceof AssociationMetadata) {
return true;
}
}
return false;
}
/**
* INTERNAL:
* Computes the changeset of an individual entity, independently of the
* computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
*
* The passed entity must be a managed entity. If the entity already has a change set
* because this method is invoked during a commit cycle then the change sets are added.
* whereby changes detected in this method prevail.
*
* @param ClassMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to (re)calculate the change set.
*
* @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
* @throws RuntimeException
*
* @ignore
*/
public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) : void
{
$oid = spl_object_id($entity);
if (! isset($this->entityStates[$oid]) || $this->entityStates[$oid] !== self::STATE_MANAGED) {
throw ORMInvalidArgumentException::entityNotManaged($entity);
}
// skip if change tracking is "NOTIFY"
if ($class->changeTrackingPolicy === ChangeTrackingPolicy::NOTIFY) {
return;
}
if ($class->inheritanceType !== InheritanceType::NONE) {
$class = $this->em->getClassMetadata(get_class($entity));
}
$actualData = [];
foreach ($class->getPropertiesIterator() as $name => $property) {
switch (true) {
case $property instanceof FieldMetadata:
// Ignore version field
if ($property->isVersioned()) {
break;
}
if (! $property->isPrimaryKey()
|| ! $property->getValueGenerator()
|| $property->getValueGenerator()->getType() !== GeneratorType::IDENTITY) {
$actualData[$name] = $property->getValue($entity);
}
break;
case $property instanceof ToOneAssociationMetadata:
$actualData[$name] = $property->getValue($entity);
break;
}
}
if (! isset($this->originalEntityData[$oid])) {
throw new RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
}
$originalData = $this->originalEntityData[$oid];
$changeSet = [];
foreach ($actualData as $propName => $actualValue) {
$orgValue = $originalData[$propName] ?? null;
if ($orgValue !== $actualValue) {
$changeSet[$propName] = [$orgValue, $actualValue];
}
}
if ($changeSet) {
if (isset($this->entityChangeSets[$oid])) {
$this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
} elseif (! isset($this->entityInsertions[$oid])) {
$this->entityChangeSets[$oid] = $changeSet;
$this->entityUpdates[$oid] = $entity;
}
$this->originalEntityData[$oid] = $actualData;
}
}
/**
* Executes all entity insertions for entities of the specified type.
*/
private function executeInserts(ClassMetadata $class) : void
{
$className = $class->getClassName();
$persister = $this->getEntityPersister($className);
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
$generationPlan = $class->getValueGenerationPlan();
foreach ($this->entityInsertions as $oid => $entity) {
if ($this->em->getClassMetadata(get_class($entity))->getClassName() !== $className) {