composer package updates
[openemr.git] / vendor / doctrine / orm / lib / Doctrine / ORM / UnitOfWork.php
blobfcbd3ab942db51e6d72af77005000a664d8d5b62
1 <?php
2 /*
3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\ORM;
22 use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService;
23 use Doctrine\DBAL\LockMode;
24 use Doctrine\ORM\Internal\HydrationCompleteHandler;
25 use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter;
26 use Exception;
27 use InvalidArgumentException;
28 use UnexpectedValueException;
30 use Doctrine\Common\Collections\ArrayCollection;
31 use Doctrine\Common\Collections\Collection;
32 use Doctrine\Common\NotifyPropertyChanged;
33 use Doctrine\Common\PropertyChangedListener;
34 use Doctrine\Common\Persistence\ObjectManagerAware;
35 use Doctrine\ORM\Mapping\ClassMetadata;
36 use Doctrine\ORM\Proxy\Proxy;
38 use Doctrine\ORM\Event\LifecycleEventArgs;
39 use Doctrine\ORM\Event\PreUpdateEventArgs;
40 use Doctrine\ORM\Event\PreFlushEventArgs;
41 use Doctrine\ORM\Event\OnFlushEventArgs;
42 use Doctrine\ORM\Event\PostFlushEventArgs;
43 use Doctrine\ORM\Event\ListenersInvoker;
45 use Doctrine\ORM\Cache\Persister\CachedPersister;
46 use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
47 use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
48 use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
49 use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
50 use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
51 use Doctrine\ORM\Utility\IdentifierFlattener;
52 use Doctrine\ORM\Cache\AssociationCacheEntry;
54 /**
55 * The UnitOfWork is responsible for tracking changes to objects during an
56 * "object-level" transaction and for writing out changes to the database
57 * in the correct order.
59 * Internal note: This class contains highly performance-sensitive code.
61 * @since 2.0
62 * @author Benjamin Eberlei <kontakt@beberlei.de>
63 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
64 * @author Jonathan Wage <jonwage@gmail.com>
65 * @author Roman Borschel <roman@code-factory.org>
66 * @author Rob Caiger <rob@clocal.co.uk>
68 class UnitOfWork implements PropertyChangedListener
70 /**
71 * An entity is in MANAGED state when its persistence is managed by an EntityManager.
73 const STATE_MANAGED = 1;
75 /**
76 * An entity is new if it has just been instantiated (i.e. using the "new" operator)
77 * and is not (yet) managed by an EntityManager.
79 const STATE_NEW = 2;
81 /**
82 * A detached entity is an instance with persistent state and identity that is not
83 * (or no longer) associated with an EntityManager (and a UnitOfWork).
85 const STATE_DETACHED = 3;
87 /**
88 * A removed entity instance is an instance with a persistent identity,
89 * associated with an EntityManager, whose persistent state will be deleted
90 * on commit.
92 const STATE_REMOVED = 4;
94 /**
95 * Hint used to collect all primary keys of associated entities during hydration
96 * and execute it in a dedicated query afterwards
97 * @see https://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#temporarily-change-fetch-mode-in-dql
99 const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
102 * The identity map that holds references to all managed entities that have
103 * an identity. The entities are grouped by their class name.
104 * Since all classes in a hierarchy must share the same identifier set,
105 * we always take the root class name of the hierarchy.
107 * @var array
109 private $identityMap = array();
112 * Map of all identifiers of managed entities.
113 * Keys are object ids (spl_object_hash).
115 * @var array
117 private $entityIdentifiers = array();
120 * Map of the original entity data of managed entities.
121 * Keys are object ids (spl_object_hash). This is used for calculating changesets
122 * at commit time.
124 * Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
125 * A value will only really be copied if the value in the entity is modified
126 * by the user.
128 * @var array
130 private $originalEntityData = array();
133 * Map of entity changes. Keys are object ids (spl_object_hash).
134 * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
136 * @var array
138 private $entityChangeSets = array();
141 * The (cached) states of any known entities.
142 * Keys are object ids (spl_object_hash).
144 * @var array
146 private $entityStates = array();
149 * Map of entities that are scheduled for dirty checking at commit time.
150 * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
151 * Keys are object ids (spl_object_hash).
153 * @var array
155 private $scheduledForSynchronization = array();
158 * A list of all pending entity insertions.
160 * @var array
162 private $entityInsertions = array();
165 * A list of all pending entity updates.
167 * @var array
169 private $entityUpdates = array();
172 * Any pending extra updates that have been scheduled by persisters.
174 * @var array
176 private $extraUpdates = array();
179 * A list of all pending entity deletions.
181 * @var array
183 private $entityDeletions = array();
186 * All pending collection deletions.
188 * @var array
190 private $collectionDeletions = array();
193 * All pending collection updates.
195 * @var array
197 private $collectionUpdates = array();
200 * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
201 * At the end of the UnitOfWork all these collections will make new snapshots
202 * of their data.
204 * @var array
206 private $visitedCollections = array();
209 * The EntityManager that "owns" this UnitOfWork instance.
211 * @var EntityManagerInterface
213 private $em;
216 * The calculator used to calculate the order in which changes to
217 * entities need to be written to the database.
219 * @var \Doctrine\ORM\Internal\CommitOrderCalculator
221 private $commitOrderCalculator;
224 * The entity persister instances used to persist entity instances.
226 * @var array
228 private $persisters = array();
231 * The collection persister instances used to persist collections.
233 * @var array
235 private $collectionPersisters = array();
238 * The EventManager used for dispatching events.
240 * @var \Doctrine\Common\EventManager
242 private $evm;
245 * The ListenersInvoker used for dispatching events.
247 * @var \Doctrine\ORM\Event\ListenersInvoker
249 private $listenersInvoker;
252 * The IdentifierFlattener used for manipulating identifiers
254 * @var \Doctrine\ORM\Utility\IdentifierFlattener
256 private $identifierFlattener;
259 * Orphaned entities that are scheduled for removal.
261 * @var array
263 private $orphanRemovals = array();
266 * Read-Only objects are never evaluated
268 * @var array
270 private $readOnlyObjects = array();
273 * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
275 * @var array
277 private $eagerLoadingEntities = array();
280 * @var boolean
282 protected $hasCache = false;
285 * Helper for handling completion of hydration
287 * @var HydrationCompleteHandler
289 private $hydrationCompleteHandler;
292 * @var ReflectionPropertiesGetter
294 private $reflectionPropertiesGetter;
297 * Initializes a new UnitOfWork instance, bound to the given EntityManager.
299 * @param EntityManagerInterface $em
301 public function __construct(EntityManagerInterface $em)
303 $this->em = $em;
304 $this->evm = $em->getEventManager();
305 $this->listenersInvoker = new ListenersInvoker($em);
306 $this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
307 $this->identifierFlattener = new IdentifierFlattener($this, $em->getMetadataFactory());
308 $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
309 $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
313 * Commits the UnitOfWork, executing all operations that have been postponed
314 * up to this point. The state of all managed entities will be synchronized with
315 * the database.
317 * The operations are executed in the following order:
319 * 1) All entity insertions
320 * 2) All entity updates
321 * 3) All collection deletions
322 * 4) All collection updates
323 * 5) All entity deletions
325 * @param null|object|array $entity
327 * @return void
329 * @throws \Exception
331 public function commit($entity = null)
333 // Raise preFlush
334 if ($this->evm->hasListeners(Events::preFlush)) {
335 $this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
338 // Compute changes done since last commit.
339 if ($entity === null) {
340 $this->computeChangeSets();
341 } elseif (is_object($entity)) {
342 $this->computeSingleEntityChangeSet($entity);
343 } elseif (is_array($entity)) {
344 foreach ($entity as $object) {
345 $this->computeSingleEntityChangeSet($object);
349 if ( ! ($this->entityInsertions ||
350 $this->entityDeletions ||
351 $this->entityUpdates ||
352 $this->collectionUpdates ||
353 $this->collectionDeletions ||
354 $this->orphanRemovals)) {
355 $this->dispatchOnFlushEvent();
356 $this->dispatchPostFlushEvent();
358 return; // Nothing to do.
361 if ($this->orphanRemovals) {
362 foreach ($this->orphanRemovals as $orphan) {
363 $this->remove($orphan);
367 $this->dispatchOnFlushEvent();
369 // Now we need a commit order to maintain referential integrity
370 $commitOrder = $this->getCommitOrder();
372 $conn = $this->em->getConnection();
373 $conn->beginTransaction();
375 try {
376 if ($this->entityInsertions) {
377 foreach ($commitOrder as $class) {
378 $this->executeInserts($class);
382 if ($this->entityUpdates) {
383 foreach ($commitOrder as $class) {
384 $this->executeUpdates($class);
388 // Extra updates that were requested by persisters.
389 if ($this->extraUpdates) {
390 $this->executeExtraUpdates();
393 // Collection deletions (deletions of complete collections)
394 foreach ($this->collectionDeletions as $collectionToDelete) {
395 $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
398 // Collection updates (deleteRows, updateRows, insertRows)
399 foreach ($this->collectionUpdates as $collectionToUpdate) {
400 $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
403 // Entity deletions come last and need to be in reverse commit order
404 if ($this->entityDeletions) {
405 for ($count = count($commitOrder), $i = $count - 1; $i >= 0 && $this->entityDeletions; --$i) {
406 $this->executeDeletions($commitOrder[$i]);
410 $conn->commit();
411 } catch (Exception $e) {
412 $this->em->close();
413 $conn->rollback();
415 $this->afterTransactionRolledBack();
417 throw $e;
420 $this->afterTransactionComplete();
422 // Take new snapshots from visited collections
423 foreach ($this->visitedCollections as $coll) {
424 $coll->takeSnapshot();
427 $this->dispatchPostFlushEvent();
429 // Clear up
430 $this->entityInsertions =
431 $this->entityUpdates =
432 $this->entityDeletions =
433 $this->extraUpdates =
434 $this->entityChangeSets =
435 $this->collectionUpdates =
436 $this->collectionDeletions =
437 $this->visitedCollections =
438 $this->scheduledForSynchronization =
439 $this->orphanRemovals = array();
443 * Computes the changesets of all entities scheduled for insertion.
445 * @return void
447 private function computeScheduleInsertsChangeSets()
449 foreach ($this->entityInsertions as $entity) {
450 $class = $this->em->getClassMetadata(get_class($entity));
452 $this->computeChangeSet($class, $entity);
457 * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
459 * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
460 * 2. Read Only entities are skipped.
461 * 3. Proxies are skipped.
462 * 4. Only if entity is properly managed.
464 * @param object $entity
466 * @return void
468 * @throws \InvalidArgumentException
470 private function computeSingleEntityChangeSet($entity)
472 $state = $this->getEntityState($entity);
474 if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
475 throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity));
478 $class = $this->em->getClassMetadata(get_class($entity));
480 if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
481 $this->persist($entity);
484 // Compute changes for INSERTed entities first. This must always happen even in this case.
485 $this->computeScheduleInsertsChangeSets();
487 if ($class->isReadOnly) {
488 return;
491 // Ignore uninitialized proxy objects
492 if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
493 return;
496 // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
497 $oid = spl_object_hash($entity);
499 if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
500 $this->computeChangeSet($class, $entity);
505 * Executes any extra updates that have been scheduled.
507 private function executeExtraUpdates()
509 foreach ($this->extraUpdates as $oid => $update) {
510 list ($entity, $changeset) = $update;
512 $this->entityChangeSets[$oid] = $changeset;
513 $this->getEntityPersister(get_class($entity))->update($entity);
516 $this->extraUpdates = array();
520 * Gets the changeset for an entity.
522 * @param object $entity
524 * @return array
526 public function getEntityChangeSet($entity)
528 $oid = spl_object_hash($entity);
530 if (isset($this->entityChangeSets[$oid])) {
531 return $this->entityChangeSets[$oid];
534 return array();
538 * Computes the changes that happened to a single entity.
540 * Modifies/populates the following properties:
542 * {@link _originalEntityData}
543 * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
544 * then it was not fetched from the database and therefore we have no original
545 * entity data yet. All of the current entity data is stored as the original entity data.
547 * {@link _entityChangeSets}
548 * The changes detected on all properties of the entity are stored there.
549 * A change is a tuple array where the first entry is the old value and the second
550 * entry is the new value of the property. Changesets are used by persisters
551 * to INSERT/UPDATE the persistent entity state.
553 * {@link _entityUpdates}
554 * If the entity is already fully MANAGED (has been fetched from the database before)
555 * and any changes to its properties are detected, then a reference to the entity is stored
556 * there to mark it for an update.
558 * {@link _collectionDeletions}
559 * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
560 * then this collection is marked for deletion.
562 * @ignore
564 * @internal Don't call from the outside.
566 * @param ClassMetadata $class The class descriptor of the entity.
567 * @param object $entity The entity for which to compute the changes.
569 * @return void
571 public function computeChangeSet(ClassMetadata $class, $entity)
573 $oid = spl_object_hash($entity);
575 if (isset($this->readOnlyObjects[$oid])) {
576 return;
579 if ( ! $class->isInheritanceTypeNone()) {
580 $class = $this->em->getClassMetadata(get_class($entity));
583 $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
585 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
586 $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
589 $actualData = array();
591 foreach ($class->reflFields as $name => $refProp) {
592 $value = $refProp->getValue($entity);
594 if ($class->isCollectionValuedAssociation($name) && $value !== null) {
595 if ($value instanceof PersistentCollection) {
596 if ($value->getOwner() === $entity) {
597 continue;
600 $value = new ArrayCollection($value->getValues());
603 // If $value is not a Collection then use an ArrayCollection.
604 if ( ! $value instanceof Collection) {
605 $value = new ArrayCollection($value);
608 $assoc = $class->associationMappings[$name];
610 // Inject PersistentCollection
611 $value = new PersistentCollection(
612 $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
614 $value->setOwner($entity, $assoc);
615 $value->setDirty( ! $value->isEmpty());
617 $class->reflFields[$name]->setValue($entity, $value);
619 $actualData[$name] = $value;
621 continue;
624 if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
625 $actualData[$name] = $value;
629 if ( ! isset($this->originalEntityData[$oid])) {
630 // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
631 // These result in an INSERT.
632 $this->originalEntityData[$oid] = $actualData;
633 $changeSet = array();
635 foreach ($actualData as $propName => $actualValue) {
636 if ( ! isset($class->associationMappings[$propName])) {
637 $changeSet[$propName] = array(null, $actualValue);
639 continue;
642 $assoc = $class->associationMappings[$propName];
644 if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
645 $changeSet[$propName] = array(null, $actualValue);
649 $this->entityChangeSets[$oid] = $changeSet;
650 } else {
651 // Entity is "fully" MANAGED: it was already fully persisted before
652 // and we have a copy of the original data
653 $originalData = $this->originalEntityData[$oid];
654 $isChangeTrackingNotify = $class->isChangeTrackingNotify();
655 $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
656 ? $this->entityChangeSets[$oid]
657 : array();
659 foreach ($actualData as $propName => $actualValue) {
660 // skip field, its a partially omitted one!
661 if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
662 continue;
665 $orgValue = $originalData[$propName];
667 // skip if value haven't changed
668 if ($orgValue === $actualValue) {
669 continue;
672 // if regular field
673 if ( ! isset($class->associationMappings[$propName])) {
674 if ($isChangeTrackingNotify) {
675 continue;
678 $changeSet[$propName] = array($orgValue, $actualValue);
680 continue;
683 $assoc = $class->associationMappings[$propName];
685 // Persistent collection was exchanged with the "originally"
686 // created one. This can only mean it was cloned and replaced
687 // on another entity.
688 if ($actualValue instanceof PersistentCollection) {
689 $owner = $actualValue->getOwner();
690 if ($owner === null) { // cloned
691 $actualValue->setOwner($entity, $assoc);
692 } else if ($owner !== $entity) { // no clone, we have to fix
693 if (!$actualValue->isInitialized()) {
694 $actualValue->initialize(); // we have to do this otherwise the cols share state
696 $newValue = clone $actualValue;
697 $newValue->setOwner($entity, $assoc);
698 $class->reflFields[$propName]->setValue($entity, $newValue);
702 if ($orgValue instanceof PersistentCollection) {
703 // A PersistentCollection was de-referenced, so delete it.
704 $coid = spl_object_hash($orgValue);
706 if (isset($this->collectionDeletions[$coid])) {
707 continue;
710 $this->collectionDeletions[$coid] = $orgValue;
711 $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
713 continue;
716 if ($assoc['type'] & ClassMetadata::TO_ONE) {
717 if ($assoc['isOwningSide']) {
718 $changeSet[$propName] = array($orgValue, $actualValue);
721 if ($orgValue !== null && $assoc['orphanRemoval']) {
722 $this->scheduleOrphanRemoval($orgValue);
727 if ($changeSet) {
728 $this->entityChangeSets[$oid] = $changeSet;
729 $this->originalEntityData[$oid] = $actualData;
730 $this->entityUpdates[$oid] = $entity;
734 // Look for changes in associations of the entity
735 foreach ($class->associationMappings as $field => $assoc) {
736 if (($val = $class->reflFields[$field]->getValue($entity)) === null) {
737 continue;
740 $this->computeAssociationChanges($assoc, $val);
742 if ( ! isset($this->entityChangeSets[$oid]) &&
743 $assoc['isOwningSide'] &&
744 $assoc['type'] == ClassMetadata::MANY_TO_MANY &&
745 $val instanceof PersistentCollection &&
746 $val->isDirty()) {
748 $this->entityChangeSets[$oid] = array();
749 $this->originalEntityData[$oid] = $actualData;
750 $this->entityUpdates[$oid] = $entity;
756 * Computes all the changes that have been done to entities and collections
757 * since the last commit and stores these changes in the _entityChangeSet map
758 * temporarily for access by the persisters, until the UoW commit is finished.
760 * @return void
762 public function computeChangeSets()
764 // Compute changes for INSERTed entities first. This must always happen.
765 $this->computeScheduleInsertsChangeSets();
767 // Compute changes for other MANAGED entities. Change tracking policies take effect here.
768 foreach ($this->identityMap as $className => $entities) {
769 $class = $this->em->getClassMetadata($className);
771 // Skip class if instances are read-only
772 if ($class->isReadOnly) {
773 continue;
776 // If change tracking is explicit or happens through notification, then only compute
777 // changes on entities of that type that are explicitly marked for synchronization.
778 switch (true) {
779 case ($class->isChangeTrackingDeferredImplicit()):
780 $entitiesToProcess = $entities;
781 break;
783 case (isset($this->scheduledForSynchronization[$className])):
784 $entitiesToProcess = $this->scheduledForSynchronization[$className];
785 break;
787 default:
788 $entitiesToProcess = array();
792 foreach ($entitiesToProcess as $entity) {
793 // Ignore uninitialized proxy objects
794 if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
795 continue;
798 // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
799 $oid = spl_object_hash($entity);
801 if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
802 $this->computeChangeSet($class, $entity);
809 * Computes the changes of an association.
811 * @param array $assoc The association mapping.
812 * @param mixed $value The value of the association.
814 * @throws ORMInvalidArgumentException
815 * @throws ORMException
817 * @return void
819 private function computeAssociationChanges($assoc, $value)
821 if ($value instanceof Proxy && ! $value->__isInitialized__) {
822 return;
825 if ($value instanceof PersistentCollection && $value->isDirty()) {
826 $coid = spl_object_hash($value);
828 $this->collectionUpdates[$coid] = $value;
829 $this->visitedCollections[$coid] = $value;
832 // Look through the entities, and in any of their associations,
833 // for transient (new) entities, recursively. ("Persistence by reachability")
834 // Unwrap. Uninitialized collections will simply be empty.
835 $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? array($value) : $value->unwrap();
836 $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
838 foreach ($unwrappedValue as $key => $entry) {
839 if (! ($entry instanceof $targetClass->name)) {
840 throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry);
843 $state = $this->getEntityState($entry, self::STATE_NEW);
845 if ( ! ($entry instanceof $assoc['targetEntity'])) {
846 throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']);
849 switch ($state) {
850 case self::STATE_NEW:
851 if ( ! $assoc['isCascadePersist']) {
852 throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry);
855 $this->persistNew($targetClass, $entry);
856 $this->computeChangeSet($targetClass, $entry);
857 break;
859 case self::STATE_REMOVED:
860 // Consume the $value as array (it's either an array or an ArrayAccess)
861 // and remove the element from Collection.
862 if ($assoc['type'] & ClassMetadata::TO_MANY) {
863 unset($value[$key]);
865 break;
867 case self::STATE_DETACHED:
868 // Can actually not happen right now as we assume STATE_NEW,
869 // so the exception will be raised from the DBAL layer (constraint violation).
870 throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
871 break;
873 default:
874 // MANAGED associated entities are already taken into account
875 // during changeset calculation anyway, since they are in the identity map.
881 * @param \Doctrine\ORM\Mapping\ClassMetadata $class
882 * @param object $entity
884 * @return void
886 private function persistNew($class, $entity)
888 $oid = spl_object_hash($entity);
889 $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
891 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
892 $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
895 $idGen = $class->idGenerator;
897 if ( ! $idGen->isPostInsertGenerator()) {
898 $idValue = $idGen->generate($this->em, $entity);
900 if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
901 $idValue = array($class->identifier[0] => $idValue);
903 $class->setIdentifierValues($entity, $idValue);
906 $this->entityIdentifiers[$oid] = $idValue;
909 $this->entityStates[$oid] = self::STATE_MANAGED;
911 $this->scheduleForInsert($entity);
915 * INTERNAL:
916 * Computes the changeset of an individual entity, independently of the
917 * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
919 * The passed entity must be a managed entity. If the entity already has a change set
920 * because this method is invoked during a commit cycle then the change sets are added.
921 * whereby changes detected in this method prevail.
923 * @ignore
925 * @param ClassMetadata $class The class descriptor of the entity.
926 * @param object $entity The entity for which to (re)calculate the change set.
928 * @return void
930 * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
932 public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
934 $oid = spl_object_hash($entity);
936 if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
937 throw ORMInvalidArgumentException::entityNotManaged($entity);
940 // skip if change tracking is "NOTIFY"
941 if ($class->isChangeTrackingNotify()) {
942 return;
945 if ( ! $class->isInheritanceTypeNone()) {
946 $class = $this->em->getClassMetadata(get_class($entity));
949 $actualData = array();
951 foreach ($class->reflFields as $name => $refProp) {
952 if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity())
953 && ($name !== $class->versionField)
954 && ! $class->isCollectionValuedAssociation($name)) {
955 $actualData[$name] = $refProp->getValue($entity);
959 if ( ! isset($this->originalEntityData[$oid])) {
960 throw new \RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
963 $originalData = $this->originalEntityData[$oid];
964 $changeSet = array();
966 foreach ($actualData as $propName => $actualValue) {
967 $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
969 if ($orgValue !== $actualValue) {
970 $changeSet[$propName] = array($orgValue, $actualValue);
974 if ($changeSet) {
975 if (isset($this->entityChangeSets[$oid])) {
976 $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
977 } else if ( ! isset($this->entityInsertions[$oid])) {
978 $this->entityChangeSets[$oid] = $changeSet;
979 $this->entityUpdates[$oid] = $entity;
981 $this->originalEntityData[$oid] = $actualData;
986 * Executes all entity insertions for entities of the specified type.
988 * @param \Doctrine\ORM\Mapping\ClassMetadata $class
990 * @return void
992 private function executeInserts($class)
994 $entities = array();
995 $className = $class->name;
996 $persister = $this->getEntityPersister($className);
997 $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
999 foreach ($this->entityInsertions as $oid => $entity) {
1001 if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
1002 continue;
1005 $persister->addInsert($entity);
1007 unset($this->entityInsertions[$oid]);
1009 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1010 $entities[] = $entity;
1014 $postInsertIds = $persister->executeInserts();
1016 if ($postInsertIds) {
1017 // Persister returned post-insert IDs
1018 foreach ($postInsertIds as $postInsertId) {
1019 $id = $postInsertId['generatedId'];
1020 $entity = $postInsertId['entity'];
1021 $oid = spl_object_hash($entity);
1022 $idField = $class->identifier[0];
1024 $class->reflFields[$idField]->setValue($entity, $id);
1026 $this->entityIdentifiers[$oid] = array($idField => $id);
1027 $this->entityStates[$oid] = self::STATE_MANAGED;
1028 $this->originalEntityData[$oid][$idField] = $id;
1030 $this->addToIdentityMap($entity);
1034 foreach ($entities as $entity) {
1035 $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1040 * Executes all entity updates for entities of the specified type.
1042 * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1044 * @return void
1046 private function executeUpdates($class)
1048 $className = $class->name;
1049 $persister = $this->getEntityPersister($className);
1050 $preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
1051 $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
1053 foreach ($this->entityUpdates as $oid => $entity) {
1055 if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
1056 continue;
1059 if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1060 $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->entityChangeSets[$oid]), $preUpdateInvoke);
1061 $this->recomputeSingleEntityChangeSet($class, $entity);
1064 if ( ! empty($this->entityChangeSets[$oid])) {
1065 $persister->update($entity);
1068 unset($this->entityUpdates[$oid]);
1070 if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
1071 $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
1077 * Executes all entity deletions for entities of the specified type.
1079 * @param \Doctrine\ORM\Mapping\ClassMetadata $class
1081 * @return void
1083 private function executeDeletions($class)
1085 $className = $class->name;
1086 $persister = $this->getEntityPersister($className);
1087 $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
1089 foreach ($this->entityDeletions as $oid => $entity) {
1090 if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
1091 continue;
1094 $persister->delete($entity);
1096 unset(
1097 $this->entityDeletions[$oid],
1098 $this->entityIdentifiers[$oid],
1099 $this->originalEntityData[$oid],
1100 $this->entityStates[$oid]
1103 // Entity with this $oid after deletion treated as NEW, even if the $oid
1104 // is obtained by a new entity because the old one went out of scope.
1105 //$this->entityStates[$oid] = self::STATE_NEW;
1106 if ( ! $class->isIdentifierNatural()) {
1107 $class->reflFields[$class->identifier[0]]->setValue($entity, null);
1110 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1111 $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1117 * Gets the commit order.
1119 * @param array|null $entityChangeSet
1121 * @return array
1123 private function getCommitOrder(array $entityChangeSet = null)
1125 if ($entityChangeSet === null) {
1126 $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
1129 $calc = $this->getCommitOrderCalculator();
1131 // See if there are any new classes in the changeset, that are not in the
1132 // commit order graph yet (don't have a node).
1133 // We have to inspect changeSet to be able to correctly build dependencies.
1134 // It is not possible to use IdentityMap here because post inserted ids
1135 // are not yet available.
1136 $newNodes = array();
1138 foreach ($entityChangeSet as $entity) {
1139 $class = $this->em->getClassMetadata(get_class($entity));
1141 if ($calc->hasClass($class->name)) {
1142 continue;
1145 $calc->addClass($class);
1147 $newNodes[] = $class;
1150 // Calculate dependencies for new nodes
1151 while ($class = array_pop($newNodes)) {
1152 foreach ($class->associationMappings as $assoc) {
1153 if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
1154 continue;
1157 $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
1159 if ( ! $calc->hasClass($targetClass->name)) {
1160 $calc->addClass($targetClass);
1162 $newNodes[] = $targetClass;
1165 $calc->addDependency($targetClass, $class);
1167 // If the target class has mapped subclasses, these share the same dependency.
1168 if ( ! $targetClass->subClasses) {
1169 continue;
1172 foreach ($targetClass->subClasses as $subClassName) {
1173 $targetSubClass = $this->em->getClassMetadata($subClassName);
1175 if ( ! $calc->hasClass($subClassName)) {
1176 $calc->addClass($targetSubClass);
1178 $newNodes[] = $targetSubClass;
1181 $calc->addDependency($targetSubClass, $class);
1186 return $calc->getCommitOrder();
1190 * Schedules an entity for insertion into the database.
1191 * If the entity already has an identifier, it will be added to the identity map.
1193 * @param object $entity The entity to schedule for insertion.
1195 * @return void
1197 * @throws ORMInvalidArgumentException
1198 * @throws \InvalidArgumentException
1200 public function scheduleForInsert($entity)
1202 $oid = spl_object_hash($entity);
1204 if (isset($this->entityUpdates[$oid])) {
1205 throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
1208 if (isset($this->entityDeletions[$oid])) {
1209 throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
1211 if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
1212 throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
1215 if (isset($this->entityInsertions[$oid])) {
1216 throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
1219 $this->entityInsertions[$oid] = $entity;
1221 if (isset($this->entityIdentifiers[$oid])) {
1222 $this->addToIdentityMap($entity);
1225 if ($entity instanceof NotifyPropertyChanged) {
1226 $entity->addPropertyChangedListener($this);
1231 * Checks whether an entity is scheduled for insertion.
1233 * @param object $entity
1235 * @return boolean
1237 public function isScheduledForInsert($entity)
1239 return isset($this->entityInsertions[spl_object_hash($entity)]);
1243 * Schedules an entity for being updated.
1245 * @param object $entity The entity to schedule for being updated.
1247 * @return void
1249 * @throws ORMInvalidArgumentException
1251 public function scheduleForUpdate($entity)
1253 $oid = spl_object_hash($entity);
1255 if ( ! isset($this->entityIdentifiers[$oid])) {
1256 throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update");
1259 if (isset($this->entityDeletions[$oid])) {
1260 throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update");
1263 if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
1264 $this->entityUpdates[$oid] = $entity;
1269 * INTERNAL:
1270 * Schedules an extra update that will be executed immediately after the
1271 * regular entity updates within the currently running commit cycle.
1273 * Extra updates for entities are stored as (entity, changeset) tuples.
1275 * @ignore
1277 * @param object $entity The entity for which to schedule an extra update.
1278 * @param array $changeset The changeset of the entity (what to update).
1280 * @return void
1282 public function scheduleExtraUpdate($entity, array $changeset)
1284 $oid = spl_object_hash($entity);
1285 $extraUpdate = array($entity, $changeset);
1287 if (isset($this->extraUpdates[$oid])) {
1288 list($ignored, $changeset2) = $this->extraUpdates[$oid];
1290 $extraUpdate = array($entity, $changeset + $changeset2);
1293 $this->extraUpdates[$oid] = $extraUpdate;
1297 * Checks whether an entity is registered as dirty in the unit of work.
1298 * Note: Is not very useful currently as dirty entities are only registered
1299 * at commit time.
1301 * @param object $entity
1303 * @return boolean
1305 public function isScheduledForUpdate($entity)
1307 return isset($this->entityUpdates[spl_object_hash($entity)]);
1311 * Checks whether an entity is registered to be checked in the unit of work.
1313 * @param object $entity
1315 * @return boolean
1317 public function isScheduledForDirtyCheck($entity)
1319 $rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
1321 return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
1325 * INTERNAL:
1326 * Schedules an entity for deletion.
1328 * @param object $entity
1330 * @return void
1332 public function scheduleForDelete($entity)
1334 $oid = spl_object_hash($entity);
1336 if (isset($this->entityInsertions[$oid])) {
1337 if ($this->isInIdentityMap($entity)) {
1338 $this->removeFromIdentityMap($entity);
1341 unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
1343 return; // entity has not been persisted yet, so nothing more to do.
1346 if ( ! $this->isInIdentityMap($entity)) {
1347 return;
1350 $this->removeFromIdentityMap($entity);
1352 if (isset($this->entityUpdates[$oid])) {
1353 unset($this->entityUpdates[$oid]);
1356 if ( ! isset($this->entityDeletions[$oid])) {
1357 $this->entityDeletions[$oid] = $entity;
1358 $this->entityStates[$oid] = self::STATE_REMOVED;
1363 * Checks whether an entity is registered as removed/deleted with the unit
1364 * of work.
1366 * @param object $entity
1368 * @return boolean
1370 public function isScheduledForDelete($entity)
1372 return isset($this->entityDeletions[spl_object_hash($entity)]);
1376 * Checks whether an entity is scheduled for insertion, update or deletion.
1378 * @param object $entity
1380 * @return boolean
1382 public function isEntityScheduled($entity)
1384 $oid = spl_object_hash($entity);
1386 return isset($this->entityInsertions[$oid])
1387 || isset($this->entityUpdates[$oid])
1388 || isset($this->entityDeletions[$oid]);
1392 * INTERNAL:
1393 * Registers an entity in the identity map.
1394 * Note that entities in a hierarchy are registered with the class name of
1395 * the root entity.
1397 * @ignore
1399 * @param object $entity The entity to register.
1401 * @return boolean TRUE if the registration was successful, FALSE if the identity of
1402 * the entity in question is already managed.
1404 * @throws ORMInvalidArgumentException
1406 public function addToIdentityMap($entity)
1408 $classMetadata = $this->em->getClassMetadata(get_class($entity));
1409 $idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
1411 if ($idHash === '') {
1412 throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity);
1415 $className = $classMetadata->rootEntityName;
1417 if (isset($this->identityMap[$className][$idHash])) {
1418 return false;
1421 $this->identityMap[$className][$idHash] = $entity;
1423 return true;
1427 * Gets the state of an entity with regard to the current unit of work.
1429 * @param object $entity
1430 * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
1431 * This parameter can be set to improve performance of entity state detection
1432 * by potentially avoiding a database lookup if the distinction between NEW and DETACHED
1433 * is either known or does not matter for the caller of the method.
1435 * @return int The entity state.
1437 public function getEntityState($entity, $assume = null)
1439 $oid = spl_object_hash($entity);
1441 if (isset($this->entityStates[$oid])) {
1442 return $this->entityStates[$oid];
1445 if ($assume !== null) {
1446 return $assume;
1449 // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
1450 // Note that you can not remember the NEW or DETACHED state in _entityStates since
1451 // the UoW does not hold references to such objects and the object hash can be reused.
1452 // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
1453 $class = $this->em->getClassMetadata(get_class($entity));
1454 $id = $class->getIdentifierValues($entity);
1456 if ( ! $id) {
1457 return self::STATE_NEW;
1460 if ($class->containsForeignIdentifier) {
1461 $id = $this->identifierFlattener->flattenIdentifier($class, $id);
1464 switch (true) {
1465 case ($class->isIdentifierNatural()):
1466 // Check for a version field, if available, to avoid a db lookup.
1467 if ($class->isVersioned) {
1468 return ($class->getFieldValue($entity, $class->versionField))
1469 ? self::STATE_DETACHED
1470 : self::STATE_NEW;
1473 // Last try before db lookup: check the identity map.
1474 if ($this->tryGetById($id, $class->rootEntityName)) {
1475 return self::STATE_DETACHED;
1478 // db lookup
1479 if ($this->getEntityPersister($class->name)->exists($entity)) {
1480 return self::STATE_DETACHED;
1483 return self::STATE_NEW;
1485 case ( ! $class->idGenerator->isPostInsertGenerator()):
1486 // if we have a pre insert generator we can't be sure that having an id
1487 // really means that the entity exists. We have to verify this through
1488 // the last resort: a db lookup
1490 // Last try before db lookup: check the identity map.
1491 if ($this->tryGetById($id, $class->rootEntityName)) {
1492 return self::STATE_DETACHED;
1495 // db lookup
1496 if ($this->getEntityPersister($class->name)->exists($entity)) {
1497 return self::STATE_DETACHED;
1500 return self::STATE_NEW;
1502 default:
1503 return self::STATE_DETACHED;
1508 * INTERNAL:
1509 * Removes an entity from the identity map. This effectively detaches the
1510 * entity from the persistence management of Doctrine.
1512 * @ignore
1514 * @param object $entity
1516 * @return boolean
1518 * @throws ORMInvalidArgumentException
1520 public function removeFromIdentityMap($entity)
1522 $oid = spl_object_hash($entity);
1523 $classMetadata = $this->em->getClassMetadata(get_class($entity));
1524 $idHash = implode(' ', $this->entityIdentifiers[$oid]);
1526 if ($idHash === '') {
1527 throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map");
1530 $className = $classMetadata->rootEntityName;
1532 if (isset($this->identityMap[$className][$idHash])) {
1533 unset($this->identityMap[$className][$idHash]);
1534 unset($this->readOnlyObjects[$oid]);
1536 //$this->entityStates[$oid] = self::STATE_DETACHED;
1538 return true;
1541 return false;
1545 * INTERNAL:
1546 * Gets an entity in the identity map by its identifier hash.
1548 * @ignore
1550 * @param string $idHash
1551 * @param string $rootClassName
1553 * @return object
1555 public function getByIdHash($idHash, $rootClassName)
1557 return $this->identityMap[$rootClassName][$idHash];
1561 * INTERNAL:
1562 * Tries to get an entity by its identifier hash. If no entity is found for
1563 * the given hash, FALSE is returned.
1565 * @ignore
1567 * @param mixed $idHash (must be possible to cast it to string)
1568 * @param string $rootClassName
1570 * @return object|bool The found entity or FALSE.
1572 public function tryGetByIdHash($idHash, $rootClassName)
1574 $stringIdHash = (string) $idHash;
1576 if (isset($this->identityMap[$rootClassName][$stringIdHash])) {
1577 return $this->identityMap[$rootClassName][$stringIdHash];
1580 return false;
1584 * Checks whether an entity is registered in the identity map of this UnitOfWork.
1586 * @param object $entity
1588 * @return boolean
1590 public function isInIdentityMap($entity)
1592 $oid = spl_object_hash($entity);
1594 if ( ! isset($this->entityIdentifiers[$oid])) {
1595 return false;
1598 $classMetadata = $this->em->getClassMetadata(get_class($entity));
1599 $idHash = implode(' ', $this->entityIdentifiers[$oid]);
1601 if ($idHash === '') {
1602 return false;
1605 return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
1609 * INTERNAL:
1610 * Checks whether an identifier hash exists in the identity map.
1612 * @ignore
1614 * @param string $idHash
1615 * @param string $rootClassName
1617 * @return boolean
1619 public function containsIdHash($idHash, $rootClassName)
1621 return isset($this->identityMap[$rootClassName][$idHash]);
1625 * Persists an entity as part of the current unit of work.
1627 * @param object $entity The entity to persist.
1629 * @return void
1631 public function persist($entity)
1633 $visited = array();
1635 $this->doPersist($entity, $visited);
1639 * Persists an entity as part of the current unit of work.
1641 * This method is internally called during persist() cascades as it tracks
1642 * the already visited entities to prevent infinite recursions.
1644 * @param object $entity The entity to persist.
1645 * @param array $visited The already visited entities.
1647 * @return void
1649 * @throws ORMInvalidArgumentException
1650 * @throws UnexpectedValueException
1652 private function doPersist($entity, array &$visited)
1654 $oid = spl_object_hash($entity);
1656 if (isset($visited[$oid])) {
1657 return; // Prevent infinite recursion
1660 $visited[$oid] = $entity; // Mark visited
1662 $class = $this->em->getClassMetadata(get_class($entity));
1664 // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
1665 // If we would detect DETACHED here we would throw an exception anyway with the same
1666 // consequences (not recoverable/programming error), so just assuming NEW here
1667 // lets us avoid some database lookups for entities with natural identifiers.
1668 $entityState = $this->getEntityState($entity, self::STATE_NEW);
1670 switch ($entityState) {
1671 case self::STATE_MANAGED:
1672 // Nothing to do, except if policy is "deferred explicit"
1673 if ($class->isChangeTrackingDeferredExplicit()) {
1674 $this->scheduleForDirtyCheck($entity);
1676 break;
1678 case self::STATE_NEW:
1679 $this->persistNew($class, $entity);
1680 break;
1682 case self::STATE_REMOVED:
1683 // Entity becomes managed again
1684 unset($this->entityDeletions[$oid]);
1685 $this->addToIdentityMap($entity);
1687 $this->entityStates[$oid] = self::STATE_MANAGED;
1688 break;
1690 case self::STATE_DETACHED:
1691 // Can actually not happen right now since we assume STATE_NEW.
1692 throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted");
1694 default:
1695 throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1698 $this->cascadePersist($entity, $visited);
1702 * Deletes an entity as part of the current unit of work.
1704 * @param object $entity The entity to remove.
1706 * @return void
1708 public function remove($entity)
1710 $visited = array();
1712 $this->doRemove($entity, $visited);
1716 * Deletes an entity as part of the current unit of work.
1718 * This method is internally called during delete() cascades as it tracks
1719 * the already visited entities to prevent infinite recursions.
1721 * @param object $entity The entity to delete.
1722 * @param array $visited The map of the already visited entities.
1724 * @return void
1726 * @throws ORMInvalidArgumentException If the instance is a detached entity.
1727 * @throws UnexpectedValueException
1729 private function doRemove($entity, array &$visited)
1731 $oid = spl_object_hash($entity);
1733 if (isset($visited[$oid])) {
1734 return; // Prevent infinite recursion
1737 $visited[$oid] = $entity; // mark visited
1739 // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
1740 // can cause problems when a lazy proxy has to be initialized for the cascade operation.
1741 $this->cascadeRemove($entity, $visited);
1743 $class = $this->em->getClassMetadata(get_class($entity));
1744 $entityState = $this->getEntityState($entity);
1746 switch ($entityState) {
1747 case self::STATE_NEW:
1748 case self::STATE_REMOVED:
1749 // nothing to do
1750 break;
1752 case self::STATE_MANAGED:
1753 $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
1755 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
1756 $this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
1759 $this->scheduleForDelete($entity);
1760 break;
1762 case self::STATE_DETACHED:
1763 throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed");
1764 default:
1765 throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
1771 * Merges the state of the given detached entity into this UnitOfWork.
1773 * @param object $entity
1775 * @return object The managed copy of the entity.
1777 * @throws OptimisticLockException If the entity uses optimistic locking through a version
1778 * attribute and the version check against the managed copy fails.
1780 * @todo Require active transaction!? OptimisticLockException may result in undefined state!?
1782 public function merge($entity)
1784 $visited = array();
1786 return $this->doMerge($entity, $visited);
1790 * Executes a merge operation on an entity.
1792 * @param object $entity
1793 * @param array $visited
1794 * @param object|null $prevManagedCopy
1795 * @param array|null $assoc
1797 * @return object The managed copy of the entity.
1799 * @throws OptimisticLockException If the entity uses optimistic locking through a version
1800 * attribute and the version check against the managed copy fails.
1801 * @throws ORMInvalidArgumentException If the entity instance is NEW.
1802 * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided
1804 private function doMerge($entity, array &$visited, $prevManagedCopy = null, $assoc = null)
1806 $oid = spl_object_hash($entity);
1808 if (isset($visited[$oid])) {
1809 $managedCopy = $visited[$oid];
1811 if ($prevManagedCopy !== null) {
1812 $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
1815 return $managedCopy;
1818 $class = $this->em->getClassMetadata(get_class($entity));
1820 // First we assume DETACHED, although it can still be NEW but we can avoid
1821 // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
1822 // we need to fetch it from the db anyway in order to merge.
1823 // MANAGED entities are ignored by the merge operation.
1824 $managedCopy = $entity;
1826 if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
1827 // Try to look the entity up in the identity map.
1828 $id = $class->getIdentifierValues($entity);
1830 // If there is no ID, it is actually NEW.
1831 if ( ! $id) {
1832 $managedCopy = $this->newInstance($class);
1834 $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1835 $this->persistNew($class, $managedCopy);
1836 } else {
1837 $flatId = ($class->containsForeignIdentifier)
1838 ? $this->identifierFlattener->flattenIdentifier($class, $id)
1839 : $id;
1841 $managedCopy = $this->tryGetById($flatId, $class->rootEntityName);
1843 if ($managedCopy) {
1844 // We have the entity in-memory already, just make sure its not removed.
1845 if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
1846 throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge");
1848 } else {
1849 // We need to fetch the managed copy in order to merge.
1850 $managedCopy = $this->em->find($class->name, $flatId);
1853 if ($managedCopy === null) {
1854 // If the identifier is ASSIGNED, it is NEW, otherwise an error
1855 // since the managed entity was not found.
1856 if ( ! $class->isIdentifierNatural()) {
1857 throw EntityNotFoundException::fromClassNameAndIdentifier(
1858 $class->getName(),
1859 $this->identifierFlattener->flattenIdentifier($class, $id)
1863 $managedCopy = $this->newInstance($class);
1864 $class->setIdentifierValues($managedCopy, $id);
1866 $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1867 $this->persistNew($class, $managedCopy);
1868 } else {
1869 $this->ensureVersionMatch($class, $entity, $managedCopy);
1870 $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy);
1874 $visited[$oid] = $managedCopy; // mark visited
1876 if ($class->isChangeTrackingDeferredExplicit()) {
1877 $this->scheduleForDirtyCheck($entity);
1881 if ($prevManagedCopy !== null) {
1882 $this->updateAssociationWithMergedEntity($entity, $assoc, $prevManagedCopy, $managedCopy);
1885 // Mark the managed copy visited as well
1886 $visited[spl_object_hash($managedCopy)] = $managedCopy;
1888 $this->cascadeMerge($entity, $managedCopy, $visited);
1890 return $managedCopy;
1894 * @param ClassMetadata $class
1895 * @param object $entity
1896 * @param object $managedCopy
1898 * @return void
1900 * @throws OptimisticLockException
1902 private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy)
1904 if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) {
1905 return;
1908 $reflField = $class->reflFields[$class->versionField];
1909 $managedCopyVersion = $reflField->getValue($managedCopy);
1910 $entityVersion = $reflField->getValue($entity);
1912 // Throw exception if versions don't match.
1913 if ($managedCopyVersion == $entityVersion) {
1914 return;
1917 throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion);
1921 * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
1923 * @param object $entity
1925 * @return bool
1927 private function isLoaded($entity)
1929 return !($entity instanceof Proxy) || $entity->__isInitialized();
1933 * Sets/adds associated managed copies into the previous entity's association field
1935 * @param object $entity
1936 * @param array $association
1937 * @param object $previousManagedCopy
1938 * @param object $managedCopy
1940 * @return void
1942 private function updateAssociationWithMergedEntity($entity, array $association, $previousManagedCopy, $managedCopy)
1944 $assocField = $association['fieldName'];
1945 $prevClass = $this->em->getClassMetadata(get_class($previousManagedCopy));
1947 if ($association['type'] & ClassMetadata::TO_ONE) {
1948 $prevClass->reflFields[$assocField]->setValue($previousManagedCopy, $managedCopy);
1950 return;
1953 $value = $prevClass->reflFields[$assocField]->getValue($previousManagedCopy);
1954 $value[] = $managedCopy;
1956 if ($association['type'] == ClassMetadata::ONE_TO_MANY) {
1957 $class = $this->em->getClassMetadata(get_class($entity));
1959 $class->reflFields[$association['mappedBy']]->setValue($managedCopy, $previousManagedCopy);
1964 * Detaches an entity from the persistence management. It's persistence will
1965 * no longer be managed by Doctrine.
1967 * @param object $entity The entity to detach.
1969 * @return void
1971 public function detach($entity)
1973 $visited = array();
1975 $this->doDetach($entity, $visited);
1979 * Executes a detach operation on the given entity.
1981 * @param object $entity
1982 * @param array $visited
1983 * @param boolean $noCascade if true, don't cascade detach operation.
1985 * @return void
1987 private function doDetach($entity, array &$visited, $noCascade = false)
1989 $oid = spl_object_hash($entity);
1991 if (isset($visited[$oid])) {
1992 return; // Prevent infinite recursion
1995 $visited[$oid] = $entity; // mark visited
1997 switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
1998 case self::STATE_MANAGED:
1999 if ($this->isInIdentityMap($entity)) {
2000 $this->removeFromIdentityMap($entity);
2003 unset(
2004 $this->entityInsertions[$oid],
2005 $this->entityUpdates[$oid],
2006 $this->entityDeletions[$oid],
2007 $this->entityIdentifiers[$oid],
2008 $this->entityStates[$oid],
2009 $this->originalEntityData[$oid]
2011 break;
2012 case self::STATE_NEW:
2013 case self::STATE_DETACHED:
2014 return;
2017 if ( ! $noCascade) {
2018 $this->cascadeDetach($entity, $visited);
2023 * Refreshes the state of the given entity from the database, overwriting
2024 * any local, unpersisted changes.
2026 * @param object $entity The entity to refresh.
2028 * @return void
2030 * @throws InvalidArgumentException If the entity is not MANAGED.
2032 public function refresh($entity)
2034 $visited = array();
2036 $this->doRefresh($entity, $visited);
2040 * Executes a refresh operation on an entity.
2042 * @param object $entity The entity to refresh.
2043 * @param array $visited The already visited entities during cascades.
2045 * @return void
2047 * @throws ORMInvalidArgumentException If the entity is not MANAGED.
2049 private function doRefresh($entity, array &$visited)
2051 $oid = spl_object_hash($entity);
2053 if (isset($visited[$oid])) {
2054 return; // Prevent infinite recursion
2057 $visited[$oid] = $entity; // mark visited
2059 $class = $this->em->getClassMetadata(get_class($entity));
2061 if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
2062 throw ORMInvalidArgumentException::entityNotManaged($entity);
2065 $this->getEntityPersister($class->name)->refresh(
2066 array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
2067 $entity
2070 $this->cascadeRefresh($entity, $visited);
2074 * Cascades a refresh operation to associated entities.
2076 * @param object $entity
2077 * @param array $visited
2079 * @return void
2081 private function cascadeRefresh($entity, array &$visited)
2083 $class = $this->em->getClassMetadata(get_class($entity));
2085 $associationMappings = array_filter(
2086 $class->associationMappings,
2087 function ($assoc) { return $assoc['isCascadeRefresh']; }
2090 foreach ($associationMappings as $assoc) {
2091 $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2093 switch (true) {
2094 case ($relatedEntities instanceof PersistentCollection):
2095 // Unwrap so that foreach() does not initialize
2096 $relatedEntities = $relatedEntities->unwrap();
2097 // break; is commented intentionally!
2099 case ($relatedEntities instanceof Collection):
2100 case (is_array($relatedEntities)):
2101 foreach ($relatedEntities as $relatedEntity) {
2102 $this->doRefresh($relatedEntity, $visited);
2104 break;
2106 case ($relatedEntities !== null):
2107 $this->doRefresh($relatedEntities, $visited);
2108 break;
2110 default:
2111 // Do nothing
2117 * Cascades a detach operation to associated entities.
2119 * @param object $entity
2120 * @param array $visited
2122 * @return void
2124 private function cascadeDetach($entity, array &$visited)
2126 $class = $this->em->getClassMetadata(get_class($entity));
2128 $associationMappings = array_filter(
2129 $class->associationMappings,
2130 function ($assoc) { return $assoc['isCascadeDetach']; }
2133 foreach ($associationMappings as $assoc) {
2134 $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2136 switch (true) {
2137 case ($relatedEntities instanceof PersistentCollection):
2138 // Unwrap so that foreach() does not initialize
2139 $relatedEntities = $relatedEntities->unwrap();
2140 // break; is commented intentionally!
2142 case ($relatedEntities instanceof Collection):
2143 case (is_array($relatedEntities)):
2144 foreach ($relatedEntities as $relatedEntity) {
2145 $this->doDetach($relatedEntity, $visited);
2147 break;
2149 case ($relatedEntities !== null):
2150 $this->doDetach($relatedEntities, $visited);
2151 break;
2153 default:
2154 // Do nothing
2160 * Cascades a merge operation to associated entities.
2162 * @param object $entity
2163 * @param object $managedCopy
2164 * @param array $visited
2166 * @return void
2168 private function cascadeMerge($entity, $managedCopy, array &$visited)
2170 $class = $this->em->getClassMetadata(get_class($entity));
2172 $associationMappings = array_filter(
2173 $class->associationMappings,
2174 function ($assoc) { return $assoc['isCascadeMerge']; }
2177 foreach ($associationMappings as $assoc) {
2178 $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2180 if ($relatedEntities instanceof Collection) {
2181 if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
2182 continue;
2185 if ($relatedEntities instanceof PersistentCollection) {
2186 // Unwrap so that foreach() does not initialize
2187 $relatedEntities = $relatedEntities->unwrap();
2190 foreach ($relatedEntities as $relatedEntity) {
2191 $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
2193 } else if ($relatedEntities !== null) {
2194 $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
2200 * Cascades the save operation to associated entities.
2202 * @param object $entity
2203 * @param array $visited
2205 * @return void
2207 private function cascadePersist($entity, array &$visited)
2209 $class = $this->em->getClassMetadata(get_class($entity));
2211 $associationMappings = array_filter(
2212 $class->associationMappings,
2213 function ($assoc) { return $assoc['isCascadePersist']; }
2216 foreach ($associationMappings as $assoc) {
2217 $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2219 switch (true) {
2220 case ($relatedEntities instanceof PersistentCollection):
2221 // Unwrap so that foreach() does not initialize
2222 $relatedEntities = $relatedEntities->unwrap();
2223 // break; is commented intentionally!
2225 case ($relatedEntities instanceof Collection):
2226 case (is_array($relatedEntities)):
2227 if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) {
2228 throw ORMInvalidArgumentException::invalidAssociation(
2229 $this->em->getClassMetadata($assoc['targetEntity']),
2230 $assoc,
2231 $relatedEntities
2235 foreach ($relatedEntities as $relatedEntity) {
2236 $this->doPersist($relatedEntity, $visited);
2239 break;
2241 case ($relatedEntities !== null):
2242 if (! $relatedEntities instanceof $assoc['targetEntity']) {
2243 throw ORMInvalidArgumentException::invalidAssociation(
2244 $this->em->getClassMetadata($assoc['targetEntity']),
2245 $assoc,
2246 $relatedEntities
2250 $this->doPersist($relatedEntities, $visited);
2251 break;
2253 default:
2254 // Do nothing
2260 * Cascades the delete operation to associated entities.
2262 * @param object $entity
2263 * @param array $visited
2265 * @return void
2267 private function cascadeRemove($entity, array &$visited)
2269 $class = $this->em->getClassMetadata(get_class($entity));
2271 $associationMappings = array_filter(
2272 $class->associationMappings,
2273 function ($assoc) { return $assoc['isCascadeRemove']; }
2276 $entitiesToCascade = array();
2278 foreach ($associationMappings as $assoc) {
2279 if ($entity instanceof Proxy && !$entity->__isInitialized__) {
2280 $entity->__load();
2283 $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2285 switch (true) {
2286 case ($relatedEntities instanceof Collection):
2287 case (is_array($relatedEntities)):
2288 // If its a PersistentCollection initialization is intended! No unwrap!
2289 foreach ($relatedEntities as $relatedEntity) {
2290 $entitiesToCascade[] = $relatedEntity;
2292 break;
2294 case ($relatedEntities !== null):
2295 $entitiesToCascade[] = $relatedEntities;
2296 break;
2298 default:
2299 // Do nothing
2303 foreach ($entitiesToCascade as $relatedEntity) {
2304 $this->doRemove($relatedEntity, $visited);
2309 * Acquire a lock on the given entity.
2311 * @param object $entity
2312 * @param int $lockMode
2313 * @param int $lockVersion
2315 * @return void
2317 * @throws ORMInvalidArgumentException
2318 * @throws TransactionRequiredException
2319 * @throws OptimisticLockException
2321 public function lock($entity, $lockMode, $lockVersion = null)
2323 if ($entity === null) {
2324 throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
2327 if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
2328 throw ORMInvalidArgumentException::entityNotManaged($entity);
2331 $class = $this->em->getClassMetadata(get_class($entity));
2333 switch (true) {
2334 case LockMode::OPTIMISTIC === $lockMode:
2335 if ( ! $class->isVersioned) {
2336 throw OptimisticLockException::notVersioned($class->name);
2339 if ($lockVersion === null) {
2340 return;
2343 if ($entity instanceof Proxy && !$entity->__isInitialized__) {
2344 $entity->__load();
2347 $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
2349 if ($entityVersion != $lockVersion) {
2350 throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
2353 break;
2355 case LockMode::NONE === $lockMode:
2356 case LockMode::PESSIMISTIC_READ === $lockMode:
2357 case LockMode::PESSIMISTIC_WRITE === $lockMode:
2358 if (!$this->em->getConnection()->isTransactionActive()) {
2359 throw TransactionRequiredException::transactionRequired();
2362 $oid = spl_object_hash($entity);
2364 $this->getEntityPersister($class->name)->lock(
2365 array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
2366 $lockMode
2368 break;
2370 default:
2371 // Do nothing
2376 * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
2378 * @return \Doctrine\ORM\Internal\CommitOrderCalculator
2380 public function getCommitOrderCalculator()
2382 if ($this->commitOrderCalculator === null) {
2383 $this->commitOrderCalculator = new Internal\CommitOrderCalculator;
2386 return $this->commitOrderCalculator;
2390 * Clears the UnitOfWork.
2392 * @param string|null $entityName if given, only entities of this type will get detached.
2394 * @return void
2396 public function clear($entityName = null)
2398 if ($entityName === null) {
2399 $this->identityMap =
2400 $this->entityIdentifiers =
2401 $this->originalEntityData =
2402 $this->entityChangeSets =
2403 $this->entityStates =
2404 $this->scheduledForSynchronization =
2405 $this->entityInsertions =
2406 $this->entityUpdates =
2407 $this->entityDeletions =
2408 $this->collectionDeletions =
2409 $this->collectionUpdates =
2410 $this->extraUpdates =
2411 $this->readOnlyObjects =
2412 $this->visitedCollections =
2413 $this->orphanRemovals = array();
2415 if ($this->commitOrderCalculator !== null) {
2416 $this->commitOrderCalculator->clear();
2418 } else {
2419 $this->clearIdentityMapForEntityName($entityName);
2420 $this->clearEntityInsertionsForEntityName($entityName);
2423 if ($this->evm->hasListeners(Events::onClear)) {
2424 $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName));
2429 * INTERNAL:
2430 * Schedules an orphaned entity for removal. The remove() operation will be
2431 * invoked on that entity at the beginning of the next commit of this
2432 * UnitOfWork.
2434 * @ignore
2436 * @param object $entity
2438 * @return void
2440 public function scheduleOrphanRemoval($entity)
2442 $this->orphanRemovals[spl_object_hash($entity)] = $entity;
2446 * INTERNAL:
2447 * Schedules a complete collection for removal when this UnitOfWork commits.
2449 * @param PersistentCollection $coll
2451 * @return void
2453 public function scheduleCollectionDeletion(PersistentCollection $coll)
2455 $coid = spl_object_hash($coll);
2457 // TODO: if $coll is already scheduled for recreation ... what to do?
2458 // Just remove $coll from the scheduled recreations?
2459 if (isset($this->collectionUpdates[$coid])) {
2460 unset($this->collectionUpdates[$coid]);
2463 $this->collectionDeletions[$coid] = $coll;
2467 * @param PersistentCollection $coll
2469 * @return bool
2471 public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2473 return isset($this->collectionDeletions[spl_object_hash($coll)]);
2477 * @param ClassMetadata $class
2479 * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
2481 private function newInstance($class)
2483 $entity = $class->newInstance();
2485 if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) {
2486 $entity->injectObjectManager($this->em, $class);
2489 return $entity;
2493 * INTERNAL:
2494 * Creates an entity. Used for reconstitution of persistent entities.
2496 * Internal note: Highly performance-sensitive method.
2498 * @ignore
2500 * @param string $className The name of the entity class.
2501 * @param array $data The data for the entity.
2502 * @param array $hints Any hints to account for during reconstitution/lookup of the entity.
2504 * @return object The managed entity instance.
2506 * @todo Rename: getOrCreateEntity
2508 public function createEntity($className, array $data, &$hints = array())
2510 $class = $this->em->getClassMetadata($className);
2511 //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]);
2513 $id = $this->identifierFlattener->flattenIdentifier($class, $data);
2514 $idHash = implode(' ', $id);
2516 if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
2517 $entity = $this->identityMap[$class->rootEntityName][$idHash];
2518 $oid = spl_object_hash($entity);
2520 if (
2521 isset($hints[Query::HINT_REFRESH])
2522 && isset($hints[Query::HINT_REFRESH_ENTITY])
2523 && ($unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY]) !== $entity
2524 && $unmanagedProxy instanceof Proxy
2525 && $this->isIdentifierEquals($unmanagedProxy, $entity)
2527 // DDC-1238 - we have a managed instance, but it isn't the provided one.
2528 // Therefore we clear its identifier. Also, we must re-fetch metadata since the
2529 // refreshed object may be anything
2531 foreach ($class->identifier as $fieldName) {
2532 $class->reflFields[$fieldName]->setValue($unmanagedProxy, null);
2535 return $unmanagedProxy;
2538 if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
2539 $entity->__setInitialized(true);
2541 $overrideLocalValues = true;
2543 if ($entity instanceof NotifyPropertyChanged) {
2544 $entity->addPropertyChangedListener($this);
2546 } else {
2547 $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
2549 // If only a specific entity is set to refresh, check that it's the one
2550 if (isset($hints[Query::HINT_REFRESH_ENTITY])) {
2551 $overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity;
2555 if ($overrideLocalValues) {
2556 // inject ObjectManager upon refresh.
2557 if ($entity instanceof ObjectManagerAware) {
2558 $entity->injectObjectManager($this->em, $class);
2561 $this->originalEntityData[$oid] = $data;
2563 } else {
2564 $entity = $this->newInstance($class);
2565 $oid = spl_object_hash($entity);
2567 $this->entityIdentifiers[$oid] = $id;
2568 $this->entityStates[$oid] = self::STATE_MANAGED;
2569 $this->originalEntityData[$oid] = $data;
2571 $this->identityMap[$class->rootEntityName][$idHash] = $entity;
2573 if ($entity instanceof NotifyPropertyChanged) {
2574 $entity->addPropertyChangedListener($this);
2577 $overrideLocalValues = true;
2580 if ( ! $overrideLocalValues) {
2581 return $entity;
2584 foreach ($data as $field => $value) {
2585 if (isset($class->fieldMappings[$field])) {
2586 $class->reflFields[$field]->setValue($entity, $value);
2590 // Loading the entity right here, if its in the eager loading map get rid of it there.
2591 unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
2593 if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
2594 unset($this->eagerLoadingEntities[$class->rootEntityName]);
2597 // Properly initialize any unfetched associations, if partial objects are not allowed.
2598 if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
2599 return $entity;
2602 foreach ($class->associationMappings as $field => $assoc) {
2603 // Check if the association is not among the fetch-joined associations already.
2604 if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
2605 continue;
2608 $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
2610 switch (true) {
2611 case ($assoc['type'] & ClassMetadata::TO_ONE):
2612 if ( ! $assoc['isOwningSide']) {
2614 // use the given entity association
2615 if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2617 $this->originalEntityData[$oid][$field] = $data[$field];
2619 $class->reflFields[$field]->setValue($entity, $data[$field]);
2620 $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity);
2622 continue 2;
2625 // Inverse side of x-to-one can never be lazy
2626 $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
2628 continue 2;
2631 // use the entity association
2632 if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
2633 $class->reflFields[$field]->setValue($entity, $data[$field]);
2634 $this->originalEntityData[$oid][$field] = $data[$field];
2636 continue;
2639 $associatedId = array();
2641 // TODO: Is this even computed right in all cases of composite keys?
2642 foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
2643 $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;
2645 if ($joinColumnValue !== null) {
2646 if ($targetClass->containsForeignIdentifier) {
2647 $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
2648 } else {
2649 $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
2651 } elseif ($targetClass->containsForeignIdentifier
2652 && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true)
2654 // the missing key is part of target's entity primary key
2655 $associatedId = array();
2656 break;
2660 if ( ! $associatedId) {
2661 // Foreign key is NULL
2662 $class->reflFields[$field]->setValue($entity, null);
2663 $this->originalEntityData[$oid][$field] = null;
2665 continue;
2668 if ( ! isset($hints['fetchMode'][$class->name][$field])) {
2669 $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
2672 // Foreign key is set
2673 // Check identity map first
2674 // FIXME: Can break easily with composite keys if join column values are in
2675 // wrong order. The correct order is the one in ClassMetadata#identifier.
2676 $relatedIdHash = implode(' ', $associatedId);
2678 switch (true) {
2679 case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
2680 $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
2682 // If this is an uninitialized proxy, we are deferring eager loads,
2683 // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2684 // then we can append this entity for eager loading!
2685 if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
2686 isset($hints[self::HINT_DEFEREAGERLOAD]) &&
2687 !$targetClass->isIdentifierComposite &&
2688 $newValue instanceof Proxy &&
2689 $newValue->__isInitialized__ === false) {
2691 $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2694 break;
2696 case ($targetClass->subClasses):
2697 // If it might be a subtype, it can not be lazy. There isn't even
2698 // a way to solve this with deferred eager loading, which means putting
2699 // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
2700 $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId);
2701 break;
2703 default:
2704 switch (true) {
2705 // We are negating the condition here. Other cases will assume it is valid!
2706 case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
2707 $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2708 break;
2710 // Deferred eager load only works for single identifier classes
2711 case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite):
2712 // TODO: Is there a faster approach?
2713 $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
2715 $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
2716 break;
2718 default:
2719 // TODO: This is very imperformant, ignore it?
2720 $newValue = $this->em->find($assoc['targetEntity'], $associatedId);
2721 break;
2724 // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
2725 $newValueOid = spl_object_hash($newValue);
2726 $this->entityIdentifiers[$newValueOid] = $associatedId;
2727 $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
2729 if (
2730 $newValue instanceof NotifyPropertyChanged &&
2731 ( ! $newValue instanceof Proxy || $newValue->__isInitialized())
2733 $newValue->addPropertyChangedListener($this);
2735 $this->entityStates[$newValueOid] = self::STATE_MANAGED;
2736 // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
2737 break;
2740 $this->originalEntityData[$oid][$field] = $newValue;
2741 $class->reflFields[$field]->setValue($entity, $newValue);
2743 if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
2744 $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
2745 $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
2748 break;
2750 default:
2751 // Ignore if its a cached collection
2752 if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) {
2753 break;
2756 // use the given collection
2757 if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
2759 $data[$field]->setOwner($entity, $assoc);
2761 $class->reflFields[$field]->setValue($entity, $data[$field]);
2762 $this->originalEntityData[$oid][$field] = $data[$field];
2764 break;
2767 // Inject collection
2768 $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
2769 $pColl->setOwner($entity, $assoc);
2770 $pColl->setInitialized(false);
2772 $reflField = $class->reflFields[$field];
2773 $reflField->setValue($entity, $pColl);
2775 if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
2776 $this->loadCollection($pColl);
2777 $pColl->takeSnapshot();
2780 $this->originalEntityData[$oid][$field] = $pColl;
2781 break;
2785 if ($overrideLocalValues) {
2786 // defer invoking of postLoad event to hydration complete step
2787 $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity);
2790 return $entity;
2794 * @return void
2796 public function triggerEagerLoads()
2798 if ( ! $this->eagerLoadingEntities) {
2799 return;
2802 // avoid infinite recursion
2803 $eagerLoadingEntities = $this->eagerLoadingEntities;
2804 $this->eagerLoadingEntities = array();
2806 foreach ($eagerLoadingEntities as $entityName => $ids) {
2807 if ( ! $ids) {
2808 continue;
2811 $class = $this->em->getClassMetadata($entityName);
2813 $this->getEntityPersister($entityName)->loadAll(
2814 array_combine($class->identifier, array(array_values($ids)))
2820 * Initializes (loads) an uninitialized persistent collection of an entity.
2822 * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
2824 * @return void
2826 * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
2828 public function loadCollection(PersistentCollection $collection)
2830 $assoc = $collection->getMapping();
2831 $persister = $this->getEntityPersister($assoc['targetEntity']);
2833 switch ($assoc['type']) {
2834 case ClassMetadata::ONE_TO_MANY:
2835 $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
2836 break;
2838 case ClassMetadata::MANY_TO_MANY:
2839 $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection);
2840 break;
2843 $collection->setInitialized(true);
2847 * Gets the identity map of the UnitOfWork.
2849 * @return array
2851 public function getIdentityMap()
2853 return $this->identityMap;
2857 * Gets the original data of an entity. The original data is the data that was
2858 * present at the time the entity was reconstituted from the database.
2860 * @param object $entity
2862 * @return array
2864 public function getOriginalEntityData($entity)
2866 $oid = spl_object_hash($entity);
2868 if (isset($this->originalEntityData[$oid])) {
2869 return $this->originalEntityData[$oid];
2872 return array();
2876 * @ignore
2878 * @param object $entity
2879 * @param array $data
2881 * @return void
2883 public function setOriginalEntityData($entity, array $data)
2885 $this->originalEntityData[spl_object_hash($entity)] = $data;
2889 * INTERNAL:
2890 * Sets a property value of the original data array of an entity.
2892 * @ignore
2894 * @param string $oid
2895 * @param string $property
2896 * @param mixed $value
2898 * @return void
2900 public function setOriginalEntityProperty($oid, $property, $value)
2902 $this->originalEntityData[$oid][$property] = $value;
2906 * Gets the identifier of an entity.
2907 * The returned value is always an array of identifier values. If the entity
2908 * has a composite identifier then the identifier values are in the same
2909 * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
2911 * @param object $entity
2913 * @return array The identifier values.
2915 public function getEntityIdentifier($entity)
2917 return $this->entityIdentifiers[spl_object_hash($entity)];
2921 * Processes an entity instance to extract their identifier values.
2923 * @param object $entity The entity instance.
2925 * @return mixed A scalar value.
2927 * @throws \Doctrine\ORM\ORMInvalidArgumentException
2929 public function getSingleIdentifierValue($entity)
2931 $class = $this->em->getClassMetadata(get_class($entity));
2933 if ($class->isIdentifierComposite) {
2934 throw ORMInvalidArgumentException::invalidCompositeIdentifier();
2937 $values = $this->isInIdentityMap($entity)
2938 ? $this->getEntityIdentifier($entity)
2939 : $class->getIdentifierValues($entity);
2941 return isset($values[$class->identifier[0]]) ? $values[$class->identifier[0]] : null;
2945 * Tries to find an entity with the given identifier in the identity map of
2946 * this UnitOfWork.
2948 * @param mixed $id The entity identifier to look for.
2949 * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
2951 * @return object|bool Returns the entity with the specified identifier if it exists in
2952 * this UnitOfWork, FALSE otherwise.
2954 public function tryGetById($id, $rootClassName)
2956 $idHash = implode(' ', (array) $id);
2958 if (isset($this->identityMap[$rootClassName][$idHash])) {
2959 return $this->identityMap[$rootClassName][$idHash];
2962 return false;
2966 * Schedules an entity for dirty-checking at commit-time.
2968 * @param object $entity The entity to schedule for dirty-checking.
2970 * @return void
2972 * @todo Rename: scheduleForSynchronization
2974 public function scheduleForDirtyCheck($entity)
2976 $rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
2978 $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
2982 * Checks whether the UnitOfWork has any pending insertions.
2984 * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
2986 public function hasPendingInsertions()
2988 return ! empty($this->entityInsertions);
2992 * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
2993 * number of entities in the identity map.
2995 * @return integer
2997 public function size()
2999 $countArray = array_map(function ($item) { return count($item); }, $this->identityMap);
3001 return array_sum($countArray);
3005 * Gets the EntityPersister for an Entity.
3007 * @param string $entityName The name of the Entity.
3009 * @return \Doctrine\ORM\Persisters\Entity\EntityPersister
3011 public function getEntityPersister($entityName)
3013 if (isset($this->persisters[$entityName])) {
3014 return $this->persisters[$entityName];
3017 $class = $this->em->getClassMetadata($entityName);
3019 switch (true) {
3020 case ($class->isInheritanceTypeNone()):
3021 $persister = new BasicEntityPersister($this->em, $class);
3022 break;
3024 case ($class->isInheritanceTypeSingleTable()):
3025 $persister = new SingleTablePersister($this->em, $class);
3026 break;
3028 case ($class->isInheritanceTypeJoined()):
3029 $persister = new JoinedSubclassPersister($this->em, $class);
3030 break;
3032 default:
3033 throw new \RuntimeException('No persister found for entity.');
3036 if ($this->hasCache && $class->cache !== null) {
3037 $persister = $this->em->getConfiguration()
3038 ->getSecondLevelCacheConfiguration()
3039 ->getCacheFactory()
3040 ->buildCachedEntityPersister($this->em, $persister, $class);
3043 $this->persisters[$entityName] = $persister;
3045 return $this->persisters[$entityName];
3049 * Gets a collection persister for a collection-valued association.
3051 * @param array $association
3053 * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister
3055 public function getCollectionPersister(array $association)
3057 $role = isset($association['cache'])
3058 ? $association['sourceEntity'] . '::' . $association['fieldName']
3059 : $association['type'];
3061 if (isset($this->collectionPersisters[$role])) {
3062 return $this->collectionPersisters[$role];
3065 $persister = ClassMetadata::ONE_TO_MANY === $association['type']
3066 ? new OneToManyPersister($this->em)
3067 : new ManyToManyPersister($this->em);
3069 if ($this->hasCache && isset($association['cache'])) {
3070 $persister = $this->em->getConfiguration()
3071 ->getSecondLevelCacheConfiguration()
3072 ->getCacheFactory()
3073 ->buildCachedCollectionPersister($this->em, $persister, $association);
3076 $this->collectionPersisters[$role] = $persister;
3078 return $this->collectionPersisters[$role];
3082 * INTERNAL:
3083 * Registers an entity as managed.
3085 * @param object $entity The entity.
3086 * @param array $id The identifier values.
3087 * @param array $data The original entity data.
3089 * @return void
3091 public function registerManaged($entity, array $id, array $data)
3093 $oid = spl_object_hash($entity);
3095 $this->entityIdentifiers[$oid] = $id;
3096 $this->entityStates[$oid] = self::STATE_MANAGED;
3097 $this->originalEntityData[$oid] = $data;
3099 $this->addToIdentityMap($entity);
3101 if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
3102 $entity->addPropertyChangedListener($this);
3107 * INTERNAL:
3108 * Clears the property changeset of the entity with the given OID.
3110 * @param string $oid The entity's OID.
3112 * @return void
3114 public function clearEntityChangeSet($oid)
3116 $this->entityChangeSets[$oid] = array();
3119 /* PropertyChangedListener implementation */
3122 * Notifies this UnitOfWork of a property change in an entity.
3124 * @param object $entity The entity that owns the property.
3125 * @param string $propertyName The name of the property that changed.
3126 * @param mixed $oldValue The old value of the property.
3127 * @param mixed $newValue The new value of the property.
3129 * @return void
3131 public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
3133 $oid = spl_object_hash($entity);
3134 $class = $this->em->getClassMetadata(get_class($entity));
3136 $isAssocField = isset($class->associationMappings[$propertyName]);
3138 if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
3139 return; // ignore non-persistent fields
3142 // Update changeset and mark entity for synchronization
3143 $this->entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue);
3145 if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) {
3146 $this->scheduleForDirtyCheck($entity);
3151 * Gets the currently scheduled entity insertions in this UnitOfWork.
3153 * @return array
3155 public function getScheduledEntityInsertions()
3157 return $this->entityInsertions;
3161 * Gets the currently scheduled entity updates in this UnitOfWork.
3163 * @return array
3165 public function getScheduledEntityUpdates()
3167 return $this->entityUpdates;
3171 * Gets the currently scheduled entity deletions in this UnitOfWork.
3173 * @return array
3175 public function getScheduledEntityDeletions()
3177 return $this->entityDeletions;
3181 * Gets the currently scheduled complete collection deletions
3183 * @return array
3185 public function getScheduledCollectionDeletions()
3187 return $this->collectionDeletions;
3191 * Gets the currently scheduled collection inserts, updates and deletes.
3193 * @return array
3195 public function getScheduledCollectionUpdates()
3197 return $this->collectionUpdates;
3201 * Helper method to initialize a lazy loading proxy or persistent collection.
3203 * @param object $obj
3205 * @return void
3207 public function initializeObject($obj)
3209 if ($obj instanceof Proxy) {
3210 $obj->__load();
3212 return;
3215 if ($obj instanceof PersistentCollection) {
3216 $obj->initialize();
3221 * Helper method to show an object as string.
3223 * @param object $obj
3225 * @return string
3227 private static function objToStr($obj)
3229 return method_exists($obj, '__toString') ? (string)$obj : get_class($obj).'@'.spl_object_hash($obj);
3233 * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
3235 * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
3236 * on this object that might be necessary to perform a correct update.
3238 * @param object $object
3240 * @return void
3242 * @throws ORMInvalidArgumentException
3244 public function markReadOnly($object)
3246 if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
3247 throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3250 $this->readOnlyObjects[spl_object_hash($object)] = true;
3254 * Is this entity read only?
3256 * @param object $object
3258 * @return bool
3260 * @throws ORMInvalidArgumentException
3262 public function isReadOnly($object)
3264 if ( ! is_object($object)) {
3265 throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
3268 return isset($this->readOnlyObjects[spl_object_hash($object)]);
3272 * Perform whatever processing is encapsulated here after completion of the transaction.
3274 private function afterTransactionComplete()
3276 if ( ! $this->hasCache) {
3277 return;
3280 foreach ($this->persisters as $persister) {
3281 if ($persister instanceof CachedPersister) {
3282 $persister->afterTransactionComplete();
3286 foreach ($this->collectionPersisters as $persister) {
3287 if ($persister instanceof CachedPersister) {
3288 $persister->afterTransactionComplete();
3294 * Perform whatever processing is encapsulated here after completion of the rolled-back.
3296 private function afterTransactionRolledBack()
3298 if ( ! $this->hasCache) {
3299 return;
3302 foreach ($this->persisters as $persister) {
3303 if ($persister instanceof CachedPersister) {
3304 $persister->afterTransactionRolledBack();
3308 foreach ($this->collectionPersisters as $persister) {
3309 if ($persister instanceof CachedPersister) {
3310 $persister->afterTransactionRolledBack();
3315 private function dispatchOnFlushEvent()
3317 if ($this->evm->hasListeners(Events::onFlush)) {
3318 $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
3322 private function dispatchPostFlushEvent()
3324 if ($this->evm->hasListeners(Events::postFlush)) {
3325 $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
3330 * Verifies if two given entities actually are the same based on identifier comparison
3332 * @param object $entity1
3333 * @param object $entity2
3335 * @return bool
3337 private function isIdentifierEquals($entity1, $entity2)
3339 if ($entity1 === $entity2) {
3340 return true;
3343 $class = $this->em->getClassMetadata(get_class($entity1));
3345 if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
3346 return false;
3349 $oid1 = spl_object_hash($entity1);
3350 $oid2 = spl_object_hash($entity2);
3352 $id1 = isset($this->entityIdentifiers[$oid1])
3353 ? $this->entityIdentifiers[$oid1]
3354 : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity1));
3355 $id2 = isset($this->entityIdentifiers[$oid2])
3356 ? $this->entityIdentifiers[$oid2]
3357 : $this->identifierFlattener->flattenIdentifier($class, $class->getIdentifierValues($entity2));
3359 return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2);
3363 * @param object $entity
3364 * @param object $managedCopy
3366 * @throws ORMException
3367 * @throws OptimisticLockException
3368 * @throws TransactionRequiredException
3370 private function mergeEntityStateIntoManagedCopy($entity, $managedCopy)
3372 if (! $this->isLoaded($entity)) {
3373 return;
3376 if (! $this->isLoaded($managedCopy)) {
3377 $managedCopy->__load();
3380 $class = $this->em->getClassMetadata(get_class($entity));
3382 foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) {
3383 $name = $prop->name;
3385 $prop->setAccessible(true);
3387 if ( ! isset($class->associationMappings[$name])) {
3388 if ( ! $class->isIdentifier($name)) {
3389 $prop->setValue($managedCopy, $prop->getValue($entity));
3391 } else {
3392 $assoc2 = $class->associationMappings[$name];
3394 if ($assoc2['type'] & ClassMetadata::TO_ONE) {
3395 $other = $prop->getValue($entity);
3396 if ($other === null) {
3397 $prop->setValue($managedCopy, null);
3398 } else {
3399 if ($other instanceof Proxy && !$other->__isInitialized()) {
3400 // do not merge fields marked lazy that have not been fetched.
3401 continue;
3404 if ( ! $assoc2['isCascadeMerge']) {
3405 if ($this->getEntityState($other) === self::STATE_DETACHED) {
3406 $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
3407 $relatedId = $targetClass->getIdentifierValues($other);
3409 if ($targetClass->subClasses) {
3410 $other = $this->em->find($targetClass->name, $relatedId);
3411 } else {
3412 $other = $this->em->getProxyFactory()->getProxy(
3413 $assoc2['targetEntity'],
3414 $relatedId
3416 $this->registerManaged($other, $relatedId, array());
3420 $prop->setValue($managedCopy, $other);
3423 } else {
3424 $mergeCol = $prop->getValue($entity);
3426 if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) {
3427 // do not merge fields marked lazy that have not been fetched.
3428 // keep the lazy persistent collection of the managed copy.
3429 continue;
3432 $managedCol = $prop->getValue($managedCopy);
3434 if ( ! $managedCol) {
3435 $managedCol = new PersistentCollection(
3436 $this->em,
3437 $this->em->getClassMetadata($assoc2['targetEntity']),
3438 new ArrayCollection
3440 $managedCol->setOwner($managedCopy, $assoc2);
3441 $prop->setValue($managedCopy, $managedCol);
3444 if ($assoc2['isCascadeMerge']) {
3445 $managedCol->initialize();
3447 // clear and set dirty a managed collection if its not also the same collection to merge from.
3448 if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
3449 $managedCol->unwrap()->clear();
3450 $managedCol->setDirty(true);
3452 if ($assoc2['isOwningSide']
3453 && $assoc2['type'] == ClassMetadata::MANY_TO_MANY
3454 && $class->isChangeTrackingNotify()
3456 $this->scheduleForDirtyCheck($managedCopy);
3463 if ($class->isChangeTrackingNotify()) {
3464 // Just treat all properties as changed, there is no other choice.
3465 $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
3471 * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
3472 * Unit of work able to fire deferred events, related to loading events here.
3474 * @internal should be called internally from object hydrators
3476 public function hydrationComplete()
3478 $this->hydrationCompleteHandler->hydrationComplete();
3482 * @param string $entityName
3484 private function clearIdentityMapForEntityName($entityName)
3486 if (! isset($this->identityMap[$entityName])) {
3487 return;
3490 $visited = [];
3492 foreach ($this->identityMap[$entityName] as $entity) {
3493 $this->doDetach($entity, $visited, false);
3498 * @param string $entityName
3500 private function clearEntityInsertionsForEntityName($entityName)
3502 foreach ($this->entityInsertions as $hash => $entity) {
3503 if (get_class($entity) === $entityName) {
3504 unset($this->entityInsertions[$hash]);