-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathUnitOfWork.php
3126 lines (2680 loc) · 110 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\ODM\MongoDB;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\EventManager;
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\Mapping\MappingException;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionException;
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionInterface;
use Doctrine\ODM\MongoDB\Persisters\CollectionPersister;
use Doctrine\ODM\MongoDB\Persisters\PersistenceBuilder;
use Doctrine\ODM\MongoDB\Query\Query;
use Doctrine\ODM\MongoDB\Types\DateType;
use Doctrine\ODM\MongoDB\Types\Type;
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
use Doctrine\ODM\MongoDB\Utility\LifecycleEventManager;
use Doctrine\Persistence\Mapping\ReflectionService;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\PropertyChangedListener;
use InvalidArgumentException;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Driver\WriteConcern;
use ProxyManager\Proxy\GhostObjectInterface;
use ReflectionProperty;
use UnexpectedValueException;
use function array_filter;
use function array_key_exists;
use function assert;
use function count;
use function get_class;
use function in_array;
use function is_array;
use function is_object;
use function method_exists;
use function preg_match;
use function serialize;
use function spl_object_hash;
use function sprintf;
use function trigger_deprecation;
/**
* 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.
*
* @psalm-import-type FieldMapping from ClassMetadata
* @psalm-import-type AssociationFieldMapping from ClassMetadata
* @psalm-type ChangeSet = array{
* 0: mixed,
* 1: mixed
* }
* @psalm-type Hints = array<int, mixed>
* @psalm-type CommitOptions array{
* fsync?: bool,
* safe?: int,
* w?: int,
* writeConcern?: WriteConcern
* }
*/
final class UnitOfWork implements PropertyChangedListener
{
/**
* A document is in MANAGED state when its persistence is managed by a DocumentManager.
*/
public const STATE_MANAGED = 1;
/**
* A document is new if it has just been instantiated (i.e. using the "new" operator)
* and is not (yet) managed by a DocumentManager.
*/
public const STATE_NEW = 2;
/**
* A detached document is an instance with a persistent identity that is not
* (or no longer) associated with a DocumentManager (and a UnitOfWork).
*/
public const STATE_DETACHED = 3;
/**
* A removed document instance is an instance with a persistent identity,
* associated with a DocumentManager, whose persistent state has been
* deleted (or is scheduled for deletion).
*/
public const STATE_REMOVED = 4;
/** @internal */
public const DEPRECATED_WRITE_OPTIONS = ['fsync', 'safe', 'w'];
/**
* The identity map holds references to all managed documents.
*
* Documents are grouped by their class name, and then indexed by the
* serialized string of their database identifier field or, if the class
* has no identifier, the SPL object hash. Serializing the identifier allows
* differentiation of values that may be equal (via type juggling) but not
* identical.
*
* Since all classes in a hierarchy must share the same identifier set,
* we always take the root class name of the hierarchy.
*
* @psalm-var array<class-string, array<string, object>>
*/
private array $identityMap = [];
/**
* Map of all identifiers of managed documents.
* Keys are object ids (spl_object_hash).
*
* @var array<string, mixed>
*/
private array $documentIdentifiers = [];
/**
* Map of the original document data of managed documents.
* Keys are object ids (spl_object_hash). This 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 document is modified
* by the user.
*
* @var array<string, array<string, mixed>>
*/
private array $originalDocumentData = [];
/**
* Map of document changes. Keys are object ids (spl_object_hash).
* Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
*
* @psalm-var array<string, array<string, ChangeSet>>
*/
private array $documentChangeSets = [];
/**
* The (cached) states of any known documents.
* Keys are object ids (spl_object_hash).
*
* @psalm-var array<string, self::STATE_*>
*/
private array $documentStates = [];
/**
* Map of documents that are scheduled for dirty checking at commit time.
*
* Documents are grouped by their class name, and then indexed by their SPL
* object hash. This is only used for documents with a change tracking
* policy of DEFERRED_EXPLICIT.
*
* @psalm-var array<class-string, array<string, object>>
*/
private array $scheduledForSynchronization = [];
/**
* A list of all pending document insertions.
*
* @var array<string, object>
*/
private array $documentInsertions = [];
/**
* A list of all pending document updates.
*
* @var array<string, object>
*/
private array $documentUpdates = [];
/**
* A list of all pending document upserts.
*
* @var array<string, object>
*/
private array $documentUpserts = [];
/**
* A list of all pending document deletions.
*
* @var array<string, object>
*/
private array $documentDeletions = [];
/**
* All pending collection deletions.
*
* @psalm-var array<string, PersistentCollectionInterface<array-key, object>>
*/
private array $collectionDeletions = [];
/**
* All pending collection updates.
*
* @psalm-var array<string, PersistentCollectionInterface<array-key, object>>
*/
private array $collectionUpdates = [];
/**
* A list of documents related to collections scheduled for update or deletion
*
* @psalm-var array<string, array<string, PersistentCollectionInterface<array-key, object>>>
*/
private array $hasScheduledCollections = [];
/**
* 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<string, array<PersistentCollectionInterface<array-key, object>>>
*/
private array $visitedCollections = [];
/**
* The DocumentManager that "owns" this UnitOfWork instance.
*/
private DocumentManager $dm;
/**
* The EventManager used for dispatching events.
*/
private EventManager $evm;
/**
* Additional documents that are scheduled for removal.
*
* @var array<string, object>
*/
private array $orphanRemovals = [];
/**
* The HydratorFactory used for hydrating array Mongo documents to Doctrine object documents.
*/
private HydratorFactory $hydratorFactory;
/**
* The document persister instances used to persist document instances.
*
* @psalm-var array<class-string, Persisters\DocumentPersister>
*/
private array $persisters = [];
/**
* The collection persister instance used to persist changes to collections.
*/
private ?CollectionPersister $collectionPersister = null;
/**
* The persistence builder instance used in DocumentPersisters.
*/
private ?PersistenceBuilder $persistenceBuilder = null;
/**
* Array of parent associations between embedded documents.
*
* @psalm-var array<string, array{0: AssociationFieldMapping, 1: object|null, 2: string}>
*/
private array $parentAssociations = [];
private LifecycleEventManager $lifecycleEventManager;
private ReflectionService $reflectionService;
/**
* Array of embedded documents known to UnitOfWork. We need to hold them to prevent spl_object_hash
* collisions in case already managed object is lost due to GC (so now it won't). Embedded documents
* found during doDetach are removed from the registry, to empty it altogether clear() can be utilized.
*
* @var array<string, object>
*/
private array $embeddedDocumentsRegistry = [];
private int $commitsInProgress = 0;
/**
* Initializes a new UnitOfWork instance, bound to the given DocumentManager.
*/
public function __construct(DocumentManager $dm, EventManager $evm, HydratorFactory $hydratorFactory)
{
$this->dm = $dm;
$this->evm = $evm;
$this->hydratorFactory = $hydratorFactory;
$this->lifecycleEventManager = new LifecycleEventManager($dm, $this, $evm);
$this->reflectionService = new RuntimeReflectionService();
}
/**
* Factory for returning new PersistenceBuilder instances used for preparing data into
* queries for insert persistence.
*
* @internal
*/
public function getPersistenceBuilder(): PersistenceBuilder
{
if (! $this->persistenceBuilder) {
$this->persistenceBuilder = new PersistenceBuilder($this->dm, $this);
}
return $this->persistenceBuilder;
}
/**
* Sets the parent association for a given embedded document.
*
* @internal
*
* @psalm-param FieldMapping $mapping
*/
public function setParentAssociation(object $document, array $mapping, ?object $parent, string $propertyPath): void
{
$oid = spl_object_hash($document);
$this->embeddedDocumentsRegistry[$oid] = $document;
$this->parentAssociations[$oid] = [$mapping, $parent, $propertyPath];
}
/**
* Gets the parent association for a given embedded document.
*
* <code>
* list($mapping, $parent, $propertyPath) = $this->getParentAssociation($embeddedDocument);
* </code>
*
* @psalm-return array{0: AssociationFieldMapping, 1: object|null, 2: string}|null
*/
public function getParentAssociation(object $document): ?array
{
$oid = spl_object_hash($document);
return $this->parentAssociations[$oid] ?? null;
}
/**
* Get the document persister instance for the given document name
*
* @psalm-param class-string<T> $documentName
*
* @psalm-return Persisters\DocumentPersister<T>
*
* @template T of object
*/
public function getDocumentPersister(string $documentName): Persisters\DocumentPersister
{
if (! isset($this->persisters[$documentName])) {
$class = $this->dm->getClassMetadata($documentName);
$pb = $this->getPersistenceBuilder();
$this->persisters[$documentName] = new Persisters\DocumentPersister($pb, $this->dm, $this, $this->hydratorFactory, $class);
}
/** @psalm-var Persisters\DocumentPersister<T> */
return $this->persisters[$documentName];
}
/**
* Get the collection persister instance.
*/
public function getCollectionPersister(): CollectionPersister
{
if (! isset($this->collectionPersister)) {
$pb = $this->getPersistenceBuilder();
$this->collectionPersister = new Persisters\CollectionPersister($this->dm, $pb, $this);
}
return $this->collectionPersister;
}
/**
* Set the document persister instance to use for the given document name
*
* @internal
*
* @psalm-param class-string<T> $documentName
* @psalm-param Persisters\DocumentPersister<T> $persister
*
* @template T of object
*/
public function setDocumentPersister(string $documentName, Persisters\DocumentPersister $persister): void
{
$this->persisters[$documentName] = $persister;
}
/**
* Commits the UnitOfWork, executing all operations that have been postponed
* up to this point. The state of all managed documents will be synchronized with
* the database.
*
* The operations are executed in the following order:
*
* 1) All document insertions
* 2) All document updates
* 3) All document deletions
*
* @param array $options Array of options to be used with batchInsert(), update() and remove()
* @psalm-param CommitOptions $options
*/
public function commit(array $options = []): void
{
foreach (self::DEPRECATED_WRITE_OPTIONS as $deprecatedOption) {
if (! array_key_exists($deprecatedOption, $options)) {
continue;
}
trigger_deprecation(
'doctrine/mongodb-odm',
'2.6',
'The "%s" commit option is deprecated.',
$deprecatedOption,
);
}
// Raise preFlush
$this->evm->dispatchEvent(Events::preFlush, new Event\PreFlushEventArgs($this->dm));
// Compute changes done since last commit.
$this->computeChangeSets();
if (
! ($this->documentInsertions ||
$this->documentUpserts ||
$this->documentDeletions ||
$this->documentUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)
) {
return; // Nothing to do.
}
$this->commitsInProgress++;
if ($this->commitsInProgress > 1) {
throw MongoDBException::commitInProgress();
}
try {
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $removal) {
$this->remove($removal);
}
}
// Raise onFlush
$this->evm->dispatchEvent(Events::onFlush, new Event\OnFlushEventArgs($this->dm));
foreach ($this->getClassesForCommitAction($this->documentUpserts) as $classAndDocuments) {
[$class, $documents] = $classAndDocuments;
$this->executeUpserts($class, $documents, $options);
}
foreach ($this->getClassesForCommitAction($this->documentInsertions) as $classAndDocuments) {
[$class, $documents] = $classAndDocuments;
$this->executeInserts($class, $documents, $options);
}
foreach ($this->getClassesForCommitAction($this->documentUpdates) as $classAndDocuments) {
[$class, $documents] = $classAndDocuments;
$this->executeUpdates($class, $documents, $options);
}
foreach ($this->getClassesForCommitAction($this->documentDeletions, true) as $classAndDocuments) {
[$class, $documents] = $classAndDocuments;
$this->executeDeletions($class, $documents, $options);
}
// Raise postFlush
$this->evm->dispatchEvent(Events::postFlush, new Event\PostFlushEventArgs($this->dm));
// Clear up
$this->documentInsertions =
$this->documentUpserts =
$this->documentUpdates =
$this->documentDeletions =
$this->documentChangeSets =
$this->collectionUpdates =
$this->collectionDeletions =
$this->visitedCollections =
$this->scheduledForSynchronization =
$this->orphanRemovals =
$this->hasScheduledCollections = [];
} finally {
$this->commitsInProgress--;
}
}
/**
* Groups a list of scheduled documents by their class.
*
* @param array<string, object> $documents
*
* @psalm-return array<class-string, array{0: ClassMetadata<object>, 1: array<string, object>}>
*/
private function getClassesForCommitAction(array $documents, bool $includeEmbedded = false): array
{
if (empty($documents)) {
return [];
}
$divided = [];
$embeds = [];
foreach ($documents as $oid => $d) {
$className = $d::class;
if (isset($embeds[$className])) {
continue;
}
if (isset($divided[$className])) {
$divided[$className][1][$oid] = $d;
continue;
}
$class = $this->dm->getClassMetadata($className);
if ($class->isEmbeddedDocument && ! $includeEmbedded) {
$embeds[$className] = true;
continue;
}
if ($class->isView()) {
continue;
}
if (empty($divided[$class->name])) {
$divided[$class->name] = [$class, [$oid => $d]];
} else {
$divided[$class->name][1][$oid] = $d;
}
}
return $divided;
}
/**
* Compute changesets of all documents scheduled for insertion.
*
* Embedded documents will not be processed.
*/
private function computeScheduleInsertsChangeSets(): void
{
foreach ($this->documentInsertions as $document) {
$class = $this->dm->getClassMetadata($document::class);
if ($class->isEmbeddedDocument || $class->isView()) {
continue;
}
$this->computeChangeSet($class, $document);
}
}
/**
* Compute changesets of all documents scheduled for upsert.
*
* Embedded documents will not be processed.
*/
private function computeScheduleUpsertsChangeSets(): void
{
foreach ($this->documentUpserts as $document) {
$class = $this->dm->getClassMetadata($document::class);
if ($class->isEmbeddedDocument || $class->isView()) {
continue;
}
$this->computeChangeSet($class, $document);
}
}
/**
* Gets the changeset for a document.
*
* @return array array('property' => array(0 => mixed, 1 => mixed))
* @psalm-return array<string, ChangeSet>
*/
public function getDocumentChangeSet(object $document): array
{
$oid = spl_object_hash($document);
return $this->documentChangeSets[$oid] ?? [];
}
/**
* Sets the changeset for a document.
*
* @internal
*
* @psalm-param array<string, ChangeSet> $changeset
*/
public function setDocumentChangeSet(object $document, array $changeset): void
{
$this->documentChangeSets[spl_object_hash($document)] = $changeset;
}
/**
* Get a documents actual data, flattening all the objects to arrays.
*
* @internal
*
* @return array<string, mixed>
*/
public function getDocumentActualData(object $document): array
{
$class = $this->dm->getClassMetadata($document::class);
$actualData = [];
foreach ($class->reflFields as $name => $refProp) {
$mapping = $class->fieldMappings[$name];
// skip not saved fields
if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) {
continue;
}
$value = $refProp->getValue($document);
if (
(isset($mapping['association']) && $mapping['type'] === ClassMetadata::MANY)
&& $value !== null && ! ($value instanceof PersistentCollectionInterface)
) {
// If $actualData[$name] is not a Collection then use an ArrayCollection.
if (! $value instanceof Collection) {
$value = new ArrayCollection($value);
}
// Inject PersistentCollection
$coll = $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm, $mapping, $value);
$coll->setOwner($document, $mapping);
$coll->setDirty(! $value->isEmpty());
$class->reflFields[$name]->setValue($document, $coll);
$actualData[$name] = $coll;
} else {
$actualData[$name] = $value;
}
}
return $actualData;
}
/**
* Computes the changes that happened to a single document.
*
* Modifies/populates the following properties:
*
* {@link originalDocumentData}
* If the document 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
* document data yet. All of the current document data is stored as the original document data.
*
* {@link documentChangeSets}
* The changes detected on all properties of the document 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 document state.
*
* {@link documentUpdates}
* If the document is already fully MANAGED (has been fetched from the database before)
* and any changes to its properties are detected, then a reference to the document is stored
* there to mark it for an update.
*
* @psalm-param ClassMetadata<T> $class
* @psalm-param T $document
*
* @template T of object
*/
public function computeChangeSet(ClassMetadata $class, object $document): void
{
if (! $class->isInheritanceTypeNone()) {
$class = $this->dm->getClassMetadata($document::class);
}
// Fire PreFlush lifecycle callbacks
if (! empty($class->lifecycleCallbacks[Events::preFlush])) {
$class->invokeLifecycleCallbacks(Events::preFlush, $document, [new Event\PreFlushEventArgs($this->dm)]);
}
$this->computeOrRecomputeChangeSet($class, $document);
}
/**
* Used to do the common work of computeChangeSet and recomputeSingleDocumentChangeSet
*
* @psalm-param ClassMetadata<T> $class
* @psalm-param T $document
*
* @template T of object
*/
private function computeOrRecomputeChangeSet(ClassMetadata $class, object $document, bool $recompute = false): void
{
if ($class->isView()) {
return;
}
$oid = spl_object_hash($document);
$actualData = $this->getDocumentActualData($document);
$isNewDocument = ! isset($this->originalDocumentData[$oid]);
if ($isNewDocument) {
// Document is either NEW or MANAGED but not yet fully persisted (only has an id).
// These result in an INSERT.
$this->originalDocumentData[$oid] = $actualData;
$changeSet = [];
foreach ($actualData as $propName => $actualValue) {
/* At this PersistentCollection shouldn't be here, probably it
* was cloned and its ownership must be fixed
*/
if ($actualValue instanceof PersistentCollectionInterface && $actualValue->getOwner() !== $document) {
$actualData[$propName] = $this->fixPersistentCollectionOwnership($actualValue, $document, $class, $propName);
$actualValue = $actualData[$propName];
}
// ignore inverse side of reference relationship
if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['isInverseSide']) {
continue;
}
$changeSet[$propName] = [null, $actualValue];
}
$this->documentChangeSets[$oid] = $changeSet;
} else {
if ($class->isReadOnly) {
return;
}
// Document is "fully" MANAGED: it was already fully persisted before
// and we have a copy of the original data
$originalData = $this->originalDocumentData[$oid];
$isChangeTrackingNotify = $class->isChangeTrackingNotify();
if ($isChangeTrackingNotify && ! $recompute && isset($this->documentChangeSets[$oid])) {
$changeSet = $this->documentChangeSets[$oid];
} else {
$changeSet = [];
}
$gridFSMetadataProperty = null;
if ($class->isFile) {
try {
$gridFSMetadata = $class->getFieldMappingByDbFieldName('metadata');
$gridFSMetadataProperty = $gridFSMetadata['fieldName'];
} catch (MappingException) {
}
}
foreach ($actualData as $propName => $actualValue) {
// skip not saved fields
if (
(isset($class->fieldMappings[$propName]['notSaved']) && $class->fieldMappings[$propName]['notSaved'] === true) ||
($class->isFile && $propName !== $gridFSMetadataProperty)
) {
continue;
}
$orgValue = $originalData[$propName] ?? null;
// skip if value has not changed
if ($orgValue === $actualValue) {
if (! $actualValue instanceof PersistentCollectionInterface) {
continue;
}
if (! $actualValue->isDirty() && ! $this->isCollectionScheduledForDeletion($actualValue)) {
// consider dirty collections as changed as well
continue;
}
}
// if relationship is a embed-one, schedule orphan removal to trigger cascade remove operations
if (isset($class->fieldMappings[$propName]['embedded']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::ONE) {
if ($orgValue !== null) {
$this->scheduleOrphanRemoval($orgValue);
}
$changeSet[$propName] = [$orgValue, $actualValue];
continue;
}
// if owning side of reference-one relationship
if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::ONE && $class->fieldMappings[$propName]['isOwningSide']) {
if ($orgValue !== null && $class->fieldMappings[$propName]['orphanRemoval']) {
$this->scheduleOrphanRemoval($orgValue);
}
$changeSet[$propName] = [$orgValue, $actualValue];
continue;
}
if ($isChangeTrackingNotify) {
continue;
}
// ignore inverse side of reference relationship
if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['isInverseSide']) {
continue;
}
// Persistent collection was exchanged with the "originally"
// created one. This can only mean it was cloned and replaced
// on another document.
if ($actualValue instanceof PersistentCollectionInterface && $actualValue->getOwner() !== $document) {
$actualValue = $this->fixPersistentCollectionOwnership($actualValue, $document, $class, $propName);
}
// if embed-many or reference-many relationship
if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::MANY) {
$changeSet[$propName] = [$orgValue, $actualValue];
/* If original collection was exchanged with a non-empty value
* and $set will be issued, there is no need to $unset it first
*/
if ($actualValue && $actualValue->isDirty() && CollectionHelper::usesSet($class->fieldMappings[$propName]['strategy'])) {
continue;
}
if ($orgValue !== $actualValue && $orgValue instanceof PersistentCollectionInterface) {
$this->scheduleCollectionDeletion($orgValue);
}
continue;
}
// skip equivalent date values
if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === 'date') {
$dateType = Type::getType('date');
assert($dateType instanceof DateType);
$dbOrgValue = $dateType->convertToDatabaseValue($orgValue);
$dbActualValue = $dateType->convertToDatabaseValue($actualValue);
$orgTimestamp = $dbOrgValue instanceof UTCDateTime ? $dbOrgValue->toDateTime()->getTimestamp() : null;
$actualTimestamp = $dbActualValue instanceof UTCDateTime ? $dbActualValue->toDateTime()->getTimestamp() : null;
if ($orgTimestamp === $actualTimestamp) {
continue;
}
}
// regular field
$changeSet[$propName] = [$orgValue, $actualValue];
}
if ($changeSet) {
$this->documentChangeSets[$oid] = isset($this->documentChangeSets[$oid])
? $changeSet + $this->documentChangeSets[$oid]
: $changeSet;
$this->originalDocumentData[$oid] = $actualData;
$this->scheduleForUpdate($document);
}
}
// Look for changes in associations of the document
$associationMappings = array_filter(
$class->associationMappings,
static fn ($assoc) => empty($assoc['notSaved'])
);
foreach ($associationMappings as $mapping) {
$value = $class->reflFields[$mapping['fieldName']]->getValue($document);
if ($value === null) {
continue;
}
$this->computeAssociationChanges($document, $mapping, $value);
if (isset($mapping['reference'])) {
continue;
}
$values = $mapping['type'] === ClassMetadata::ONE ? [$value] : $value->unwrap();
foreach ($values as $obj) {
$oid2 = spl_object_hash($obj);
if (! isset($this->documentChangeSets[$oid2])) {
continue;
}
if (empty($this->documentChangeSets[$oid][$mapping['fieldName']])) {
// instance of $value is the same as it was previously otherwise there would be
// change set already in place
$this->documentChangeSets[$oid][$mapping['fieldName']] = [$value, $value];
}
if (! $isNewDocument) {
$this->scheduleForUpdate($document);
}
break;
}
}
}
/**
* Computes all the changes that have been done to documents and collections
* since the last commit and stores these changes in the _documentChangeSet map
* temporarily for access by the persisters, until the UoW commit is finished.
*/
public function computeChangeSets(): void
{
$this->computeScheduleInsertsChangeSets();
$this->computeScheduleUpsertsChangeSets();
// Compute changes for other MANAGED documents. Change tracking policies take effect here.
foreach ($this->identityMap as $className => $documents) {
$class = $this->dm->getClassMetadata($className);
if ($class->isEmbeddedDocument || $class->isView()) {
/* we do not want to compute changes to embedded documents up front
* in case embedded document was replaced and its changeset
* would corrupt data. Embedded documents' change set will
* be calculated by reachability from owning document.
*/
continue;
}
// If change tracking is explicit or happens through notification, then only compute
// changes on document of that type that are explicitly marked for synchronization.
switch (true) {
case $class->isChangeTrackingDeferredImplicit():
$documentsToProcess = $documents;
break;
case isset($this->scheduledForSynchronization[$className]):
$documentsToProcess = $this->scheduledForSynchronization[$className];
break;
default:
$documentsToProcess = [];
}
foreach ($documentsToProcess as $document) {
// Ignore uninitialized proxy objects
if ($this->isUninitializedObject($document)) {
continue;
}
// Only MANAGED documents that are NOT SCHEDULED FOR INSERTION, UPSERT OR DELETION are processed here.
$oid = spl_object_hash($document);
if (
isset($this->documentInsertions[$oid])
|| isset($this->documentUpserts[$oid])
|| isset($this->documentDeletions[$oid])
|| ! isset($this->documentStates[$oid])
) {
continue;
}
$this->computeChangeSet($class, $document);
}
}
}
/**
* Computes the changes of an association.
*
* @param mixed $value The value of the association.
* @psalm-param AssociationFieldMapping $assoc
*
* @throws InvalidArgumentException
*/
private function computeAssociationChanges(object $parentDocument, array $assoc, $value): void
{
$isNewParentDocument = isset($this->documentInsertions[spl_object_hash($parentDocument)]);
$class = $this->dm->getClassMetadata($parentDocument::class);
$topOrExistingDocument = ( ! $isNewParentDocument || ! $class->isEmbeddedDocument);
if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
return;
}
if ($value instanceof PersistentCollectionInterface && $value->isDirty() && $value->getOwner() !== null && ($assoc['isOwningSide'] || isset($assoc['embedded']))) {
if ($topOrExistingDocument || CollectionHelper::usesSet($assoc['strategy'])) {
$this->scheduleCollectionUpdate($value);
}
$topmostOwner = $this->getOwningDocument($value->getOwner());
$this->visitedCollections[spl_object_hash($topmostOwner)][] = $value;
if (! empty($assoc['orphanRemoval']) || isset($assoc['embedded'])) {
$value->initialize();
foreach ($value->getDeletedDocuments() as $orphan) {
$this->scheduleOrphanRemoval($orphan);
}
}
}
// Look through the documents, and in any of their associations,
// for transient (new) documents, recursively. ("Persistence by reachability")
// Unwrap. Uninitialized collections will simply be empty.
$unwrappedValue = $assoc['type'] === ClassMetadata::ONE ? [$value] : $value->unwrap();
$count = 0;
foreach ($unwrappedValue as $key => $entry) {
if (! is_object($entry)) {
throw new InvalidArgumentException(
sprintf('Expected object, found "%s" in %s::%s', $entry, $parentDocument::class, $assoc['name']),
);
}
$targetClass = $this->dm->getClassMetadata($entry::class);
$state = $this->getDocumentState($entry, self::STATE_NEW);
// Handle "set" strategy for multi-level hierarchy
$pathKey = ! isset($assoc['strategy']) || CollectionHelper::isList($assoc['strategy']) ? $count : $key;
$path = $assoc['type'] === ClassMetadata::MANY ? $assoc['name'] . '.' . $pathKey : $assoc['name'];
$count++;