forked from doctrine/mongodb-odm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnitOfWork.php
2813 lines (2556 loc) · 106 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
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ODM\MongoDB;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\EventManager;
use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\MongoDB\GridFSFile;
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PreLoadEventArgs;
use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
use Doctrine\ODM\MongoDB\Internal\CommitOrderCalculator;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\PersistentCollection;
use Doctrine\ODM\MongoDB\Persisters\PersistenceBuilder;
use Doctrine\ODM\MongoDB\Proxy\Proxy;
use Doctrine\ODM\MongoDB\Query\Query;
use Doctrine\ODM\MongoDB\Types\Type;
/**
* 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.
*
* @since 1.0
* @author Jonathan H. Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class UnitOfWork implements PropertyChangedListener
{
/**
* An document is in MANAGED state when its persistence is managed by an DocumentManager.
*/
const STATE_MANAGED = 1;
/**
* An document is new if it has just been instantiated (i.e. using the "new" operator)
* and is not (yet) managed by an DocumentManager.
*/
const STATE_NEW = 2;
/**
* A detached document is an instance with a persistent identity that is not
* (or no longer) associated with an DocumentManager (and a UnitOfWork).
*/
const STATE_DETACHED = 3;
/**
* A removed document instance is an instance with a persistent identity,
* associated with an DocumentManager, whose persistent state has been
* deleted (or is scheduled for deletion).
*/
const STATE_REMOVED = 4;
/**
* The identity map that holds references to all managed documents that have
* an identity. The documents 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 array
*/
private $identityMap = array();
/**
* Map of all identifiers of managed documents.
* Keys are object ids (spl_object_hash).
*
* @var array
*/
private $documentIdentifiers = array();
/**
* 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.
*
* @var array
* @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.
*/
private $originalDocumentData = array();
/**
* 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.
*
* @var array
*/
private $documentChangeSets = array();
/**
* The (cached) states of any known documents.
* Keys are object ids (spl_object_hash).
*
* @var array
*/
private $documentStates = array();
/**
* Map of documents that are scheduled for dirty checking at commit time.
* This is only used for documents with a change tracking policy of DEFERRED_EXPLICIT.
* Keys are object ids (spl_object_hash).
*
* @var array
* @todo rename: scheduledForSynchronization
*/
private $scheduledForDirtyCheck = array();
/**
* A list of all pending document insertions.
*
* @var array
*/
private $documentInsertions = array();
/**
* A list of all pending document updates.
*
* @var array
*/
private $documentUpdates = array();
/**
* A list of all pending document upserts.
*
* @var array
*/
private $documentUpserts = array();
/**
* Any pending extra updates that have been scheduled by persisters.
*
* @var array
*/
private $extraUpdates = array();
/**
* A list of all pending document deletions.
*
* @var array
*/
private $documentDeletions = array();
/**
* All pending collection deletions.
*
* @var array
*/
private $collectionDeletions = array();
/**
* All pending collection updates.
*
* @var array
*/
private $collectionUpdates = array();
/**
* 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 array
*/
private $visitedCollections = array();
/**
* The DocumentManager that "owns" this UnitOfWork instance.
*
* @var DocumentManager
*/
private $dm;
/**
* The calculator used to calculate the order in which changes to
* documents need to be written to the database.
*
* @var Internal\CommitOrderCalculator
*/
private $commitOrderCalculator;
/**
* The EventManager used for dispatching events.
*
* @var EventManager
*/
private $evm;
/**
* Embedded documents that are scheduled for removal.
*
* @var array
*/
private $orphanRemovals = array();
/**
* The HydratorFactory used for hydrating array Mongo documents to Doctrine object documents.
*
* @var HydratorFactory
*/
private $hydratorFactory;
/**
* The document persister instances used to persist document instances.
*
* @var array
*/
private $persisters = array();
/**
* The collection persister instance used to persist changes to collections.
*
* @var Persisters\CollectionPersister
*/
private $collectionPersister;
/**
* The persistence builder instance used in DocumentPersisters.
*
* @var PersistenceBuilder
*/
private $persistenceBuilder;
/**
* Array of parent associations between embedded documents
*
* @todo We might need to clean up this array in clear(), doDetach(), etc.
* @var array
*/
private $parentAssociations = array();
/**
* Mongo command character
*
* @var string
*/
private $cmd;
/**
* Initializes a new UnitOfWork instance, bound to the given DocumentManager.
*
* @param DocumentManager $dm
* @param EventManager $evm
* @param HydratorFactory $hydratorFactory
* @param string $cmd
*/
public function __construct(DocumentManager $dm, EventManager $evm, HydratorFactory $hydratorFactory, $cmd)
{
$this->dm = $dm;
$this->evm = $evm;
$this->hydratorFactory = $hydratorFactory;
$this->cmd = $cmd;
}
/**
* Factory for returning new PersistenceBuilder instances used for preparing data into
* queries for insert persistence.
*
* @return PersistenceBuilder $pb
*/
public function getPersistenceBuilder()
{
if ( ! $this->persistenceBuilder) {
$this->persistenceBuilder = new PersistenceBuilder($this->dm, $this, $this->cmd);
}
return $this->persistenceBuilder;
}
/**
* Sets the parent association for a given embedded document.
*
* @param object $document
* @param array $mapping
* @param object $parent
* @param string $propertyPath
*/
public function setParentAssociation($document, $mapping, $parent, $propertyPath)
{
$oid = spl_object_hash($document);
$this->parentAssociations[$oid] = array($mapping, $parent, $propertyPath);
}
/**
* Gets the parent association for a given embedded document.
*
* <code>
* list($mapping, $parent, $propertyPath) = $this->getParentAssociation($embeddedDocument);
* </code>
*
* @param object $document
* @return array $association
*/
public function getParentAssociation($document)
{
$oid = spl_object_hash($document);
if ( ! isset($this->parentAssociations[$oid])) {
return null;
}
return $this->parentAssociations[$oid];
}
/**
* Get the document persister instance for the given document name
*
* @param string $documentName
* @return Persisters\DocumentPersister
*/
public function getDocumentPersister($documentName)
{
if ( ! isset($this->persisters[$documentName])) {
$class = $this->dm->getClassMetadata($documentName);
$pb = $this->getPersistenceBuilder();
$this->persisters[$documentName] = new Persisters\DocumentPersister($pb, $this->dm, $this->evm, $this, $this->hydratorFactory, $class, $this->cmd);
}
return $this->persisters[$documentName];
}
/**
* Gets a collection persister for a collection-valued association.
*
* @param array $mapping
* @return Persisters\CollectionPersister
*/
public function getCollectionPersister(array $mapping)
{
if ( ! isset($this->collectionPersister)) {
$pb = $this->getPersistenceBuilder();
$this->collectionPersister = new Persisters\CollectionPersister($this->dm, $pb, $this, $this->cmd);
}
return $this->collectionPersister;
}
/**
* Set the document persister instance to use for the given document name
*
* @param string $documentName
* @param Persisters\DocumentPersister $persister
*/
public function setDocumentPersister($documentName, Persisters\DocumentPersister $persister)
{
$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 object $document
* @param array $options Array of options to be used with batchInsert(), update() and remove()
*/
public function commit($document = null, array $options = array())
{
// Raise preFlush
if ($this->evm->hasListeners(Events::preFlush)) {
$this->evm->dispatchEvent(Events::preFlush, new Event\PreFlushEventArgs($this->dm));
}
$defaultOptions = $this->dm->getConfiguration()->getDefaultCommitOptions();
if ($options) {
$options = array_merge($defaultOptions, $options);
} else {
$options = $defaultOptions;
}
// Compute changes done since last commit.
if ($document === null) {
$this->computeChangeSets();
} elseif (is_object($document)) {
$this->computeSingleDocumentChangeSet($document);
} elseif (is_array($document)) {
foreach ($document as $object) {
$this->computeSingleDocumentChangeSet($object);
}
}
if ( ! ($this->documentInsertions ||
$this->documentUpserts ||
$this->documentDeletions ||
$this->documentUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)
) {
return; // Nothing to do.
}
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $removal) {
$this->remove($removal);
}
}
// Raise onFlush
if ($this->evm->hasListeners(Events::onFlush)) {
$this->evm->dispatchEvent(Events::onFlush, new Event\OnFlushEventArgs($this->dm));
}
// Now we need a commit order to maintain referential integrity
$commitOrder = $this->getCommitOrder();
if ($this->documentInsertions) {
foreach ($commitOrder as $class) {
if ($class->isEmbeddedDocument) {
continue;
}
$this->executeInserts($class, $options);
}
}
if ($this->documentUpdates) {
foreach ($commitOrder as $class) {
$this->executeUpdates($class, $options);
}
}
// Extra updates that were requested by persisters.
if ($this->extraUpdates) {
$this->executeExtraUpdates($options);
}
// Collection deletions (deletions of complete collections)
foreach ($this->collectionDeletions as $collectionToDelete) {
$this->getCollectionPersister($collectionToDelete->getMapping())
->delete($collectionToDelete, $options);
}
// Collection updates (deleteRows, updateRows, insertRows)
foreach ($this->collectionUpdates as $collectionToUpdate) {
$this->getCollectionPersister($collectionToUpdate->getMapping())
->update($collectionToUpdate, $options);
}
// Document deletions come last and need to be in reverse commit order
if ($this->documentDeletions) {
for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
$this->executeDeletions($commitOrder[$i], $options);
}
}
// Take new snapshots from visited collections
foreach ($this->visitedCollections as $coll) {
$coll->takeSnapshot();
}
// Raise postFlush
if ($this->evm->hasListeners(Events::postFlush)) {
$this->evm->dispatchEvent(Events::postFlush, new Event\PostFlushEventArgs($this->dm));
}
// Clear up
$this->documentInsertions =
$this->documentUpserts =
$this->documentUpdates =
$this->documentDeletions =
$this->extraUpdates =
$this->documentChangeSets =
$this->collectionUpdates =
$this->collectionDeletions =
$this->visitedCollections =
$this->scheduledForDirtyCheck =
$this->orphanRemovals = array();
}
/**
* Compute the changesets of all documents scheduled for insertion
*
* @return void
*/
private function computeScheduleInsertsChangeSets()
{
foreach ($this->documentInsertions as $document) {
$class = $this->dm->getClassMetadata(get_class($document));
$this->computeChangeSet($class, $document);
}
}
/**
* Only flush the given document according to a ruleset that keeps the UoW consistent.
*
* 1. All documents scheduled for insertion, (orphan) removals and changes in collections are processed as well!
* 2. Proxies are skipped.
* 3. Only if document is properly managed.
*
* @param object $document
* @throws \InvalidArgumentException If the document is not STATE_MANAGED
* @return void
*/
private function computeSingleDocumentChangeSet($document)
{
if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
throw new \InvalidArgumentException("Document has to be managed for single computation " . self::objToStr($document));
}
$class = $this->dm->getClassMetadata(get_class($document));
if ($class->isChangeTrackingDeferredImplicit()) {
$this->persist($document);
}
// Compute changes for INSERTed documents first. This must always happen even in this case.
$this->computeScheduleInsertsChangeSets();
// Ignore uninitialized proxy objects
if ($document instanceof Proxy && ! $document->__isInitialized__) {
return;
}
// Only MANAGED documents that are NOT SCHEDULED FOR INSERTION are processed here.
$oid = spl_object_hash($document);
if ( ! isset($this->documentInsertions[$oid]) && isset($this->documentStates[$oid])) {
$this->computeChangeSet($class, $document);
}
}
/**
* Executes reference updates
*/
private function executeExtraUpdates(array $options)
{
foreach ($this->extraUpdates as $oid => $update) {
list ($document, $changeset) = $update;
$this->documentChangeSets[$oid] = $changeset;
$this->getDocumentPersister(get_class($document))->update($document, $options);
}
}
/**
* Gets the changeset for an document.
*
* @param object $document
* @return array
*/
public function getDocumentChangeSet($document)
{
$oid = spl_object_hash($document);
if (isset($this->documentChangeSets[$oid])) {
return $this->documentChangeSets[$oid];
}
return array();
}
/**
* Get a documents actual data, flattening all the objects to arrays.
*
* @param object $document
* @return array
*/
public function getDocumentActualData($document)
{
$class = $this->dm->getClassMetadata(get_class($document));
$actualData = array();
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['file']) && ! $value instanceof GridFSFile) {
$value = new GridFSFile($value);
$class->reflFields[$name]->setValue($document, $value);
$actualData[$name] = $value;
} elseif ((isset($mapping['association']) && $mapping['type'] === 'many')
&& $value !== null && ! ($value instanceof PersistentCollection)) {
// If $actualData[$name] is not a Collection then use an ArrayCollection.
if ( ! $value instanceof Collection) {
$value = new ArrayCollection($value);
}
// Inject PersistentCollection
$coll = new PersistentCollection($value, $this->dm, $this, $this->cmd);
$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.
*
* @param ClassMetadata $class The class descriptor of the document.
* @param object $document The document for which to compute the changes.
*/
public function computeChangeSet(ClassMetadata $class, $document)
{
if ( ! $class->isInheritanceTypeNone()) {
$class = $this->dm->getClassMetadata(get_class($document));
}
// Fire PreFlush lifecycle callbacks
if (isset($class->lifecycleCallbacks[Events::preFlush])) {
$class->invokeLifecycleCallbacks(Events::preFlush, $document);
}
$this->computeOrRecomputeChangeSet($class, $document);
}
/**
* Used to do the common work of computeChangeSet and recomputeSingleDocumentChangeSet
*
* @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $class
* @param object $document
* @param boolean $recompute
*/
private function computeOrRecomputeChangeSet(ClassMetadata $class, $document, $recompute = false)
{
$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 = array();
foreach ($actualData as $propName => $actualValue) {
$changeSet[$propName] = array(null, $actualValue);
}
$this->documentChangeSets[$oid] = $changeSet;
} else {
// 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) {
$changeSet = $this->documentChangeSets[$oid];
} else {
$changeSet = array();
}
foreach ($actualData as $propName => $actualValue) {
// skip not saved fields
if (isset($class->fieldMappings[$propName]['notSaved']) && $class->fieldMappings[$propName]['notSaved'] === true) {
continue;
}
$orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
// skip if value has not changed
if ($orgValue === $actualValue) {
// but consider dirty GridFSFile instances as changed
if ( ! (isset($class->fieldMappings[$propName]['file']) && $actualValue->isDirty())) {
continue;
}
}
// if embed-one relationship
if (isset($class->fieldMappings[$propName]['embedded']) && $class->fieldMappings[$propName]['type'] === 'one') {
if ($orgValue !== null) {
$this->scheduleOrphanRemoval($orgValue);
}
$changeSet[$propName] = array($orgValue, $actualValue);
continue;
}
// if owning side of reference-one relationship
if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['type'] === 'one' && $class->fieldMappings[$propName]['isOwningSide']) {
$changeSet[$propName] = array($orgValue, $actualValue);
continue;
}
if ($isChangeTrackingNotify) {
continue;
}
// ignore inverse side of reference-many relationship
if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['type'] === 'many' && $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 PersistentCollection) {
$owner = $actualValue->getOwner();
if ($owner === null) { // cloned
$actualValue->setOwner($document, $class->fieldMappings[$propName]);
} elseif ($owner !== $document) { // 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($document, $class->fieldMappings[$propName]);
$class->reflFields[$propName]->setValue($document, $newValue);
}
}
// if embed-many or reference-many relationship
if ($class->fieldMappings[$propName]['type'] === 'many') {
$changeSet[$propName] = array($orgValue, $actualValue);
if ($orgValue instanceof PersistentCollection) {
$this->collectionDeletions[] = $orgValue;
}
continue;
}
// skip equivalent date values
if ($class->fieldMappings[$propName]['type'] === 'date') {
$dateType = Type::getType('date');
$dbOrgValue = $dateType->convertToDatabaseValue($orgValue);
$dbActualValue = $dateType->convertToDatabaseValue($actualValue);
if ($dbOrgValue instanceof \MongoDate && $dbActualValue instanceof \MongoDate && $dbOrgValue == $dbActualValue) {
continue;
}
}
// regular field
$changeSet[$propName] = array($orgValue, $actualValue);
}
if ($changeSet) {
if ($recompute) {
$this->documentChangeSets[$oid] = $changeSet + $this->documentChangeSets[$oid];
} else {
$this->documentChangeSets[$oid] = $changeSet;
}
$this->originalDocumentData[$oid] = $actualData;
$this->documentUpdates[$oid] = $document;
}
}
// Look for changes in associations of the document
foreach ($class->fieldMappings as $mapping) {
// skip not saved fields
if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) {
continue;
}
if (isset($mapping['reference']) || isset($mapping['embedded'])) {
$value = $class->reflFields[$mapping['fieldName']]->getValue($document);
if ($value !== null) {
$this->computeAssociationChanges($document, $mapping, $value);
if (isset($mapping['reference'])) {
continue;
}
$values = $value;
if (isset($mapping['type']) && $mapping['type'] === 'one') {
$values = array($values);
} elseif ($values instanceof PersistentCollection) {
$values = $values->unwrap();
}
foreach ($values as $obj) {
$oid2 = spl_object_hash($obj);
if (isset($this->documentChangeSets[$oid2])) {
$this->documentChangeSets[$oid][$mapping['fieldName']] = array($value, $value);
if ( ! $isNewDocument) {
$this->documentUpdates[$oid] = $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()
{
$this->computeScheduleInsertsChangeSets();
// 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) {
// Embedded documents should only compute by the document itself which include the embedded document.
// This is done separately later.
// @see computeChangeSet()
// @see computeAssociationChanges()
continue;
}
// If change tracking is explicit or happens through notification, then only compute
// changes on documents of that type that are explicitly marked for synchronization.
$documentsToProcess = ! $class->isChangeTrackingDeferredImplicit() ?
(isset($this->scheduledForDirtyCheck[$className]) ?
$this->scheduledForDirtyCheck[$className] : array())
: $documents;
foreach ($documentsToProcess as $document) {
// Ignore uninitialized proxy objects
if (/* $document is readOnly || */ $document instanceof Proxy && ! $document->__isInitialized__) {
continue;
}
// Only MANAGED documents that are NOT SCHEDULED FOR INSERTION are processed here.
$oid = spl_object_hash($document);
if ( ! isset($this->documentInsertions[$oid]) && isset($this->documentStates[$oid])) {
$this->computeChangeSet($class, $document);
}
}
}
}
/**
* Computes the changes of an embedded document.
*
* @param object $parentDocument
* @param array $mapping
* @param mixed $value The value of the association.
* @throws \InvalidArgumentException
*/
private function computeAssociationChanges($parentDocument, $mapping, $value)
{
$isNewParentDocument = isset($this->documentInsertions[spl_object_hash($parentDocument)]);
$class = $this->dm->getClassMetadata(get_class($parentDocument));
$topOrExistingDocument = ( ! $isNewParentDocument || ! $class->isEmbeddedDocument);
if ($value instanceof PersistentCollection && $value->isDirty() && $mapping['isOwningSide'] && ($topOrExistingDocument || $mapping['strategy'] === 'set')) {
if ( ! in_array($value, $this->collectionUpdates, true)) {
$this->collectionUpdates[] = $value;
}
$this->visitedCollections[] = $value;
} elseif ($value instanceof PersistentCollection && $value->isDirty() && $mapping['isOwningSide']) {
$this->visitedCollections[] = $value;
}
if ( ! isset($mapping['embedded']) && ! $mapping['isCascadePersist']) {
return; // "Persistence by reachability" only if persist cascade specified
}
if ($mapping['type'] === 'one') {
if ($value instanceof Proxy && ! $value->__isInitialized__) {
return; // Ignore uninitialized proxy objects
}
$value = array($value);
} elseif ($value instanceof PersistentCollection) {
$value = $value->unwrap();
}
$count = 0;
foreach ($value as $key => $entry) {
$targetClass = $this->dm->getClassMetadata(get_class($entry));
$state = $this->getDocumentState($entry, self::STATE_NEW);
$oid = spl_object_hash($entry);
// Handle "set" strategy for multi-level hierarchy
$pathKey = $mapping['strategy'] !== 'set' ? $count : $key;
$path = $mapping['type'] === 'many' ? $mapping['name'] . '.' . $pathKey : $mapping['name'];
$count++;
if ($state == self::STATE_NEW) {
if ( ! $targetClass->isEmbeddedDocument && ! $mapping['isCascadePersist']) {
throw new \InvalidArgumentException("A new document was found through a relationship that was not"
. " configured to cascade persist operations: " . self::objToStr($entry) . "."
. " Explicitly persist the new document or configure cascading persist operations"
. " on the relationship.");
}
$this->persistNew($targetClass, $entry);
$this->setParentAssociation($entry, $mapping, $parentDocument, $path);
$this->computeChangeSet($targetClass, $entry);
} elseif ($state == self::STATE_MANAGED && $targetClass->isEmbeddedDocument) {
$this->setParentAssociation($entry, $mapping, $parentDocument, $path);
$this->computeChangeSet($targetClass, $entry);
} elseif ($state == self::STATE_REMOVED) {
throw new \InvalidArgumentException("Removed document detected during flush: "
. self::objToStr($entry) . ". Remove deleted documents from associations.");
} elseif ($state == 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 new \InvalidArgumentException("A detached document was found through a "
. "relationship during cascading a persist operation.");
}
}
}
/**
* INTERNAL:
* Computes the changeset of an individual document, independently of the
* computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
*
* The passed document must be a managed document. If the document 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.
*
* @ignore
* @param ClassMetadata $class The class descriptor of the document.
* @param object $document The document for which to (re)calculate the change set.
* @throws \InvalidArgumentException If the passed document is not MANAGED.
*/
public function recomputeSingleDocumentChangeSet(ClassMetadata $class, $document)
{
$oid = spl_object_hash($document);
if ( ! isset($this->documentStates[$oid]) || $this->documentStates[$oid] != self::STATE_MANAGED) {
throw new \InvalidArgumentException('Document must be managed.');
}
if ( ! $class->isInheritanceTypeNone()) {
$class = $this->dm->getClassMetadata(get_class($document));
}
$this->computeOrRecomputeChangeSet($class, $document, true);
}
/**
* @param $class
* @param object $document
*/
private function persistNew($class, $document)
{
$oid = spl_object_hash($document);
if (isset($class->lifecycleCallbacks[Events::prePersist])) {
$class->invokeLifecycleCallbacks(Events::prePersist, $document);
}
if ($this->evm->hasListeners(Events::prePersist)) {
$this->evm->dispatchEvent(Events::prePersist, new LifecycleEventArgs($document, $this->dm));
}
$this->documentStates[$oid] = self::STATE_MANAGED;
$this->scheduleForInsert($class, $document);
}
/**
* Executes all document insertions for documents of the specified type.
*
* @param ClassMetadata $class
* @param array $options Array of options to be used with batchInsert()
*/
private function executeInserts(ClassMetadata $class, array $options = array())
{
$className = $class->name;
$persister = $this->getDocumentPersister($className);
$collection = $this->dm->getDocumentCollection($className);
$insertedDocuments = array();
foreach ($this->documentInsertions as $oid => $document) {
if (get_class($document) === $className) {
$persister->addInsert($document);
$insertedDocuments[] = $document;
unset($this->documentInsertions[$oid]);
}
}
$postInsertIds = $persister->executeInserts($options);
foreach ($postInsertIds as $idAndDocument) {
list($id, $document) = $idAndDocument;
$class->setIdentifierValue($document, $id);
/* Inline call to UnitOfWork::registerManager(), but only update the
* identifier in the original document data.
*/
$oid = spl_object_hash($document);
$this->documentIdentifiers[$oid] = $id;
$this->documentStates[$oid] = self::STATE_MANAGED;