-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnitOfWork.php
2237 lines (2087 loc) · 81.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
namespace Bankiru\Api\Doctrine;
use Bankiru\Api\Doctrine\Cache\ApiEntityCache;
use Bankiru\Api\Doctrine\Cache\EntityCacheAwareInterface;
use Bankiru\Api\Doctrine\Cache\LoggingCache;
use Bankiru\Api\Doctrine\Cache\VoidEntityCache;
use Bankiru\Api\Doctrine\Exception\MappingException;
use Bankiru\Api\Doctrine\Hydration\EntityHydrator;
use Bankiru\Api\Doctrine\Hydration\Hydrator;
use Bankiru\Api\Doctrine\Mapping\ApiMetadata;
use Bankiru\Api\Doctrine\Mapping\EntityMetadata;
use Bankiru\Api\Doctrine\Persister\ApiPersister;
use Bankiru\Api\Doctrine\Persister\CollectionMatcher;
use Bankiru\Api\Doctrine\Persister\CollectionPersister;
use Bankiru\Api\Doctrine\Persister\EntityPersister;
use Bankiru\Api\Doctrine\Proxy\ApiCollection;
use Bankiru\Api\Doctrine\Rpc\CrudsApiInterface;
use Bankiru\Api\Doctrine\Utility\IdentifierFlattener;
use Bankiru\Api\Doctrine\Utility\ReflectionPropertiesGetter;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Common\Persistence\ObjectManagerAware;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\Common\Proxy\Proxy;
class UnitOfWork implements PropertyChangedListener
{
/**
* An entity is in MANAGED state when its persistence is managed by an EntityManager.
*/
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.
*/
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).
*/
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.
*/
const STATE_REMOVED = 4;
/**
* The (cached) states of any known entities.
* Keys are object ids (spl_object_hash).
*
* @var array
*/
private $entityStates = [];
/** @var EntityManager */
private $manager;
/** @var EntityPersister[] */
private $persisters = [];
/** @var CollectionPersister[] */
private $collectionPersisters = [];
/** @var array */
private $entityIdentifiers = [];
/** @var object[][] */
private $identityMap = [];
/** @var IdentifierFlattener */
private $identifierFlattener;
/** @var array */
private $originalEntityData = [];
/** @var array */
private $entityDeletions = [];
/** @var array */
private $entityChangeSets = [];
/** @var array */
private $entityInsertions = [];
/** @var array */
private $entityUpdates = [];
/** @var array */
private $readOnlyObjects = [];
/** @var array */
private $scheduledForSynchronization = [];
/** @var array */
private $orphanRemovals = [];
/** @var ApiCollection[] */
private $collectionDeletions = [];
/** @var array */
private $extraUpdates = [];
/** @var ApiCollection[] */
private $collectionUpdates = [];
/** @var ApiCollection[] */
private $visitedCollections = [];
/** @var ReflectionPropertiesGetter */
private $reflectionPropertiesGetter;
/** @var Hydrator[] */
private $hydrators = [];
/** @var CrudsApiInterface[] */
private $apis = [];
/**
* UnitOfWork constructor.
*
* @param EntityManager $manager
*/
public function __construct(EntityManager $manager)
{
$this->manager = $manager;
$this->identifierFlattener = new IdentifierFlattener($this->manager);
$this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
}
/**
* @param $className
*
* @return EntityPersister
*/
public function getEntityPersister($className)
{
if (!array_key_exists($className, $this->persisters)) {
/** @var ApiMetadata $classMetadata */
$classMetadata = $this->manager->getClassMetadata($className);
$api = $this->getCrudsApi($classMetadata);
if ($api instanceof EntityCacheAwareInterface) {
$api->setEntityCache($this->createEntityCache($classMetadata));
}
$this->persisters[$className] = new ApiPersister($this->manager, $api);
}
return $this->persisters[$className];
}
/**
* Checks whether an entity is registered in the identity map of this UnitOfWork.
*
* @param object $entity
*
* @return boolean
*/
public function isInIdentityMap($entity)
{
$oid = spl_object_hash($entity);
if (!isset($this->entityIdentifiers[$oid])) {
return false;
}
/** @var EntityMetadata $classMetadata */
$classMetadata = $this->manager->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[$oid]);
if ($idHash === '') {
return false;
}
return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
}
/**
* Gets the identifier of an entity.
* The returned value is always an array of identifier values. If the entity
* has a composite identifier then the identifier values are in the same
* order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
*
* @param object $entity
*
* @return array The identifier values.
*/
public function getEntityIdentifier($entity)
{
return $this->entityIdentifiers[spl_object_hash($entity)];
}
/**
* @param string $className
* @param \stdClass $data
*
* @return ObjectManagerAware|object
* @throws MappingException
*/
public function getOrCreateEntity($className, \stdClass $data)
{
/** @var EntityMetadata $class */
$class = $this->resolveSourceMetadataForClass($data, $className);
$tmpEntity = $this->getHydratorForClass($class)->hydarate($data);
$id = $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($tmpEntity));
$idHash = implode(' ', $id);
$overrideLocalValues = false;
if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
$entity = $this->identityMap[$class->rootEntityName][$idHash];
$oid = spl_object_hash($entity);
if ($entity instanceof Proxy && !$entity->__isInitialized()) {
$entity->__setInitialized(true);
$overrideLocalValues = true;
$this->originalEntityData[$oid] = $data;
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
}
} else {
$entity = $this->newInstance($class);
$oid = spl_object_hash($entity);
$this->entityIdentifiers[$oid] = $id;
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->originalEntityData[$oid] = $data;
$this->identityMap[$class->rootEntityName][$idHash] = $entity;
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
$overrideLocalValues = true;
}
if (!$overrideLocalValues) {
return $entity;
}
$entity = $this->getHydratorForClass($class)->hydarate($data, $entity);
return $entity;
}
/**
* INTERNAL:
* Registers an entity as managed.
*
* @param Proxy $entity The entity.
* @param array $id The identifier values.
* @param \stdClass|null $data The original entity data.
*
* @return void
*/
public function registerManaged($entity, array $id, \stdClass $data = null)
{
$oid = spl_object_hash($entity);
$this->entityIdentifiers[$oid] = $id;
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->originalEntityData[$oid] = $data;
$this->addToIdentityMap($entity);
if ($entity instanceof NotifyPropertyChanged && (!$entity instanceof Proxy || $entity->__isInitialized())) {
$entity->addPropertyChangedListener($this);
}
}
/**
* INTERNAL:
* Registers an entity in the identity map.
* Note that entities in a hierarchy are registered with the class name of
* the root entity.
*
* @ignore
*
* @param object $entity The entity to register.
*
* @return boolean TRUE if the registration was successful, FALSE if the identity of
* the entity in question is already managed.
*
*/
public function addToIdentityMap($entity)
{
/** @var EntityMetadata $classMetadata */
$classMetadata = $this->manager->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
if ($idHash === '') {
throw new \InvalidArgumentException('Entitty does not have valid identifiers to be stored at identity map');
}
$className = $classMetadata->rootEntityName;
if (isset($this->identityMap[$className][$idHash])) {
return false;
}
$this->identityMap[$className][$idHash] = $entity;
return true;
}
/**
* Gets the identity map of the UnitOfWork.
*
* @return array
*/
public function getIdentityMap()
{
return $this->identityMap;
}
/**
* Gets the original data of an entity. The original data is the data that was
* present at the time the entity was reconstituted from the database.
*
* @param object $entity
*
* @return array
*/
public function getOriginalEntityData($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->originalEntityData[$oid])) {
return $this->originalEntityData[$oid];
}
return [];
}
/**
* INTERNAL:
* Checks whether an identifier hash exists in the identity map.
*
* @ignore
*
* @param string $idHash
* @param string $rootClassName
*
* @return boolean
*/
public function containsIdHash($idHash, $rootClassName)
{
return isset($this->identityMap[$rootClassName][$idHash]);
}
/**
* INTERNAL:
* Gets an entity in the identity map by its identifier hash.
*
* @ignore
*
* @param string $idHash
* @param string $rootClassName
*
* @return object
*/
public function getByIdHash($idHash, $rootClassName)
{
return $this->identityMap[$rootClassName][$idHash];
}
/**
* INTERNAL:
* Tries to get an entity by its identifier hash. If no entity is found for
* the given hash, FALSE is returned.
*
* @ignore
*
* @param mixed $idHash (must be possible to cast it to string)
* @param string $rootClassName
*
* @return object|bool The found entity or FALSE.
*/
public function tryGetByIdHash($idHash, $rootClassName)
{
$stringIdHash = (string)$idHash;
if (isset($this->identityMap[$rootClassName][$stringIdHash])) {
return $this->identityMap[$rootClassName][$stringIdHash];
}
return false;
}
/**
* Gets the state of an entity with regard to the current unit of work.
*
* @param object $entity
* @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
* This parameter can be set to improve performance of entity state detection
* by potentially avoiding a database lookup if the distinction between NEW and DETACHED
* is either known or does not matter for the caller of the method.
*
* @return int The entity state.
*/
public function getEntityState($entity, $assume = null)
{
$oid = spl_object_hash($entity);
if (isset($this->entityStates[$oid])) {
return $this->entityStates[$oid];
}
if ($assume !== null) {
return $assume;
}
// State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
// Note that you can not remember the NEW or DETACHED state in _entityStates since
// the UoW does not hold references to such objects and the object hash can be reused.
// More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
$class = $this->manager->getClassMetadata(get_class($entity));
$id = $class->getIdentifierValues($entity);
if (!$id) {
return self::STATE_NEW;
}
return self::STATE_DETACHED;
}
/**
* Tries to find an entity with the given identifier in the identity map of
* this UnitOfWork.
*
* @param mixed $id The entity identifier to look for.
* @param string $rootClassName The name of the root class of the mapped entity hierarchy.
*
* @return object|bool Returns the entity with the specified identifier if it exists in
* this UnitOfWork, FALSE otherwise.
*/
public function tryGetById($id, $rootClassName)
{
/** @var EntityMetadata $metadata */
$metadata = $this->manager->getClassMetadata($rootClassName);
$idHash = implode(' ', (array)$this->identifierFlattener->flattenIdentifier($metadata, $id));
if (isset($this->identityMap[$rootClassName][$idHash])) {
return $this->identityMap[$rootClassName][$idHash];
}
return false;
}
/**
* Notifies this UnitOfWork of a property change in an entity.
*
* @param object $entity The entity that owns the property.
* @param string $propertyName The name of the property that changed.
* @param mixed $oldValue The old value of the property.
* @param mixed $newValue The new value of the property.
*
* @return void
*/
public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
{
$oid = spl_object_hash($entity);
$class = $this->manager->getClassMetadata(get_class($entity));
$isAssocField = $class->hasAssociation($propertyName);
if (!$isAssocField && !$class->hasField($propertyName)) {
return; // ignore non-persistent fields
}
// Update changeset and mark entity for synchronization
$this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue];
if (!isset($this->scheduledForSynchronization[$class->getRootEntityName()][$oid])) {
$this->scheduleForDirtyCheck($entity);
}
}
/**
* Persists an entity as part of the current unit of work.
*
* @param object $entity The entity to persist.
*
* @return void
*/
public function persist($entity)
{
$visited = [];
$this->doPersist($entity, $visited);
}
/**
* @param ApiMetadata $class
* @param $entity
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function recomputeSingleEntityChangeSet(ApiMetadata $class, $entity)
{
$oid = spl_object_hash($entity);
if (!isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
throw new \InvalidArgumentException('Entity is not managed');
}
$actualData = [];
foreach ($class->getReflectionProperties() as $name => $refProp) {
if (!$class->isIdentifier($name) && !$class->isCollectionValuedAssociation($name)) {
$actualData[$name] = $refProp->getValue($entity);
}
}
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 = isset($originalData->$propName) ? $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);
} else {
if (!isset($this->entityInsertions[$oid])) {
$this->entityChangeSets[$oid] = $changeSet;
$this->entityUpdates[$oid] = $entity;
}
}
$this->originalEntityData[$oid] = (object)$actualData;
}
}
/**
* Schedules an entity for insertion into the database.
* If the entity already has an identifier, it will be added to the identity map.
*
* @param object $entity The entity to schedule for insertion.
*
* @return void
*
* @throws \InvalidArgumentException
*/
public function scheduleForInsert($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->entityUpdates[$oid])) {
throw new \InvalidArgumentException('Dirty entity cannot be scheduled for insertion');
}
if (isset($this->entityDeletions[$oid])) {
throw new \InvalidArgumentException('Removed entity scheduled for insertion');
}
if (isset($this->originalEntityData[$oid]) && !isset($this->entityInsertions[$oid])) {
throw new \InvalidArgumentException('Managed entity scheduled for insertion');
}
if (isset($this->entityInsertions[$oid])) {
throw new \InvalidArgumentException('Entity scheduled for insertion twice');
}
$this->entityInsertions[$oid] = $entity;
if (isset($this->entityIdentifiers[$oid])) {
$this->addToIdentityMap($entity);
}
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
}
/**
* Checks whether an entity is scheduled for insertion.
*
* @param object $entity
*
* @return boolean
*/
public function isScheduledForInsert($entity)
{
return isset($this->entityInsertions[spl_object_hash($entity)]);
}
/**
* Schedules an entity for being updated.
*
* @param object $entity The entity to schedule for being updated.
*
* @return void
*
* @throws \InvalidArgumentException
*/
public function scheduleForUpdate($entity)
{
$oid = spl_object_hash($entity);
if (!isset($this->entityIdentifiers[$oid])) {
throw new \InvalidArgumentException('Entity has no identity');
}
if (isset($this->entityDeletions[$oid])) {
throw new \InvalidArgumentException('Entity is removed');
}
if (!isset($this->entityUpdates[$oid]) && !isset($this->entityInsertions[$oid])) {
$this->entityUpdates[$oid] = $entity;
}
}
/**
* Checks whether an entity is registered as dirty in the unit of work.
* Note: Is not very useful currently as dirty entities are only registered
* at commit time.
*
* @param object $entity
*
* @return boolean
*/
public function isScheduledForUpdate($entity)
{
return isset($this->entityUpdates[spl_object_hash($entity)]);
}
/**
* Checks whether an entity is registered to be checked in the unit of work.
*
* @param object $entity
*
* @return boolean
*/
public function isScheduledForDirtyCheck($entity)
{
$rootEntityName = $this->manager->getClassMetadata(get_class($entity))->getRootEntityName();
return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
}
/**
* INTERNAL:
* Schedules an entity for deletion.
*
* @param object $entity
*
* @return void
*/
public function scheduleForDelete($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->entityInsertions[$oid])) {
if ($this->isInIdentityMap($entity)) {
$this->removeFromIdentityMap($entity);
}
unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
return; // entity has not been persisted yet, so nothing more to do.
}
if (!$this->isInIdentityMap($entity)) {
return;
}
$this->removeFromIdentityMap($entity);
unset($this->entityUpdates[$oid]);
if (!isset($this->entityDeletions[$oid])) {
$this->entityDeletions[$oid] = $entity;
$this->entityStates[$oid] = self::STATE_REMOVED;
}
}
/**
* Checks whether an entity is registered as removed/deleted with the unit
* of work.
*
* @param object $entity
*
* @return boolean
*/
public function isScheduledForDelete($entity)
{
return isset($this->entityDeletions[spl_object_hash($entity)]);
}
/**
* Checks whether an entity is scheduled for insertion, update or deletion.
*
* @param object $entity
*
* @return boolean
*/
public function isEntityScheduled($entity)
{
$oid = spl_object_hash($entity);
return isset($this->entityInsertions[$oid])
|| isset($this->entityUpdates[$oid])
|| isset($this->entityDeletions[$oid]);
}
/**
* INTERNAL:
* Removes an entity from the identity map. This effectively detaches the
* entity from the persistence management of Doctrine.
*
* @ignore
*
* @param object $entity
*
* @return boolean
*
* @throws \InvalidArgumentException
*/
public function removeFromIdentityMap($entity)
{
$oid = spl_object_hash($entity);
$classMetadata = $this->manager->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[$oid]);
if ($idHash === '') {
throw new \InvalidArgumentException('Entity has no identity');
}
$className = $classMetadata->getRootEntityName();
if (isset($this->identityMap[$className][$idHash])) {
unset($this->identityMap[$className][$idHash]);
unset($this->readOnlyObjects[$oid]);
//$this->entityStates[$oid] = self::STATE_DETACHED;
return true;
}
return false;
}
/**
* Commits the UnitOfWork, executing all operations that have been postponed
* up to this point. The state of all managed entities will be synchronized with
* the database.
*
* The operations are executed in the following order:
*
* 1) All entity insertions
* 2) All entity updates
* 3) All collection deletions
* 4) All collection updates
* 5) All entity deletions
*
* @param null|object|array $entity
*
* @return void
*
* @throws \Exception
*/
public function commit($entity = null)
{
// Compute changes done since last commit.
if ($entity === null) {
$this->computeChangeSets();
} elseif (is_object($entity)) {
$this->computeSingleEntityChangeSet($entity);
} elseif (is_array($entity)) {
foreach ((array)$entity as $object) {
$this->computeSingleEntityChangeSet($object);
}
}
if (!($this->entityInsertions ||
$this->entityDeletions ||
$this->entityUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)
) {
return; // Nothing to do.
}
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $orphan) {
$this->remove($orphan);
}
}
// Now we need a commit order to maintain referential integrity
$commitOrder = $this->getCommitOrder();
// Collection deletions (deletions of complete collections)
// foreach ($this->collectionDeletions as $collectionToDelete) {
// //fixme: collection mutations
// $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) {
//fixme: decide what to do with collection mutation if API does not support this
//$this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
}
// Entity deletions come last and need to be in reverse commit order
if ($this->entityDeletions) {
for ($count = count($commitOrder), $i = $count - 1; $i >= 0 && $this->entityDeletions; --$i) {
$this->executeDeletions($commitOrder[$i]);
}
}
// Take new snapshots from visited collections
foreach ($this->visitedCollections as $coll) {
$coll->takeSnapshot();
}
// Clear up
$this->entityInsertions =
$this->entityUpdates =
$this->entityDeletions =
$this->extraUpdates =
$this->entityChangeSets =
$this->collectionUpdates =
$this->collectionDeletions =
$this->visitedCollections =
$this->scheduledForSynchronization =
$this->orphanRemovals = [];
}
/**
* Gets the changeset for an entity.
*
* @param object $entity
*
* @return array
*/
public function & getEntityChangeSet($entity)
{
$oid = spl_object_hash($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.
*
* @ignore
*
* @internal Don't call from the outside.
*
* @param ApiMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to compute the changes.
*
* @return void
*/
public function computeChangeSet(ApiMetadata $class, $entity)
{
$oid = spl_object_hash($entity);
if (isset($this->readOnlyObjects[$oid])) {
return;
}
$actualData = [];
foreach ($class->getReflectionProperties() as $name => $refProp) {
$value = $refProp->getValue($entity);
if (null !== $value && $class->isCollectionValuedAssociation($name)) {
if ($value instanceof ApiCollection) {
if ($value->getOwner() === $entity) {
continue;
}
$value = new ArrayCollection($value->getValues());
}
// If $value is not a Collection then use an ArrayCollection.
if (!$value instanceof Collection) {
$value = new ArrayCollection($value);
}
$assoc = $class->getAssociationMapping($name);
// Inject PersistentCollection
$value = new ApiCollection(
$this->manager,
$this->manager->getClassMetadata($assoc['targetEntity']),
$value
);
$value->setOwner($entity, $assoc);
$value->setDirty(!$value->isEmpty());
$class->getReflectionProperty($name)->setValue($entity, $value);
$actualData[$name] = $value;
continue;
}
if (!$class->isIdentifier($name)) {
$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] = (object)$actualData;
$changeSet = [];
foreach ($actualData as $propName => $actualValue) {
if (!$class->hasAssociation($propName)) {
$changeSet[$propName] = [null, $actualValue];
continue;
}
$assoc = $class->getAssociationMapping($propName);
if ($assoc['isOwningSide'] && $assoc['type'] & ApiMetadata::TO_ONE) {
$changeSet[$propName] = [null, $actualValue];
}
}
$this->entityChangeSets[$oid] = $changeSet;
} else {
// Entity is "fully" MANAGED: it was already fully persisted before
// and we have a copy of the original data
$originalData = $this->originalEntityData[$oid];
$isChangeTrackingNotify = false;
$changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
? $this->entityChangeSets[$oid]
: [];
foreach ($actualData as $propName => $actualValue) {
// skip field, its a partially omitted one!
if (!property_exists($originalData, $propName)) {
continue;
}
$orgValue = $originalData->$propName;
// skip if value haven't changed
if ($orgValue === $actualValue) {
continue;
}
// if regular field
if (!$class->hasAssociation($propName)) {
if ($isChangeTrackingNotify) {
continue;
}
$changeSet[$propName] = [$orgValue, $actualValue];
continue;
}
$assoc = $class->getAssociationMapping($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 ApiCollection) {
$owner = $actualValue->getOwner();
if ($owner === null) { // cloned
$actualValue->setOwner($entity, $assoc);
} else {
if ($owner !== $entity) { // no clone, we have to fix
if (!$actualValue->isInitialized()) {
$actualValue->initialize(); // we have to do this otherwise the cols share state
}
$newValue = clone $actualValue;
$newValue->setOwner($entity, $assoc);
$class->getReflectionProperty($propName)->setValue($entity, $newValue);
}
}
}
if ($orgValue instanceof ApiCollection) {
// A PersistentCollection was de-referenced, so delete it.
$coid = spl_object_hash($orgValue);
if (isset($this->collectionDeletions[$coid])) {
continue;
}
$this->collectionDeletions[$coid] = $orgValue;
$changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
continue;
}
if ($assoc['type'] & ApiMetadata::TO_ONE) {
if ($assoc['isOwningSide']) {
$changeSet[$propName] = [$orgValue, $actualValue];
}
if ($orgValue !== null && $assoc['orphanRemoval']) {
$this->scheduleOrphanRemoval($orgValue);
}
}
}
if ($changeSet) {
$this->entityChangeSets[$oid] = $changeSet;
$this->originalEntityData[$oid] = (object)$actualData;
$this->entityUpdates[$oid] = $entity;
}
}
// Look for changes in associations of the entity
foreach ($class->getAssociationMappings() as $field => $assoc) {
if (($val = $class->getReflectionProperty($field)->getValue($entity)) === null) {
continue;
}
$this->computeAssociationChanges($assoc, $val);
if (!isset($this->entityChangeSets[$oid]) &&
$assoc['isOwningSide'] &&
$assoc['type'] == ApiMetadata::MANY_TO_MANY &&
$val instanceof ApiCollection &&
$val->isDirty()
) {
$this->entityChangeSets[$oid] = [];
$this->originalEntityData[$oid] = (object)$actualData;
$this->entityUpdates[$oid] = $entity;
}
}
}