vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 1814

Open in your IDE?
  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.
  14.  *
  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>.
  18.  */
  19. namespace Doctrine\ORM;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\Common\Collections\Collection;
  22. use Doctrine\DBAL\LockMode;
  23. use Doctrine\ORM\Cache\Persister\CachedPersister;
  24. use Doctrine\ORM\Event\LifecycleEventArgs;
  25. use Doctrine\ORM\Event\ListenersInvoker;
  26. use Doctrine\ORM\Event\OnFlushEventArgs;
  27. use Doctrine\ORM\Event\PostFlushEventArgs;
  28. use Doctrine\ORM\Event\PreFlushEventArgs;
  29. use Doctrine\ORM\Event\PreUpdateEventArgs;
  30. use Doctrine\ORM\Internal\HydrationCompleteHandler;
  31. use Doctrine\ORM\Mapping\ClassMetadata;
  32. use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter;
  33. use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
  34. use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
  35. use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
  36. use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
  37. use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
  38. use Doctrine\ORM\Proxy\Proxy;
  39. use Doctrine\ORM\Utility\IdentifierFlattener;
  40. use Doctrine\Persistence\Mapping\RuntimeReflectionService;
  41. use Doctrine\Persistence\NotifyPropertyChanged;
  42. use Doctrine\Persistence\ObjectManagerAware;
  43. use Doctrine\Persistence\PropertyChangedListener;
  44. use InvalidArgumentException;
  45. use Throwable;
  46. use UnexpectedValueException;
  47. use function get_class;
  48. use function spl_object_hash;
  49. /**
  50.  * The UnitOfWork is responsible for tracking changes to objects during an
  51.  * "object-level" transaction and for writing out changes to the database
  52.  * in the correct order.
  53.  *
  54.  * Internal note: This class contains highly performance-sensitive code.
  55.  *
  56.  * @since       2.0
  57.  * @author      Benjamin Eberlei <kontakt@beberlei.de>
  58.  * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
  59.  * @author      Jonathan Wage <jonwage@gmail.com>
  60.  * @author      Roman Borschel <roman@code-factory.org>
  61.  * @author      Rob Caiger <rob@clocal.co.uk>
  62.  */
  63. class UnitOfWork implements PropertyChangedListener
  64. {
  65.     /**
  66.      * An entity is in MANAGED state when its persistence is managed by an EntityManager.
  67.      */
  68.     const STATE_MANAGED 1;
  69.     /**
  70.      * An entity is new if it has just been instantiated (i.e. using the "new" operator)
  71.      * and is not (yet) managed by an EntityManager.
  72.      */
  73.     const STATE_NEW 2;
  74.     /**
  75.      * A detached entity is an instance with persistent state and identity that is not
  76.      * (or no longer) associated with an EntityManager (and a UnitOfWork).
  77.      */
  78.     const STATE_DETACHED 3;
  79.     /**
  80.      * A removed entity instance is an instance with a persistent identity,
  81.      * associated with an EntityManager, whose persistent state will be deleted
  82.      * on commit.
  83.      */
  84.     const STATE_REMOVED 4;
  85.     /**
  86.      * Hint used to collect all primary keys of associated entities during hydration
  87.      * and execute it in a dedicated query afterwards
  88.      * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql
  89.      */
  90.     const HINT_DEFEREAGERLOAD 'deferEagerLoad';
  91.     /**
  92.      * The identity map that holds references to all managed entities that have
  93.      * an identity. The entities are grouped by their class name.
  94.      * Since all classes in a hierarchy must share the same identifier set,
  95.      * we always take the root class name of the hierarchy.
  96.      *
  97.      * @var array
  98.      */
  99.     private $identityMap = [];
  100.     /**
  101.      * Map of all identifiers of managed entities.
  102.      * Keys are object ids (spl_object_hash).
  103.      *
  104.      * @var array
  105.      */
  106.     private $entityIdentifiers = [];
  107.     /**
  108.      * Map of the original entity data of managed entities.
  109.      * Keys are object ids (spl_object_hash). This is used for calculating changesets
  110.      * at commit time.
  111.      *
  112.      * Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
  113.      *                A value will only really be copied if the value in the entity is modified
  114.      *                by the user.
  115.      *
  116.      * @var array
  117.      */
  118.     private $originalEntityData = [];
  119.     /**
  120.      * Map of entity changes. Keys are object ids (spl_object_hash).
  121.      * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
  122.      *
  123.      * @var array
  124.      */
  125.     private $entityChangeSets = [];
  126.     /**
  127.      * The (cached) states of any known entities.
  128.      * Keys are object ids (spl_object_hash).
  129.      *
  130.      * @var array
  131.      */
  132.     private $entityStates = [];
  133.     /**
  134.      * Map of entities that are scheduled for dirty checking at commit time.
  135.      * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
  136.      * Keys are object ids (spl_object_hash).
  137.      *
  138.      * @var array
  139.      */
  140.     private $scheduledForSynchronization = [];
  141.     /**
  142.      * A list of all pending entity insertions.
  143.      *
  144.      * @var array
  145.      */
  146.     private $entityInsertions = [];
  147.     /**
  148.      * A list of all pending entity updates.
  149.      *
  150.      * @var array
  151.      */
  152.     private $entityUpdates = [];
  153.     /**
  154.      * Any pending extra updates that have been scheduled by persisters.
  155.      *
  156.      * @var array
  157.      */
  158.     private $extraUpdates = [];
  159.     /**
  160.      * A list of all pending entity deletions.
  161.      *
  162.      * @var array
  163.      */
  164.     private $entityDeletions = [];
  165.     /**
  166.      * New entities that were discovered through relationships that were not
  167.      * marked as cascade-persist. During flush, this array is populated and
  168.      * then pruned of any entities that were discovered through a valid
  169.      * cascade-persist path. (Leftovers cause an error.)
  170.      *
  171.      * Keys are OIDs, payload is a two-item array describing the association
  172.      * and the entity.
  173.      *
  174.      * @var object[][]|array[][] indexed by respective object spl_object_hash()
  175.      */
  176.     private $nonCascadedNewDetectedEntities = [];
  177.     /**
  178.      * All pending collection deletions.
  179.      *
  180.      * @var array
  181.      */
  182.     private $collectionDeletions = [];
  183.     /**
  184.      * All pending collection updates.
  185.      *
  186.      * @var array
  187.      */
  188.     private $collectionUpdates = [];
  189.     /**
  190.      * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
  191.      * At the end of the UnitOfWork all these collections will make new snapshots
  192.      * of their data.
  193.      *
  194.      * @var array
  195.      */
  196.     private $visitedCollections = [];
  197.     /**
  198.      * The EntityManager that "owns" this UnitOfWork instance.
  199.      *
  200.      * @var EntityManagerInterface
  201.      */
  202.     private $em;
  203.     /**
  204.      * The entity persister instances used to persist entity instances.
  205.      *
  206.      * @var array
  207.      */
  208.     private $persisters = [];
  209.     /**
  210.      * The collection persister instances used to persist collections.
  211.      *
  212.      * @var array
  213.      */
  214.     private $collectionPersisters = [];
  215.     /**
  216.      * The EventManager used for dispatching events.
  217.      *
  218.      * @var \Doctrine\Common\EventManager
  219.      */
  220.     private $evm;
  221.     /**
  222.      * The ListenersInvoker used for dispatching events.
  223.      *
  224.      * @var \Doctrine\ORM\Event\ListenersInvoker
  225.      */
  226.     private $listenersInvoker;
  227.     /**
  228.      * The IdentifierFlattener used for manipulating identifiers
  229.      *
  230.      * @var \Doctrine\ORM\Utility\IdentifierFlattener
  231.      */
  232.     private $identifierFlattener;
  233.     /**
  234.      * Orphaned entities that are scheduled for removal.
  235.      *
  236.      * @var array
  237.      */
  238.     private $orphanRemovals = [];
  239.     /**
  240.      * Read-Only objects are never evaluated
  241.      *
  242.      * @var array
  243.      */
  244.     private $readOnlyObjects = [];
  245.     /**
  246.      * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
  247.      *
  248.      * @var array
  249.      */
  250.     private $eagerLoadingEntities = [];
  251.     /**
  252.      * @var boolean
  253.      */
  254.     protected $hasCache false;
  255.     /**
  256.      * Helper for handling completion of hydration
  257.      *
  258.      * @var HydrationCompleteHandler
  259.      */
  260.     private $hydrationCompleteHandler;
  261.     /**
  262.      * @var ReflectionPropertiesGetter
  263.      */
  264.     private $reflectionPropertiesGetter;
  265.     /**
  266.      * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  267.      *
  268.      * @param EntityManagerInterface $em
  269.      */
  270.     public function __construct(EntityManagerInterface $em)
  271.     {
  272.         $this->em                         $em;
  273.         $this->evm                        $em->getEventManager();
  274.         $this->listenersInvoker           = new ListenersInvoker($em);
  275.         $this->hasCache                   $em->getConfiguration()->isSecondLevelCacheEnabled();
  276.         $this->identifierFlattener        = new IdentifierFlattener($this$em->getMetadataFactory());
  277.         $this->hydrationCompleteHandler   = new HydrationCompleteHandler($this->listenersInvoker$em);
  278.         $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
  279.     }
  280.     /**
  281.      * Commits the UnitOfWork, executing all operations that have been postponed
  282.      * up to this point. The state of all managed entities will be synchronized with
  283.      * the database.
  284.      *
  285.      * The operations are executed in the following order:
  286.      *
  287.      * 1) All entity insertions
  288.      * 2) All entity updates
  289.      * 3) All collection deletions
  290.      * 4) All collection updates
  291.      * 5) All entity deletions
  292.      *
  293.      * @param null|object|array $entity
  294.      *
  295.      * @return void
  296.      *
  297.      * @throws \Exception
  298.      */
  299.     public function commit($entity null)
  300.     {
  301.         // Raise preFlush
  302.         if ($this->evm->hasListeners(Events::preFlush)) {
  303.             $this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
  304.         }
  305.         // Compute changes done since last commit.
  306.         if (null === $entity) {
  307.             $this->computeChangeSets();
  308.         } elseif (is_object($entity)) {
  309.             $this->computeSingleEntityChangeSet($entity);
  310.         } elseif (is_array($entity)) {
  311.             foreach ($entity as $object) {
  312.                 $this->computeSingleEntityChangeSet($object);
  313.             }
  314.         }
  315.         if ( ! ($this->entityInsertions ||
  316.                 $this->entityDeletions ||
  317.                 $this->entityUpdates ||
  318.                 $this->collectionUpdates ||
  319.                 $this->collectionDeletions ||
  320.                 $this->orphanRemovals)) {
  321.             $this->dispatchOnFlushEvent();
  322.             $this->dispatchPostFlushEvent();
  323.             $this->postCommitCleanup($entity);
  324.             return; // Nothing to do.
  325.         }
  326.         $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
  327.         if ($this->orphanRemovals) {
  328.             foreach ($this->orphanRemovals as $orphan) {
  329.                 $this->remove($orphan);
  330.             }
  331.         }
  332.         $this->dispatchOnFlushEvent();
  333.         // Now we need a commit order to maintain referential integrity
  334.         $commitOrder $this->getCommitOrder();
  335.         $conn $this->em->getConnection();
  336.         $conn->beginTransaction();
  337.         try {
  338.             // Collection deletions (deletions of complete collections)
  339.             foreach ($this->collectionDeletions as $collectionToDelete) {
  340.                 if (! $collectionToDelete instanceof PersistentCollection) {
  341.                     $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
  342.                     continue;
  343.                 }
  344.                 // Deferred explicit tracked collections can be removed only when owning relation was persisted
  345.                 $owner $collectionToDelete->getOwner();
  346.                 if ($this->em->getClassMetadata(get_class($owner))->isChangeTrackingDeferredImplicit() || $this->isScheduledForDirtyCheck($owner)) {
  347.                     $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
  348.                 }
  349.             }
  350.             if ($this->entityInsertions) {
  351.                 foreach ($commitOrder as $class) {
  352.                     $this->executeInserts($class);
  353.                 }
  354.             }
  355.             if ($this->entityUpdates) {
  356.                 foreach ($commitOrder as $class) {
  357.                     $this->executeUpdates($class);
  358.                 }
  359.             }
  360.             // Extra updates that were requested by persisters.
  361.             if ($this->extraUpdates) {
  362.                 $this->executeExtraUpdates();
  363.             }
  364.             // Collection updates (deleteRows, updateRows, insertRows)
  365.             foreach ($this->collectionUpdates as $collectionToUpdate) {
  366.                 $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
  367.             }
  368.             // Entity deletions come last and need to be in reverse commit order
  369.             if ($this->entityDeletions) {
  370.                 for ($count count($commitOrder), $i $count 1$i >= && $this->entityDeletions; --$i) {
  371.                     $this->executeDeletions($commitOrder[$i]);
  372.                 }
  373.             }
  374.             $conn->commit();
  375.         } catch (Throwable $e) {
  376.             $this->em->close();
  377.             $conn->rollBack();
  378.             $this->afterTransactionRolledBack();
  379.             throw $e;
  380.         }
  381.         $this->afterTransactionComplete();
  382.         // Take new snapshots from visited collections
  383.         foreach ($this->visitedCollections as $coll) {
  384.             $coll->takeSnapshot();
  385.         }
  386.         $this->dispatchPostFlushEvent();
  387.         $this->postCommitCleanup($entity);
  388.     }
  389.     /**
  390.      * @param null|object|object[] $entity
  391.      */
  392.     private function postCommitCleanup($entity) : void
  393.     {
  394.         $this->entityInsertions =
  395.         $this->entityUpdates =
  396.         $this->entityDeletions =
  397.         $this->extraUpdates =
  398.         $this->collectionUpdates =
  399.         $this->nonCascadedNewDetectedEntities =
  400.         $this->collectionDeletions =
  401.         $this->visitedCollections =
  402.         $this->orphanRemovals = [];
  403.         if (null === $entity) {
  404.             $this->entityChangeSets $this->scheduledForSynchronization = [];
  405.             return;
  406.         }
  407.         $entities = \is_object($entity)
  408.             ? [$entity]
  409.             : $entity;
  410.         foreach ($entities as $object) {
  411.             $oid spl_object_hash($object);
  412.             $this->clearEntityChangeSet($oid);
  413.             unset($this->scheduledForSynchronization[$this->em->getClassMetadata(\get_class($object))->rootEntityName][$oid]);
  414.         }
  415.     }
  416.     /**
  417.      * Computes the changesets of all entities scheduled for insertion.
  418.      *
  419.      * @return void
  420.      */
  421.     private function computeScheduleInsertsChangeSets()
  422.     {
  423.         foreach ($this->entityInsertions as $entity) {
  424.             $class $this->em->getClassMetadata(get_class($entity));
  425.             $this->computeChangeSet($class$entity);
  426.         }
  427.     }
  428.     /**
  429.      * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
  430.      *
  431.      * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
  432.      * 2. Read Only entities are skipped.
  433.      * 3. Proxies are skipped.
  434.      * 4. Only if entity is properly managed.
  435.      *
  436.      * @param object $entity
  437.      *
  438.      * @return void
  439.      *
  440.      * @throws \InvalidArgumentException
  441.      */
  442.     private function computeSingleEntityChangeSet($entity)
  443.     {
  444.         $state $this->getEntityState($entity);
  445.         if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
  446.             throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " self::objToStr($entity));
  447.         }
  448.         $class $this->em->getClassMetadata(get_class($entity));
  449.         if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
  450.             $this->persist($entity);
  451.         }
  452.         // Compute changes for INSERTed entities first. This must always happen even in this case.
  453.         $this->computeScheduleInsertsChangeSets();
  454.         if ($class->isReadOnly) {
  455.             return;
  456.         }
  457.         // Ignore uninitialized proxy objects
  458.         if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  459.             return;
  460.         }
  461.         // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
  462.         $oid spl_object_hash($entity);
  463.         if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
  464.             $this->computeChangeSet($class$entity);
  465.         }
  466.     }
  467.     /**
  468.      * Executes any extra updates that have been scheduled.
  469.      */
  470.     private function executeExtraUpdates()
  471.     {
  472.         foreach ($this->extraUpdates as $oid => $update) {
  473.             [$entity$changeset] = $update;
  474.             $this->entityChangeSets[$oid] = $changeset;
  475.             $this->getEntityPersister(get_class($entity))->update($entity);
  476.         }
  477.         $this->extraUpdates = [];
  478.     }
  479.     /**
  480.      * Gets the changeset for an entity.
  481.      *
  482.      * @param object $entity
  483.      *
  484.      * @return array
  485.      */
  486.     public function & getEntityChangeSet($entity)
  487.     {
  488.         $oid  spl_object_hash($entity);
  489.         $data = [];
  490.         if (!isset($this->entityChangeSets[$oid])) {
  491.             return $data;
  492.         }
  493.         return $this->entityChangeSets[$oid];
  494.     }
  495.     /**
  496.      * Computes the changes that happened to a single entity.
  497.      *
  498.      * Modifies/populates the following properties:
  499.      *
  500.      * {@link _originalEntityData}
  501.      * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
  502.      * then it was not fetched from the database and therefore we have no original
  503.      * entity data yet. All of the current entity data is stored as the original entity data.
  504.      *
  505.      * {@link _entityChangeSets}
  506.      * The changes detected on all properties of the entity are stored there.
  507.      * A change is a tuple array where the first entry is the old value and the second
  508.      * entry is the new value of the property. Changesets are used by persisters
  509.      * to INSERT/UPDATE the persistent entity state.
  510.      *
  511.      * {@link _entityUpdates}
  512.      * If the entity is already fully MANAGED (has been fetched from the database before)
  513.      * and any changes to its properties are detected, then a reference to the entity is stored
  514.      * there to mark it for an update.
  515.      *
  516.      * {@link _collectionDeletions}
  517.      * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
  518.      * then this collection is marked for deletion.
  519.      *
  520.      * @ignore
  521.      *
  522.      * @internal Don't call from the outside.
  523.      *
  524.      * @param ClassMetadata $class  The class descriptor of the entity.
  525.      * @param object        $entity The entity for which to compute the changes.
  526.      *
  527.      * @return void
  528.      */
  529.     public function computeChangeSet(ClassMetadata $class$entity)
  530.     {
  531.         $oid spl_object_hash($entity);
  532.         if (isset($this->readOnlyObjects[$oid])) {
  533.             return;
  534.         }
  535.         if ( ! $class->isInheritanceTypeNone()) {
  536.             $class $this->em->getClassMetadata(get_class($entity));
  537.         }
  538.         $invoke $this->listenersInvoker->getSubscribedSystems($classEvents::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
  539.         if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  540.             $this->listenersInvoker->invoke($classEvents::preFlush$entity, new PreFlushEventArgs($this->em), $invoke);
  541.         }
  542.         $actualData = [];
  543.         foreach ($class->reflFields as $name => $refProp) {
  544.             $value $refProp->getValue($entity);
  545.             if ($class->isCollectionValuedAssociation($name) && $value !== null) {
  546.                 if ($value instanceof PersistentCollection) {
  547.                     if ($value->getOwner() === $entity) {
  548.                         continue;
  549.                     }
  550.                     $value = new ArrayCollection($value->getValues());
  551.                 }
  552.                 // If $value is not a Collection then use an ArrayCollection.
  553.                 if ( ! $value instanceof Collection) {
  554.                     $value = new ArrayCollection($value);
  555.                 }
  556.                 $assoc $class->associationMappings[$name];
  557.                 // Inject PersistentCollection
  558.                 $value = new PersistentCollection(
  559.                     $this->em$this->em->getClassMetadata($assoc['targetEntity']), $value
  560.                 );
  561.                 $value->setOwner($entity$assoc);
  562.                 $value->setDirty( ! $value->isEmpty());
  563.                 $class->reflFields[$name]->setValue($entity$value);
  564.                 $actualData[$name] = $value;
  565.                 continue;
  566.             }
  567.             if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
  568.                 $actualData[$name] = $value;
  569.             }
  570.         }
  571.         if ( ! isset($this->originalEntityData[$oid])) {
  572.             // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
  573.             // These result in an INSERT.
  574.             $this->originalEntityData[$oid] = $actualData;
  575.             $changeSet = [];
  576.             foreach ($actualData as $propName => $actualValue) {
  577.                 if ( ! isset($class->associationMappings[$propName])) {
  578.                     $changeSet[$propName] = [null$actualValue];
  579.                     continue;
  580.                 }
  581.                 $assoc $class->associationMappings[$propName];
  582.                 if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  583.                     $changeSet[$propName] = [null$actualValue];
  584.                 }
  585.             }
  586.             $this->entityChangeSets[$oid] = $changeSet;
  587.         } else {
  588.             // Entity is "fully" MANAGED: it was already fully persisted before
  589.             // and we have a copy of the original data
  590.             $originalData           $this->originalEntityData[$oid];
  591.             $isChangeTrackingNotify $class->isChangeTrackingNotify();
  592.             $changeSet              = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
  593.                 ? $this->entityChangeSets[$oid]
  594.                 : [];
  595.             foreach ($actualData as $propName => $actualValue) {
  596.                 // skip field, its a partially omitted one!
  597.                 if ( ! (isset($originalData[$propName]) || array_key_exists($propName$originalData))) {
  598.                     continue;
  599.                 }
  600.                 $orgValue $originalData[$propName];
  601.                 // skip if value haven't changed
  602.                 if ($orgValue === $actualValue) {
  603.                     continue;
  604.                 }
  605.                 // if regular field
  606.                 if ( ! isset($class->associationMappings[$propName])) {
  607.                     if ($isChangeTrackingNotify) {
  608.                         continue;
  609.                     }
  610.                     $changeSet[$propName] = [$orgValue$actualValue];
  611.                     continue;
  612.                 }
  613.                 $assoc $class->associationMappings[$propName];
  614.                 // Persistent collection was exchanged with the "originally"
  615.                 // created one. This can only mean it was cloned and replaced
  616.                 // on another entity.
  617.                 if ($actualValue instanceof PersistentCollection) {
  618.                     $owner $actualValue->getOwner();
  619.                     if ($owner === null) { // cloned
  620.                         $actualValue->setOwner($entity$assoc);
  621.                     } else if ($owner !== $entity) { // no clone, we have to fix
  622.                         if (!$actualValue->isInitialized()) {
  623.                             $actualValue->initialize(); // we have to do this otherwise the cols share state
  624.                         }
  625.                         $newValue = clone $actualValue;
  626.                         $newValue->setOwner($entity$assoc);
  627.                         $class->reflFields[$propName]->setValue($entity$newValue);
  628.                     }
  629.                 }
  630.                 if ($orgValue instanceof PersistentCollection) {
  631.                     // A PersistentCollection was de-referenced, so delete it.
  632.                     $coid spl_object_hash($orgValue);
  633.                     if (isset($this->collectionDeletions[$coid])) {
  634.                         continue;
  635.                     }
  636.                     $this->collectionDeletions[$coid] = $orgValue;
  637.                     $changeSet[$propName] = $orgValue// Signal changeset, to-many assocs will be ignored.
  638.                     continue;
  639.                 }
  640.                 if ($assoc['type'] & ClassMetadata::TO_ONE) {
  641.                     if ($assoc['isOwningSide']) {
  642.                         $changeSet[$propName] = [$orgValue$actualValue];
  643.                     }
  644.                     if ($orgValue !== null && $assoc['orphanRemoval']) {
  645.                         $this->scheduleOrphanRemoval($orgValue);
  646.                     }
  647.                 }
  648.             }
  649.             if ($changeSet) {
  650.                 $this->entityChangeSets[$oid]   = $changeSet;
  651.                 $this->originalEntityData[$oid] = $actualData;
  652.                 $this->entityUpdates[$oid]      = $entity;
  653.             }
  654.         }
  655.         // Look for changes in associations of the entity
  656.         foreach ($class->associationMappings as $field => $assoc) {
  657.             if (($val $class->reflFields[$field]->getValue($entity)) === null) {
  658.                 continue;
  659.             }
  660.             $this->computeAssociationChanges($assoc$val);
  661.             if ( ! isset($this->entityChangeSets[$oid]) &&
  662.                 $assoc['isOwningSide'] &&
  663.                 $assoc['type'] == ClassMetadata::MANY_TO_MANY &&
  664.                 $val instanceof PersistentCollection &&
  665.                 $val->isDirty()) {
  666.                 $this->entityChangeSets[$oid]   = [];
  667.                 $this->originalEntityData[$oid] = $actualData;
  668.                 $this->entityUpdates[$oid]      = $entity;
  669.             }
  670.         }
  671.     }
  672.     /**
  673.      * Computes all the changes that have been done to entities and collections
  674.      * since the last commit and stores these changes in the _entityChangeSet map
  675.      * temporarily for access by the persisters, until the UoW commit is finished.
  676.      *
  677.      * @return void
  678.      */
  679.     public function computeChangeSets()
  680.     {
  681.         // Compute changes for INSERTed entities first. This must always happen.
  682.         $this->computeScheduleInsertsChangeSets();
  683.         // Compute changes for other MANAGED entities. Change tracking policies take effect here.
  684.         foreach ($this->identityMap as $className => $entities) {
  685.             $class $this->em->getClassMetadata($className);
  686.             // Skip class if instances are read-only
  687.             if ($class->isReadOnly) {
  688.                 continue;
  689.             }
  690.             // If change tracking is explicit or happens through notification, then only compute
  691.             // changes on entities of that type that are explicitly marked for synchronization.
  692.             switch (true) {
  693.                 case ($class->isChangeTrackingDeferredImplicit()):
  694.                     $entitiesToProcess $entities;
  695.                     break;
  696.                 case (isset($this->scheduledForSynchronization[$className])):
  697.                     $entitiesToProcess $this->scheduledForSynchronization[$className];
  698.                     break;
  699.                 default:
  700.                     $entitiesToProcess = [];
  701.             }
  702.             foreach ($entitiesToProcess as $entity) {
  703.                 // Ignore uninitialized proxy objects
  704.                 if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  705.                     continue;
  706.                 }
  707.                 // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
  708.                 $oid spl_object_hash($entity);
  709.                 if ( ! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
  710.                     $this->computeChangeSet($class$entity);
  711.                 }
  712.             }
  713.         }
  714.     }
  715.     /**
  716.      * Computes the changes of an association.
  717.      *
  718.      * @param array $assoc The association mapping.
  719.      * @param mixed $value The value of the association.
  720.      *
  721.      * @throws ORMInvalidArgumentException
  722.      * @throws ORMException
  723.      *
  724.      * @return void
  725.      */
  726.     private function computeAssociationChanges($assoc$value)
  727.     {
  728.         if ($value instanceof Proxy && ! $value->__isInitialized__) {
  729.             return;
  730.         }
  731.         if ($value instanceof PersistentCollection && $value->isDirty()) {
  732.             $coid spl_object_hash($value);
  733.             $this->collectionUpdates[$coid] = $value;
  734.             $this->visitedCollections[$coid] = $value;
  735.         }
  736.         // Look through the entities, and in any of their associations,
  737.         // for transient (new) entities, recursively. ("Persistence by reachability")
  738.         // Unwrap. Uninitialized collections will simply be empty.
  739.         $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? [$value] : $value->unwrap();
  740.         $targetClass    $this->em->getClassMetadata($assoc['targetEntity']);
  741.         foreach ($unwrappedValue as $key => $entry) {
  742.             if (! ($entry instanceof $targetClass->name)) {
  743.                 throw ORMInvalidArgumentException::invalidAssociation($targetClass$assoc$entry);
  744.             }
  745.             $state $this->getEntityState($entryself::STATE_NEW);
  746.             if ( ! ($entry instanceof $assoc['targetEntity'])) {
  747.                 throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']);
  748.             }
  749.             switch ($state) {
  750.                 case self::STATE_NEW:
  751.                     if ( ! $assoc['isCascadePersist']) {
  752.                         /*
  753.                          * For now just record the details, because this may
  754.                          * not be an issue if we later discover another pathway
  755.                          * through the object-graph where cascade-persistence
  756.                          * is enabled for this object.
  757.                          */
  758.                         $this->nonCascadedNewDetectedEntities[spl_object_hash($entry)] = [$assoc$entry];
  759.                         break;
  760.                     }
  761.                     $this->persistNew($targetClass$entry);
  762.                     $this->computeChangeSet($targetClass$entry);
  763.                     break;
  764.                 case self::STATE_REMOVED:
  765.                     // Consume the $value as array (it's either an array or an ArrayAccess)
  766.                     // and remove the element from Collection.
  767.                     if ($assoc['type'] & ClassMetadata::TO_MANY) {
  768.                         unset($value[$key]);
  769.                     }
  770.                     break;
  771.                 case self::STATE_DETACHED:
  772.                     // Can actually not happen right now as we assume STATE_NEW,
  773.                     // so the exception will be raised from the DBAL layer (constraint violation).
  774.                     throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc$entry);
  775.                     break;
  776.                 default:
  777.                     // MANAGED associated entities are already taken into account
  778.                     // during changeset calculation anyway, since they are in the identity map.
  779.             }
  780.         }
  781.     }
  782.     /**
  783.      * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  784.      * @param object                              $entity
  785.      *
  786.      * @return void
  787.      */
  788.     private function persistNew($class$entity)
  789.     {
  790.         $oid    spl_object_hash($entity);
  791.         $invoke $this->listenersInvoker->getSubscribedSystems($classEvents::prePersist);
  792.         if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  793.             $this->listenersInvoker->invoke($classEvents::prePersist$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  794.         }
  795.         $idGen $class->idGenerator;
  796.         if ( ! $idGen->isPostInsertGenerator()) {
  797.             $idValue $idGen->generate($this->em$entity);
  798.             if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
  799.                 $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class$idValue)];
  800.                 $class->setIdentifierValues($entity$idValue);
  801.             }
  802.             // Some identifiers may be foreign keys to new entities.
  803.             // In this case, we don't have the value yet and should treat it as if we have a post-insert generator
  804.             if (! $this->hasMissingIdsWhichAreForeignKeys($class$idValue)) {
  805.                 $this->entityIdentifiers[$oid] = $idValue;
  806.             }
  807.         }
  808.         $this->entityStates[$oid] = self::STATE_MANAGED;
  809.         $this->scheduleForInsert($entity);
  810.     }
  811.     /**
  812.      * @param mixed[] $idValue
  813.      */
  814.     private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool
  815.     {
  816.         foreach ($idValue as $idField => $idFieldValue) {
  817.             if ($idFieldValue === null && isset($class->associationMappings[$idField])) {
  818.                 return true;
  819.             }
  820.         }
  821.         return false;
  822.     }
  823.     /**
  824.      * INTERNAL:
  825.      * Computes the changeset of an individual entity, independently of the
  826.      * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
  827.      *
  828.      * The passed entity must be a managed entity. If the entity already has a change set
  829.      * because this method is invoked during a commit cycle then the change sets are added.
  830.      * whereby changes detected in this method prevail.
  831.      *
  832.      * @ignore
  833.      *
  834.      * @param ClassMetadata $class  The class descriptor of the entity.
  835.      * @param object        $entity The entity for which to (re)calculate the change set.
  836.      *
  837.      * @return void
  838.      *
  839.      * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
  840.      */
  841.     public function recomputeSingleEntityChangeSet(ClassMetadata $class$entity)
  842.     {
  843.         $oid spl_object_hash($entity);
  844.         if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
  845.             throw ORMInvalidArgumentException::entityNotManaged($entity);
  846.         }
  847.         // skip if change tracking is "NOTIFY"
  848.         if ($class->isChangeTrackingNotify()) {
  849.             return;
  850.         }
  851.         if ( ! $class->isInheritanceTypeNone()) {
  852.             $class $this->em->getClassMetadata(get_class($entity));
  853.         }
  854.         $actualData = [];
  855.         foreach ($class->reflFields as $name => $refProp) {
  856.             if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity())
  857.                 && ($name !== $class->versionField)
  858.                 && ! $class->isCollectionValuedAssociation($name)) {
  859.                 $actualData[$name] = $refProp->getValue($entity);
  860.             }
  861.         }
  862.         if ( ! isset($this->originalEntityData[$oid])) {
  863.             throw new \RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
  864.         }
  865.         $originalData $this->originalEntityData[$oid];
  866.         $changeSet = [];
  867.         foreach ($actualData as $propName => $actualValue) {
  868.             $orgValue $originalData[$propName] ?? null;
  869.             if ($orgValue !== $actualValue) {
  870.                 $changeSet[$propName] = [$orgValue$actualValue];
  871.             }
  872.         }
  873.         if ($changeSet) {
  874.             if (isset($this->entityChangeSets[$oid])) {
  875.                 $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
  876.             } else if ( ! isset($this->entityInsertions[$oid])) {
  877.                 $this->entityChangeSets[$oid] = $changeSet;
  878.                 $this->entityUpdates[$oid]    = $entity;
  879.             }
  880.             $this->originalEntityData[$oid] = $actualData;
  881.         }
  882.     }
  883.     /**
  884.      * Executes all entity insertions for entities of the specified type.
  885.      *
  886.      * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  887.      *
  888.      * @return void
  889.      */
  890.     private function executeInserts($class)
  891.     {
  892.         $entities   = [];
  893.         $className  $class->name;
  894.         $persister  $this->getEntityPersister($className);
  895.         $invoke     $this->listenersInvoker->getSubscribedSystems($classEvents::postPersist);
  896.         $insertionsForClass = [];
  897.         foreach ($this->entityInsertions as $oid => $entity) {
  898.             if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  899.                 continue;
  900.             }
  901.             $insertionsForClass[$oid] = $entity;
  902.             $persister->addInsert($entity);
  903.             unset($this->entityInsertions[$oid]);
  904.             if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  905.                 $entities[] = $entity;
  906.             }
  907.         }
  908.         $postInsertIds $persister->executeInserts();
  909.         if ($postInsertIds) {
  910.             // Persister returned post-insert IDs
  911.             foreach ($postInsertIds as $postInsertId) {
  912.                 $idField $class->getSingleIdentifierFieldName();
  913.                 $idValue $this->convertSingleFieldIdentifierToPHPValue($class$postInsertId['generatedId']);
  914.                 $entity  $postInsertId['entity'];
  915.                 $oid     spl_object_hash($entity);
  916.                 $class->reflFields[$idField]->setValue($entity$idValue);
  917.                 $this->entityIdentifiers[$oid] = [$idField => $idValue];
  918.                 $this->entityStates[$oid] = self::STATE_MANAGED;
  919.                 $this->originalEntityData[$oid][$idField] = $idValue;
  920.                 $this->addToIdentityMap($entity);
  921.             }
  922.         } else {
  923.             foreach ($insertionsForClass as $oid => $entity) {
  924.                 if (! isset($this->entityIdentifiers[$oid])) {
  925.                     //entity was not added to identity map because some identifiers are foreign keys to new entities.
  926.                     //add it now
  927.                     $this->addToEntityIdentifiersAndEntityMap($class$oid$entity);
  928.                 }
  929.             }
  930.         }
  931.         foreach ($entities as $entity) {
  932.             $this->listenersInvoker->invoke($classEvents::postPersist$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  933.         }
  934.     }
  935.     /**
  936.      * @param object $entity
  937.      */
  938.     private function addToEntityIdentifiersAndEntityMap(ClassMetadata $classstring $oid$entity): void
  939.     {
  940.         $identifier = [];
  941.         foreach ($class->getIdentifierFieldNames() as $idField) {
  942.             $value $class->getFieldValue($entity$idField);
  943.             if (isset($class->associationMappings[$idField])) {
  944.                 // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
  945.                 $value $this->getSingleIdentifierValue($value);
  946.             }
  947.             $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value;
  948.         }
  949.         $this->entityStates[$oid]      = self::STATE_MANAGED;
  950.         $this->entityIdentifiers[$oid] = $identifier;
  951.         $this->addToIdentityMap($entity);
  952.     }
  953.     /**
  954.      * Executes all entity updates for entities of the specified type.
  955.      *
  956.      * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  957.      *
  958.      * @return void
  959.      */
  960.     private function executeUpdates($class)
  961.     {
  962.         $className          $class->name;
  963.         $persister          $this->getEntityPersister($className);
  964.         $preUpdateInvoke    $this->listenersInvoker->getSubscribedSystems($classEvents::preUpdate);
  965.         $postUpdateInvoke   $this->listenersInvoker->getSubscribedSystems($classEvents::postUpdate);
  966.         foreach ($this->entityUpdates as $oid => $entity) {
  967.             if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  968.                 continue;
  969.             }
  970.             if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
  971.                 $this->listenersInvoker->invoke($classEvents::preUpdate$entity, new PreUpdateEventArgs($entity$this->em$this->getEntityChangeSet($entity)), $preUpdateInvoke);
  972.                 $this->recomputeSingleEntityChangeSet($class$entity);
  973.             }
  974.             if ( ! empty($this->entityChangeSets[$oid])) {
  975.                 $persister->update($entity);
  976.             }
  977.             unset($this->entityUpdates[$oid]);
  978.             if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
  979.                 $this->listenersInvoker->invoke($classEvents::postUpdate$entity, new LifecycleEventArgs($entity$this->em), $postUpdateInvoke);
  980.             }
  981.         }
  982.     }
  983.     /**
  984.      * Executes all entity deletions for entities of the specified type.
  985.      *
  986.      * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  987.      *
  988.      * @return void
  989.      */
  990.     private function executeDeletions($class)
  991.     {
  992.         $className  $class->name;
  993.         $persister  $this->getEntityPersister($className);
  994.         $invoke     $this->listenersInvoker->getSubscribedSystems($classEvents::postRemove);
  995.         foreach ($this->entityDeletions as $oid => $entity) {
  996.             if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  997.                 continue;
  998.             }
  999.             $persister->delete($entity);
  1000.             unset(
  1001.                 $this->entityDeletions[$oid],
  1002.                 $this->entityIdentifiers[$oid],
  1003.                 $this->originalEntityData[$oid],
  1004.                 $this->entityStates[$oid]
  1005.             );
  1006.             // Entity with this $oid after deletion treated as NEW, even if the $oid
  1007.             // is obtained by a new entity because the old one went out of scope.
  1008.             //$this->entityStates[$oid] = self::STATE_NEW;
  1009.             if ( ! $class->isIdentifierNatural()) {
  1010.                 $class->reflFields[$class->identifier[0]]->setValue($entitynull);
  1011.             }
  1012.             if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  1013.                 $this->listenersInvoker->invoke($classEvents::postRemove$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  1014.             }
  1015.         }
  1016.     }
  1017.     /**
  1018.      * Gets the commit order.
  1019.      *
  1020.      * @param array|null $entityChangeSet
  1021.      *
  1022.      * @return array
  1023.      */
  1024.     private function getCommitOrder(array $entityChangeSet null)
  1025.     {
  1026.         if ($entityChangeSet === null) {
  1027.             $entityChangeSet array_merge($this->entityInsertions$this->entityUpdates$this->entityDeletions);
  1028.         }
  1029.         $calc $this->getCommitOrderCalculator();
  1030.         // See if there are any new classes in the changeset, that are not in the
  1031.         // commit order graph yet (don't have a node).
  1032.         // We have to inspect changeSet to be able to correctly build dependencies.
  1033.         // It is not possible to use IdentityMap here because post inserted ids
  1034.         // are not yet available.
  1035.         $newNodes = [];
  1036.         foreach ($entityChangeSet as $entity) {
  1037.             $class $this->em->getClassMetadata(get_class($entity));
  1038.             if ($calc->hasNode($class->name)) {
  1039.                 continue;
  1040.             }
  1041.             $calc->addNode($class->name$class);
  1042.             $newNodes[] = $class;
  1043.         }
  1044.         // Calculate dependencies for new nodes
  1045.         while ($class array_pop($newNodes)) {
  1046.             foreach ($class->associationMappings as $assoc) {
  1047.                 if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1048.                     continue;
  1049.                 }
  1050.                 $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  1051.                 if ( ! $calc->hasNode($targetClass->name)) {
  1052.                     $calc->addNode($targetClass->name$targetClass);
  1053.                     $newNodes[] = $targetClass;
  1054.                 }
  1055.                 $joinColumns reset($assoc['joinColumns']);
  1056.                 $calc->addDependency($targetClass->name$class->name, (int)empty($joinColumns['nullable']));
  1057.                 // If the target class has mapped subclasses, these share the same dependency.
  1058.                 if ( ! $targetClass->subClasses) {
  1059.                     continue;
  1060.                 }
  1061.                 foreach ($targetClass->subClasses as $subClassName) {
  1062.                     $targetSubClass $this->em->getClassMetadata($subClassName);
  1063.                     if ( ! $calc->hasNode($subClassName)) {
  1064.                         $calc->addNode($targetSubClass->name$targetSubClass);
  1065.                         $newNodes[] = $targetSubClass;
  1066.                     }
  1067.                     $calc->addDependency($targetSubClass->name$class->name1);
  1068.                 }
  1069.             }
  1070.         }
  1071.         return $calc->sort();
  1072.     }
  1073.     /**
  1074.      * Schedules an entity for insertion into the database.
  1075.      * If the entity already has an identifier, it will be added to the identity map.
  1076.      *
  1077.      * @param object $entity The entity to schedule for insertion.
  1078.      *
  1079.      * @return void
  1080.      *
  1081.      * @throws ORMInvalidArgumentException
  1082.      * @throws \InvalidArgumentException
  1083.      */
  1084.     public function scheduleForInsert($entity)
  1085.     {
  1086.         $oid spl_object_hash($entity);
  1087.         if (isset($this->entityUpdates[$oid])) {
  1088.             throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
  1089.         }
  1090.         if (isset($this->entityDeletions[$oid])) {
  1091.             throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
  1092.         }
  1093.         if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1094.             throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
  1095.         }
  1096.         if (isset($this->entityInsertions[$oid])) {
  1097.             throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
  1098.         }
  1099.         $this->entityInsertions[$oid] = $entity;
  1100.         if (isset($this->entityIdentifiers[$oid])) {
  1101.             $this->addToIdentityMap($entity);
  1102.         }
  1103.         if ($entity instanceof NotifyPropertyChanged) {
  1104.             $entity->addPropertyChangedListener($this);
  1105.         }
  1106.     }
  1107.     /**
  1108.      * Checks whether an entity is scheduled for insertion.
  1109.      *
  1110.      * @param object $entity
  1111.      *
  1112.      * @return boolean
  1113.      */
  1114.     public function isScheduledForInsert($entity)
  1115.     {
  1116.         return isset($this->entityInsertions[spl_object_hash($entity)]);
  1117.     }
  1118.     /**
  1119.      * Schedules an entity for being updated.
  1120.      *
  1121.      * @param object $entity The entity to schedule for being updated.
  1122.      *
  1123.      * @return void
  1124.      *
  1125.      * @throws ORMInvalidArgumentException
  1126.      */
  1127.     public function scheduleForUpdate($entity)
  1128.     {
  1129.         $oid spl_object_hash($entity);
  1130.         if ( ! isset($this->entityIdentifiers[$oid])) {
  1131.             throw ORMInvalidArgumentException::entityHasNoIdentity($entity"scheduling for update");
  1132.         }
  1133.         if (isset($this->entityDeletions[$oid])) {
  1134.             throw ORMInvalidArgumentException::entityIsRemoved($entity"schedule for update");
  1135.         }
  1136.         if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1137.             $this->entityUpdates[$oid] = $entity;
  1138.         }
  1139.     }
  1140.     /**
  1141.      * INTERNAL:
  1142.      * Schedules an extra update that will be executed immediately after the
  1143.      * regular entity updates within the currently running commit cycle.
  1144.      *
  1145.      * Extra updates for entities are stored as (entity, changeset) tuples.
  1146.      *
  1147.      * @ignore
  1148.      *
  1149.      * @param object $entity    The entity for which to schedule an extra update.
  1150.      * @param array  $changeset The changeset of the entity (what to update).
  1151.      *
  1152.      * @return void
  1153.      */
  1154.     public function scheduleExtraUpdate($entity, array $changeset)
  1155.     {
  1156.         $oid         spl_object_hash($entity);
  1157.         $extraUpdate = [$entity$changeset];
  1158.         if (isset($this->extraUpdates[$oid])) {
  1159.             [, $changeset2] = $this->extraUpdates[$oid];
  1160.             $extraUpdate = [$entity$changeset $changeset2];
  1161.         }
  1162.         $this->extraUpdates[$oid] = $extraUpdate;
  1163.     }
  1164.     /**
  1165.      * Checks whether an entity is registered as dirty in the unit of work.
  1166.      * Note: Is not very useful currently as dirty entities are only registered
  1167.      * at commit time.
  1168.      *
  1169.      * @param object $entity
  1170.      *
  1171.      * @return boolean
  1172.      */
  1173.     public function isScheduledForUpdate($entity)
  1174.     {
  1175.         return isset($this->entityUpdates[spl_object_hash($entity)]);
  1176.     }
  1177.     /**
  1178.      * Checks whether an entity is registered to be checked in the unit of work.
  1179.      *
  1180.      * @param object $entity
  1181.      *
  1182.      * @return boolean
  1183.      */
  1184.     public function isScheduledForDirtyCheck($entity)
  1185.     {
  1186.         $rootEntityName $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  1187.         return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_hash($entity)]);
  1188.     }
  1189.     /**
  1190.      * INTERNAL:
  1191.      * Schedules an entity for deletion.
  1192.      *
  1193.      * @param object $entity
  1194.      *
  1195.      * @return void
  1196.      */
  1197.     public function scheduleForDelete($entity)
  1198.     {
  1199.         $oid spl_object_hash($entity);
  1200.         if (isset($this->entityInsertions[$oid])) {
  1201.             if ($this->isInIdentityMap($entity)) {
  1202.                 $this->removeFromIdentityMap($entity);
  1203.             }
  1204.             unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
  1205.             return; // entity has not been persisted yet, so nothing more to do.
  1206.         }
  1207.         if ( ! $this->isInIdentityMap($entity)) {
  1208.             return;
  1209.         }
  1210.         $this->removeFromIdentityMap($entity);
  1211.         unset($this->entityUpdates[$oid]);
  1212.         if ( ! isset($this->entityDeletions[$oid])) {
  1213.             $this->entityDeletions[$oid] = $entity;
  1214.             $this->entityStates[$oid]    = self::STATE_REMOVED;
  1215.         }
  1216.     }
  1217.     /**
  1218.      * Checks whether an entity is registered as removed/deleted with the unit
  1219.      * of work.
  1220.      *
  1221.      * @param object $entity
  1222.      *
  1223.      * @return boolean
  1224.      */
  1225.     public function isScheduledForDelete($entity)
  1226.     {
  1227.         return isset($this->entityDeletions[spl_object_hash($entity)]);
  1228.     }
  1229.     /**
  1230.      * Checks whether an entity is scheduled for insertion, update or deletion.
  1231.      *
  1232.      * @param object $entity
  1233.      *
  1234.      * @return boolean
  1235.      */
  1236.     public function isEntityScheduled($entity)
  1237.     {
  1238.         $oid spl_object_hash($entity);
  1239.         return isset($this->entityInsertions[$oid])
  1240.             || isset($this->entityUpdates[$oid])
  1241.             || isset($this->entityDeletions[$oid]);
  1242.     }
  1243.     /**
  1244.      * INTERNAL:
  1245.      * Registers an entity in the identity map.
  1246.      * Note that entities in a hierarchy are registered with the class name of
  1247.      * the root entity.
  1248.      *
  1249.      * @ignore
  1250.      *
  1251.      * @param object $entity The entity to register.
  1252.      *
  1253.      * @return boolean TRUE if the registration was successful, FALSE if the identity of
  1254.      *                 the entity in question is already managed.
  1255.      *
  1256.      * @throws ORMInvalidArgumentException
  1257.      */
  1258.     public function addToIdentityMap($entity)
  1259.     {
  1260.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1261.         $identifier    $this->entityIdentifiers[spl_object_hash($entity)];
  1262.         if (empty($identifier) || in_array(null$identifiertrue)) {
  1263.             throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name$entity);
  1264.         }
  1265.         $idHash    implode(' '$identifier);
  1266.         $className $classMetadata->rootEntityName;
  1267.         if (isset($this->identityMap[$className][$idHash])) {
  1268.             return false;
  1269.         }
  1270.         $this->identityMap[$className][$idHash] = $entity;
  1271.         return true;
  1272.     }
  1273.     /**
  1274.      * Gets the state of an entity with regard to the current unit of work.
  1275.      *
  1276.      * @param object   $entity
  1277.      * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
  1278.      *                         This parameter can be set to improve performance of entity state detection
  1279.      *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
  1280.      *                         is either known or does not matter for the caller of the method.
  1281.      *
  1282.      * @return int The entity state.
  1283.      */
  1284.     public function getEntityState($entity$assume null)
  1285.     {
  1286.         $oid spl_object_hash($entity);
  1287.         if (isset($this->entityStates[$oid])) {
  1288.             return $this->entityStates[$oid];
  1289.         }
  1290.         if ($assume !== null) {
  1291.             return $assume;
  1292.         }
  1293.         // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
  1294.         // Note that you can not remember the NEW or DETACHED state in _entityStates since
  1295.         // the UoW does not hold references to such objects and the object hash can be reused.
  1296.         // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
  1297.         $class $this->em->getClassMetadata(get_class($entity));
  1298.         $id    $class->getIdentifierValues($entity);
  1299.         if ( ! $id) {
  1300.             return self::STATE_NEW;
  1301.         }
  1302.         if ($class->containsForeignIdentifier) {
  1303.             $id $this->identifierFlattener->flattenIdentifier($class$id);
  1304.         }
  1305.         switch (true) {
  1306.             case ($class->isIdentifierNatural()):
  1307.                 // Check for a version field, if available, to avoid a db lookup.
  1308.                 if ($class->isVersioned) {
  1309.                     return ($class->getFieldValue($entity$class->versionField))
  1310.                         ? self::STATE_DETACHED
  1311.                         self::STATE_NEW;
  1312.                 }
  1313.                 // Last try before db lookup: check the identity map.
  1314.                 if ($this->tryGetById($id$class->rootEntityName)) {
  1315.                     return self::STATE_DETACHED;
  1316.                 }
  1317.                 // db lookup
  1318.                 if ($this->getEntityPersister($class->name)->exists($entity)) {
  1319.                     return self::STATE_DETACHED;
  1320.                 }
  1321.                 return self::STATE_NEW;
  1322.             case ( ! $class->idGenerator->isPostInsertGenerator()):
  1323.                 // if we have a pre insert generator we can't be sure that having an id
  1324.                 // really means that the entity exists. We have to verify this through
  1325.                 // the last resort: a db lookup
  1326.                 // Last try before db lookup: check the identity map.
  1327.                 if ($this->tryGetById($id$class->rootEntityName)) {
  1328.                     return self::STATE_DETACHED;
  1329.                 }
  1330.                 // db lookup
  1331.                 if ($this->getEntityPersister($class->name)->exists($entity)) {
  1332.                     return self::STATE_DETACHED;
  1333.                 }
  1334.                 return self::STATE_NEW;
  1335.             default:
  1336.                 return self::STATE_DETACHED;
  1337.         }
  1338.     }
  1339.     /**
  1340.      * INTERNAL:
  1341.      * Removes an entity from the identity map. This effectively detaches the
  1342.      * entity from the persistence management of Doctrine.
  1343.      *
  1344.      * @ignore
  1345.      *
  1346.      * @param object $entity
  1347.      *
  1348.      * @return boolean
  1349.      *
  1350.      * @throws ORMInvalidArgumentException
  1351.      */
  1352.     public function removeFromIdentityMap($entity)
  1353.     {
  1354.         $oid           spl_object_hash($entity);
  1355.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1356.         $idHash        implode(' '$this->entityIdentifiers[$oid]);
  1357.         if ($idHash === '') {
  1358.             throw ORMInvalidArgumentException::entityHasNoIdentity($entity"remove from identity map");
  1359.         }
  1360.         $className $classMetadata->rootEntityName;
  1361.         if (isset($this->identityMap[$className][$idHash])) {
  1362.             unset($this->identityMap[$className][$idHash]);
  1363.             unset($this->readOnlyObjects[$oid]);
  1364.             //$this->entityStates[$oid] = self::STATE_DETACHED;
  1365.             return true;
  1366.         }
  1367.         return false;
  1368.     }
  1369.     /**
  1370.      * INTERNAL:
  1371.      * Gets an entity in the identity map by its identifier hash.
  1372.      *
  1373.      * @ignore
  1374.      *
  1375.      * @param string $idHash
  1376.      * @param string $rootClassName
  1377.      *
  1378.      * @return object
  1379.      */
  1380.     public function getByIdHash($idHash$rootClassName)
  1381.     {
  1382.         return $this->identityMap[$rootClassName][$idHash];
  1383.     }
  1384.     /**
  1385.      * INTERNAL:
  1386.      * Tries to get an entity by its identifier hash. If no entity is found for
  1387.      * the given hash, FALSE is returned.
  1388.      *
  1389.      * @ignore
  1390.      *
  1391.      * @param mixed  $idHash        (must be possible to cast it to string)
  1392.      * @param string $rootClassName
  1393.      *
  1394.      * @return object|bool The found entity or FALSE.
  1395.      */
  1396.     public function tryGetByIdHash($idHash$rootClassName)
  1397.     {
  1398.         $stringIdHash = (string) $idHash;
  1399.         return isset($this->identityMap[$rootClassName][$stringIdHash])
  1400.             ? $this->identityMap[$rootClassName][$stringIdHash]
  1401.             : false;
  1402.     }
  1403.     /**
  1404.      * Checks whether an entity is registered in the identity map of this UnitOfWork.
  1405.      *
  1406.      * @param object $entity
  1407.      *
  1408.      * @return boolean
  1409.      */
  1410.     public function isInIdentityMap($entity)
  1411.     {
  1412.         $oid spl_object_hash($entity);
  1413.         if (empty($this->entityIdentifiers[$oid])) {
  1414.             return false;
  1415.         }
  1416.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1417.         $idHash        implode(' '$this->entityIdentifiers[$oid]);
  1418.         return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
  1419.     }
  1420.     /**
  1421.      * INTERNAL:
  1422.      * Checks whether an identifier hash exists in the identity map.
  1423.      *
  1424.      * @ignore
  1425.      *
  1426.      * @param string $idHash
  1427.      * @param string $rootClassName
  1428.      *
  1429.      * @return boolean
  1430.      */
  1431.     public function containsIdHash($idHash$rootClassName)
  1432.     {
  1433.         return isset($this->identityMap[$rootClassName][$idHash]);
  1434.     }
  1435.     /**
  1436.      * Persists an entity as part of the current unit of work.
  1437.      *
  1438.      * @param object $entity The entity to persist.
  1439.      *
  1440.      * @return void
  1441.      */
  1442.     public function persist($entity)
  1443.     {
  1444.         $visited = [];
  1445.         $this->doPersist($entity$visited);
  1446.     }
  1447.     /**
  1448.      * Persists an entity as part of the current unit of work.
  1449.      *
  1450.      * This method is internally called during persist() cascades as it tracks
  1451.      * the already visited entities to prevent infinite recursions.
  1452.      *
  1453.      * @param object $entity  The entity to persist.
  1454.      * @param array  $visited The already visited entities.
  1455.      *
  1456.      * @return void
  1457.      *
  1458.      * @throws ORMInvalidArgumentException
  1459.      * @throws UnexpectedValueException
  1460.      */
  1461.     private function doPersist($entity, array &$visited)
  1462.     {
  1463.         $oid spl_object_hash($entity);
  1464.         if (isset($visited[$oid])) {
  1465.             return; // Prevent infinite recursion
  1466.         }
  1467.         $visited[$oid] = $entity// Mark visited
  1468.         $class $this->em->getClassMetadata(get_class($entity));
  1469.         // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
  1470.         // If we would detect DETACHED here we would throw an exception anyway with the same
  1471.         // consequences (not recoverable/programming error), so just assuming NEW here
  1472.         // lets us avoid some database lookups for entities with natural identifiers.
  1473.         $entityState $this->getEntityState($entityself::STATE_NEW);
  1474.         switch ($entityState) {
  1475.             case self::STATE_MANAGED:
  1476.                 // Nothing to do, except if policy is "deferred explicit"
  1477.                 if ($class->isChangeTrackingDeferredExplicit()) {
  1478.                     $this->scheduleForDirtyCheck($entity);
  1479.                 }
  1480.                 break;
  1481.             case self::STATE_NEW:
  1482.                 $this->persistNew($class$entity);
  1483.                 break;
  1484.             case self::STATE_REMOVED:
  1485.                 // Entity becomes managed again
  1486.                 unset($this->entityDeletions[$oid]);
  1487.                 $this->addToIdentityMap($entity);
  1488.                 $this->entityStates[$oid] = self::STATE_MANAGED;
  1489.                 break;
  1490.             case self::STATE_DETACHED:
  1491.                 // Can actually not happen right now since we assume STATE_NEW.
  1492.                 throw ORMInvalidArgumentException::detachedEntityCannot($entity"persisted");
  1493.             default:
  1494.                 throw new UnexpectedValueException("Unexpected entity state: $entityState." self::objToStr($entity));
  1495.         }
  1496.         $this->cascadePersist($entity$visited);
  1497.     }
  1498.     /**
  1499.      * Deletes an entity as part of the current unit of work.
  1500.      *
  1501.      * @param object $entity The entity to remove.
  1502.      *
  1503.      * @return void
  1504.      */
  1505.     public function remove($entity)
  1506.     {
  1507.         $visited = [];
  1508.         $this->doRemove($entity$visited);
  1509.     }
  1510.     /**
  1511.      * Deletes an entity as part of the current unit of work.
  1512.      *
  1513.      * This method is internally called during delete() cascades as it tracks
  1514.      * the already visited entities to prevent infinite recursions.
  1515.      *
  1516.      * @param object $entity  The entity to delete.
  1517.      * @param array  $visited The map of the already visited entities.
  1518.      *
  1519.      * @return void
  1520.      *
  1521.      * @throws ORMInvalidArgumentException If the instance is a detached entity.
  1522.      * @throws UnexpectedValueException
  1523.      */
  1524.     private function doRemove($entity, array &$visited)
  1525.     {
  1526.         $oid spl_object_hash($entity);
  1527.         if (isset($visited[$oid])) {
  1528.             return; // Prevent infinite recursion
  1529.         }
  1530.         $visited[$oid] = $entity// mark visited
  1531.         // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
  1532.         // can cause problems when a lazy proxy has to be initialized for the cascade operation.
  1533.         $this->cascadeRemove($entity$visited);
  1534.         $class       $this->em->getClassMetadata(get_class($entity));
  1535.         $entityState $this->getEntityState($entity);
  1536.         switch ($entityState) {
  1537.             case self::STATE_NEW:
  1538.             case self::STATE_REMOVED:
  1539.                 // nothing to do
  1540.                 break;
  1541.             case self::STATE_MANAGED:
  1542.                 $invoke $this->listenersInvoker->getSubscribedSystems($classEvents::preRemove);
  1543.                 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  1544.                     $this->listenersInvoker->invoke($classEvents::preRemove$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  1545.                 }
  1546.                 $this->scheduleForDelete($entity);
  1547.                 break;
  1548.             case self::STATE_DETACHED:
  1549.                 throw ORMInvalidArgumentException::detachedEntityCannot($entity"removed");
  1550.             default:
  1551.                 throw new UnexpectedValueException("Unexpected entity state: $entityState." self::objToStr($entity));
  1552.         }
  1553.     }
  1554.     /**
  1555.      * Merges the state of the given detached entity into this UnitOfWork.
  1556.      *
  1557.      * @param object $entity
  1558.      *
  1559.      * @return object The managed copy of the entity.
  1560.      *
  1561.      * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1562.      *         attribute and the version check against the managed copy fails.
  1563.      *
  1564.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  1565.      */
  1566.     public function merge($entity)
  1567.     {
  1568.         $visited = [];
  1569.         return $this->doMerge($entity$visited);
  1570.     }
  1571.     /**
  1572.      * Executes a merge operation on an entity.
  1573.      *
  1574.      * @param object      $entity
  1575.      * @param array       $visited
  1576.      * @param object|null $prevManagedCopy
  1577.      * @param string[]    $assoc
  1578.      *
  1579.      * @return object The managed copy of the entity.
  1580.      *
  1581.      * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1582.      *         attribute and the version check against the managed copy fails.
  1583.      * @throws ORMInvalidArgumentException If the entity instance is NEW.
  1584.      * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided
  1585.      */
  1586.     private function doMerge($entity, array &$visited$prevManagedCopy null, array $assoc = [])
  1587.     {
  1588.         $oid spl_object_hash($entity);
  1589.         if (isset($visited[$oid])) {
  1590.             $managedCopy $visited[$oid];
  1591.             if ($prevManagedCopy !== null) {
  1592.                 $this->updateAssociationWithMergedEntity($entity$assoc$prevManagedCopy$managedCopy);
  1593.             }
  1594.             return $managedCopy;
  1595.         }
  1596.         $class $this->em->getClassMetadata(get_class($entity));
  1597.         // First we assume DETACHED, although it can still be NEW but we can avoid
  1598.         // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
  1599.         // we need to fetch it from the db anyway in order to merge.
  1600.         // MANAGED entities are ignored by the merge operation.
  1601.         $managedCopy $entity;
  1602.         if ($this->getEntityState($entityself::STATE_DETACHED) !== self::STATE_MANAGED) {
  1603.             // Try to look the entity up in the identity map.
  1604.             $id $class->getIdentifierValues($entity);
  1605.             // If there is no ID, it is actually NEW.
  1606.             if ( ! $id) {
  1607.                 $managedCopy $this->newInstance($class);
  1608.                 $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1609.                 $this->persistNew($class$managedCopy);
  1610.             } else {
  1611.                 $flatId = ($class->containsForeignIdentifier)
  1612.                     ? $this->identifierFlattener->flattenIdentifier($class$id)
  1613.                     : $id;
  1614.                 $managedCopy $this->tryGetById($flatId$class->rootEntityName);
  1615.                 if ($managedCopy) {
  1616.                     // We have the entity in-memory already, just make sure its not removed.
  1617.                     if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
  1618.                         throw ORMInvalidArgumentException::entityIsRemoved($managedCopy"merge");
  1619.                     }
  1620.                 } else {
  1621.                     // We need to fetch the managed copy in order to merge.
  1622.                     $managedCopy $this->em->find($class->name$flatId);
  1623.                 }
  1624.                 if ($managedCopy === null) {
  1625.                     // If the identifier is ASSIGNED, it is NEW, otherwise an error
  1626.                     // since the managed entity was not found.
  1627.                     if ( ! $class->isIdentifierNatural()) {
  1628.                         throw EntityNotFoundException::fromClassNameAndIdentifier(
  1629.                             $class->getName(),
  1630.                             $this->identifierFlattener->flattenIdentifier($class$id)
  1631.                         );
  1632.                     }
  1633.                     $managedCopy $this->newInstance($class);
  1634.                     $class->setIdentifierValues($managedCopy$id);
  1635.                     $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1636.                     $this->persistNew($class$managedCopy);
  1637.                 } else {
  1638.                     $this->ensureVersionMatch($class$entity$managedCopy);
  1639.                     $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1640.                 }
  1641.             }
  1642.             $visited[$oid] = $managedCopy// mark visited
  1643.             if ($class->isChangeTrackingDeferredExplicit()) {
  1644.                 $this->scheduleForDirtyCheck($entity);
  1645.             }
  1646.         }
  1647.         if ($prevManagedCopy !== null) {
  1648.             $this->updateAssociationWithMergedEntity($entity$assoc$prevManagedCopy$managedCopy);
  1649.         }
  1650.         // Mark the managed copy visited as well
  1651.         $visited[spl_object_hash($managedCopy)] = $managedCopy;
  1652.         $this->cascadeMerge($entity$managedCopy$visited);
  1653.         return $managedCopy;
  1654.     }
  1655.     /**
  1656.      * @param ClassMetadata $class
  1657.      * @param object        $entity
  1658.      * @param object        $managedCopy
  1659.      *
  1660.      * @return void
  1661.      *
  1662.      * @throws OptimisticLockException
  1663.      */
  1664.     private function ensureVersionMatch(ClassMetadata $class$entity$managedCopy)
  1665.     {
  1666.         if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) {
  1667.             return;
  1668.         }
  1669.         $reflField          $class->reflFields[$class->versionField];
  1670.         $managedCopyVersion $reflField->getValue($managedCopy);
  1671.         $entityVersion      $reflField->getValue($entity);
  1672.         // Throw exception if versions don't match.
  1673.         if ($managedCopyVersion == $entityVersion) {
  1674.             return;
  1675.         }
  1676.         throw OptimisticLockException::lockFailedVersionMismatch($entity$entityVersion$managedCopyVersion);
  1677.     }
  1678.     /**
  1679.      * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
  1680.      *
  1681.      * @param object $entity
  1682.      *
  1683.      * @return bool
  1684.      */
  1685.     private function isLoaded($entity)
  1686.     {
  1687.         return !($entity instanceof Proxy) || $entity->__isInitialized();
  1688.     }
  1689.     /**
  1690.      * Sets/adds associated managed copies into the previous entity's association field
  1691.      *
  1692.      * @param object $entity
  1693.      * @param array  $association
  1694.      * @param object $previousManagedCopy
  1695.      * @param object $managedCopy
  1696.      *
  1697.      * @return void
  1698.      */
  1699.     private function updateAssociationWithMergedEntity($entity, array $association$previousManagedCopy$managedCopy)
  1700.     {
  1701.         $assocField $association['fieldName'];
  1702.         $prevClass  $this->em->getClassMetadata(get_class($previousManagedCopy));
  1703.         if ($association['type'] & ClassMetadata::TO_ONE) {
  1704.             $prevClass->reflFields[$assocField]->setValue($previousManagedCopy$managedCopy);
  1705.             return;
  1706.         }
  1707.         $value   $prevClass->reflFields[$assocField]->getValue($previousManagedCopy);
  1708.         $value[] = $managedCopy;
  1709.         if ($association['type'] == ClassMetadata::ONE_TO_MANY) {
  1710.             $class $this->em->getClassMetadata(get_class($entity));
  1711.             $class->reflFields[$association['mappedBy']]->setValue($managedCopy$previousManagedCopy);
  1712.         }
  1713.     }
  1714.     /**
  1715.      * Detaches an entity from the persistence management. It's persistence will
  1716.      * no longer be managed by Doctrine.
  1717.      *
  1718.      * @param object $entity The entity to detach.
  1719.      *
  1720.      * @return void
  1721.      *
  1722.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  1723.      */
  1724.     public function detach($entity)
  1725.     {
  1726.         $visited = [];
  1727.         $this->doDetach($entity$visited);
  1728.     }
  1729.     /**
  1730.      * Executes a detach operation on the given entity.
  1731.      *
  1732.      * @param object  $entity
  1733.      * @param array   $visited
  1734.      * @param boolean $noCascade if true, don't cascade detach operation.
  1735.      *
  1736.      * @return void
  1737.      */
  1738.     private function doDetach($entity, array &$visited$noCascade false)
  1739.     {
  1740.         $oid spl_object_hash($entity);
  1741.         if (isset($visited[$oid])) {
  1742.             return; // Prevent infinite recursion
  1743.         }
  1744.         $visited[$oid] = $entity// mark visited
  1745.         switch ($this->getEntityState($entityself::STATE_DETACHED)) {
  1746.             case self::STATE_MANAGED:
  1747.                 if ($this->isInIdentityMap($entity)) {
  1748.                     $this->removeFromIdentityMap($entity);
  1749.                 }
  1750.                 unset(
  1751.                     $this->entityInsertions[$oid],
  1752.                     $this->entityUpdates[$oid],
  1753.                     $this->entityDeletions[$oid],
  1754.                     $this->entityIdentifiers[$oid],
  1755.                     $this->entityStates[$oid],
  1756.                     $this->originalEntityData[$oid]
  1757.                 );
  1758.                 break;
  1759.             case self::STATE_NEW:
  1760.             case self::STATE_DETACHED:
  1761.                 return;
  1762.         }
  1763.         if ( ! $noCascade) {
  1764.             $this->cascadeDetach($entity$visited);
  1765.         }
  1766.     }
  1767.     /**
  1768.      * Refreshes the state of the given entity from the database, overwriting
  1769.      * any local, unpersisted changes.
  1770.      *
  1771.      * @param object $entity The entity to refresh.
  1772.      *
  1773.      * @return void
  1774.      *
  1775.      * @throws InvalidArgumentException If the entity is not MANAGED.
  1776.      */
  1777.     public function refresh($entity)
  1778.     {
  1779.         $visited = [];
  1780.         $this->doRefresh($entity$visited);
  1781.     }
  1782.     /**
  1783.      * Executes a refresh operation on an entity.
  1784.      *
  1785.      * @param object $entity  The entity to refresh.
  1786.      * @param array  $visited The already visited entities during cascades.
  1787.      *
  1788.      * @return void
  1789.      *
  1790.      * @throws ORMInvalidArgumentException If the entity is not MANAGED.
  1791.      */
  1792.     private function doRefresh($entity, array &$visited)
  1793.     {
  1794.         $oid spl_object_hash($entity);
  1795.         if (isset($visited[$oid])) {
  1796.             return; // Prevent infinite recursion
  1797.         }
  1798.         $visited[$oid] = $entity// mark visited
  1799.         $class $this->em->getClassMetadata(get_class($entity));
  1800.         if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
  1801.             throw ORMInvalidArgumentException::entityNotManaged($entity);
  1802.         }
  1803.         $this->getEntityPersister($class->name)->refresh(
  1804.             array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1805.             $entity
  1806.         );
  1807.         $this->cascadeRefresh($entity$visited);
  1808.     }
  1809.     /**
  1810.      * Cascades a refresh operation to associated entities.
  1811.      *
  1812.      * @param object $entity
  1813.      * @param array  $visited
  1814.      *
  1815.      * @return void
  1816.      */
  1817.     private function cascadeRefresh($entity, array &$visited)
  1818.     {
  1819.         $class $this->em->getClassMetadata(get_class($entity));
  1820.         $associationMappings array_filter(
  1821.             $class->associationMappings,
  1822.             function ($assoc) { return $assoc['isCascadeRefresh']; }
  1823.         );
  1824.         foreach ($associationMappings as $assoc) {
  1825.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1826.             switch (true) {
  1827.                 case ($relatedEntities instanceof PersistentCollection):
  1828.                     // Unwrap so that foreach() does not initialize
  1829.                     $relatedEntities $relatedEntities->unwrap();
  1830.                     // break; is commented intentionally!
  1831.                 case ($relatedEntities instanceof Collection):
  1832.                 case (is_array($relatedEntities)):
  1833.                     foreach ($relatedEntities as $relatedEntity) {
  1834.                         $this->doRefresh($relatedEntity$visited);
  1835.                     }
  1836.                     break;
  1837.                 case ($relatedEntities !== null):
  1838.                     $this->doRefresh($relatedEntities$visited);
  1839.                     break;
  1840.                 default:
  1841.                     // Do nothing
  1842.             }
  1843.         }
  1844.     }
  1845.     /**
  1846.      * Cascades a detach operation to associated entities.
  1847.      *
  1848.      * @param object $entity
  1849.      * @param array  $visited
  1850.      *
  1851.      * @return void
  1852.      */
  1853.     private function cascadeDetach($entity, array &$visited)
  1854.     {
  1855.         $class $this->em->getClassMetadata(get_class($entity));
  1856.         $associationMappings array_filter(
  1857.             $class->associationMappings,
  1858.             function ($assoc) { return $assoc['isCascadeDetach']; }
  1859.         );
  1860.         foreach ($associationMappings as $assoc) {
  1861.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1862.             switch (true) {
  1863.                 case ($relatedEntities instanceof PersistentCollection):
  1864.                     // Unwrap so that foreach() does not initialize
  1865.                     $relatedEntities $relatedEntities->unwrap();
  1866.                     // break; is commented intentionally!
  1867.                 case ($relatedEntities instanceof Collection):
  1868.                 case (is_array($relatedEntities)):
  1869.                     foreach ($relatedEntities as $relatedEntity) {
  1870.                         $this->doDetach($relatedEntity$visited);
  1871.                     }
  1872.                     break;
  1873.                 case ($relatedEntities !== null):
  1874.                     $this->doDetach($relatedEntities$visited);
  1875.                     break;
  1876.                 default:
  1877.                     // Do nothing
  1878.             }
  1879.         }
  1880.     }
  1881.     /**
  1882.      * Cascades a merge operation to associated entities.
  1883.      *
  1884.      * @param object $entity
  1885.      * @param object $managedCopy
  1886.      * @param array  $visited
  1887.      *
  1888.      * @return void
  1889.      */
  1890.     private function cascadeMerge($entity$managedCopy, array &$visited)
  1891.     {
  1892.         $class $this->em->getClassMetadata(get_class($entity));
  1893.         $associationMappings array_filter(
  1894.             $class->associationMappings,
  1895.             function ($assoc) { return $assoc['isCascadeMerge']; }
  1896.         );
  1897.         foreach ($associationMappings as $assoc) {
  1898.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1899.             if ($relatedEntities instanceof Collection) {
  1900.                 if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
  1901.                     continue;
  1902.                 }
  1903.                 if ($relatedEntities instanceof PersistentCollection) {
  1904.                     // Unwrap so that foreach() does not initialize
  1905.                     $relatedEntities $relatedEntities->unwrap();
  1906.                 }
  1907.                 foreach ($relatedEntities as $relatedEntity) {
  1908.                     $this->doMerge($relatedEntity$visited$managedCopy$assoc);
  1909.                 }
  1910.             } else if ($relatedEntities !== null) {
  1911.                 $this->doMerge($relatedEntities$visited$managedCopy$assoc);
  1912.             }
  1913.         }
  1914.     }
  1915.     /**
  1916.      * Cascades the save operation to associated entities.
  1917.      *
  1918.      * @param object $entity
  1919.      * @param array  $visited
  1920.      *
  1921.      * @return void
  1922.      */
  1923.     private function cascadePersist($entity, array &$visited)
  1924.     {
  1925.         $class $this->em->getClassMetadata(get_class($entity));
  1926.         $associationMappings array_filter(
  1927.             $class->associationMappings,
  1928.             function ($assoc) { return $assoc['isCascadePersist']; }
  1929.         );
  1930.         foreach ($associationMappings as $assoc) {
  1931.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1932.             switch (true) {
  1933.                 case ($relatedEntities instanceof PersistentCollection):
  1934.                     // Unwrap so that foreach() does not initialize
  1935.                     $relatedEntities $relatedEntities->unwrap();
  1936.                     // break; is commented intentionally!
  1937.                 case ($relatedEntities instanceof Collection):
  1938.                 case (is_array($relatedEntities)):
  1939.                     if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) {
  1940.                         throw ORMInvalidArgumentException::invalidAssociation(
  1941.                             $this->em->getClassMetadata($assoc['targetEntity']),
  1942.                             $assoc,
  1943.                             $relatedEntities
  1944.                         );
  1945.                     }
  1946.                     foreach ($relatedEntities as $relatedEntity) {
  1947.                         $this->doPersist($relatedEntity$visited);
  1948.                     }
  1949.                     break;
  1950.                 case ($relatedEntities !== null):
  1951.                     if (! $relatedEntities instanceof $assoc['targetEntity']) {
  1952.                         throw ORMInvalidArgumentException::invalidAssociation(
  1953.                             $this->em->getClassMetadata($assoc['targetEntity']),
  1954.                             $assoc,
  1955.                             $relatedEntities
  1956.                         );
  1957.                     }
  1958.                     $this->doPersist($relatedEntities$visited);
  1959.                     break;
  1960.                 default:
  1961.                     // Do nothing
  1962.             }
  1963.         }
  1964.     }
  1965.     /**
  1966.      * Cascades the delete operation to associated entities.
  1967.      *
  1968.      * @param object $entity
  1969.      * @param array  $visited
  1970.      *
  1971.      * @return void
  1972.      */
  1973.     private function cascadeRemove($entity, array &$visited)
  1974.     {
  1975.         $class $this->em->getClassMetadata(get_class($entity));
  1976.         $associationMappings array_filter(
  1977.             $class->associationMappings,
  1978.             function ($assoc) { return $assoc['isCascadeRemove']; }
  1979.         );
  1980.         $entitiesToCascade = [];
  1981.         foreach ($associationMappings as $assoc) {
  1982.             if ($entity instanceof Proxy && !$entity->__isInitialized__) {
  1983.                 $entity->__load();
  1984.             }
  1985.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1986.             switch (true) {
  1987.                 case ($relatedEntities instanceof Collection):
  1988.                 case (is_array($relatedEntities)):
  1989.                     // If its a PersistentCollection initialization is intended! No unwrap!
  1990.                     foreach ($relatedEntities as $relatedEntity) {
  1991.                         $entitiesToCascade[] = $relatedEntity;
  1992.                     }
  1993.                     break;
  1994.                 case ($relatedEntities !== null):
  1995.                     $entitiesToCascade[] = $relatedEntities;
  1996.                     break;
  1997.                 default:
  1998.                     // Do nothing
  1999.             }
  2000.         }
  2001.         foreach ($entitiesToCascade as $relatedEntity) {
  2002.             $this->doRemove($relatedEntity$visited);
  2003.         }
  2004.     }
  2005.     /**
  2006.      * Acquire a lock on the given entity.
  2007.      *
  2008.      * @param object $entity
  2009.      * @param int    $lockMode
  2010.      * @param int    $lockVersion
  2011.      *
  2012.      * @return void
  2013.      *
  2014.      * @throws ORMInvalidArgumentException
  2015.      * @throws TransactionRequiredException
  2016.      * @throws OptimisticLockException
  2017.      */
  2018.     public function lock($entity$lockMode$lockVersion null)
  2019.     {
  2020.         if ($entity === null) {
  2021.             throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
  2022.         }
  2023.         if ($this->getEntityState($entityself::STATE_DETACHED) != self::STATE_MANAGED) {
  2024.             throw ORMInvalidArgumentException::entityNotManaged($entity);
  2025.         }
  2026.         $class $this->em->getClassMetadata(get_class($entity));
  2027.         switch (true) {
  2028.             case LockMode::OPTIMISTIC === $lockMode:
  2029.                 if ( ! $class->isVersioned) {
  2030.                     throw OptimisticLockException::notVersioned($class->name);
  2031.                 }
  2032.                 if ($lockVersion === null) {
  2033.                     return;
  2034.                 }
  2035.                 if ($entity instanceof Proxy && !$entity->__isInitialized__) {
  2036.                     $entity->__load();
  2037.                 }
  2038.                 $entityVersion $class->reflFields[$class->versionField]->getValue($entity);
  2039.                 if ($entityVersion != $lockVersion) {
  2040.                     throw OptimisticLockException::lockFailedVersionMismatch($entity$lockVersion$entityVersion);
  2041.                 }
  2042.                 break;
  2043.             case LockMode::NONE === $lockMode:
  2044.             case LockMode::PESSIMISTIC_READ === $lockMode:
  2045.             case LockMode::PESSIMISTIC_WRITE === $lockMode:
  2046.                 if (!$this->em->getConnection()->isTransactionActive()) {
  2047.                     throw TransactionRequiredException::transactionRequired();
  2048.                 }
  2049.                 $oid spl_object_hash($entity);
  2050.                 $this->getEntityPersister($class->name)->lock(
  2051.                     array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  2052.                     $lockMode
  2053.                 );
  2054.                 break;
  2055.             default:
  2056.                 // Do nothing
  2057.         }
  2058.     }
  2059.     /**
  2060.      * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
  2061.      *
  2062.      * @return \Doctrine\ORM\Internal\CommitOrderCalculator
  2063.      */
  2064.     public function getCommitOrderCalculator()
  2065.     {
  2066.         return new Internal\CommitOrderCalculator();
  2067.     }
  2068.     /**
  2069.      * Clears the UnitOfWork.
  2070.      *
  2071.      * @param string|null $entityName if given, only entities of this type will get detached.
  2072.      *
  2073.      * @return void
  2074.      *
  2075.      * @throws ORMInvalidArgumentException if an invalid entity name is given
  2076.      */
  2077.     public function clear($entityName null)
  2078.     {
  2079.         if ($entityName === null) {
  2080.             $this->identityMap                    =
  2081.             $this->entityIdentifiers              =
  2082.             $this->originalEntityData             =
  2083.             $this->entityChangeSets               =
  2084.             $this->entityStates                   =
  2085.             $this->scheduledForSynchronization    =
  2086.             $this->entityInsertions               =
  2087.             $this->entityUpdates                  =
  2088.             $this->entityDeletions                =
  2089.             $this->nonCascadedNewDetectedEntities =
  2090.             $this->collectionDeletions            =
  2091.             $this->collectionUpdates              =
  2092.             $this->extraUpdates                   =
  2093.             $this->readOnlyObjects                =
  2094.             $this->visitedCollections             =
  2095.             $this->eagerLoadingEntities           =
  2096.             $this->orphanRemovals                 = [];
  2097.         } else {
  2098.             $this->clearIdentityMapForEntityName($entityName);
  2099.             $this->clearEntityInsertionsForEntityName($entityName);
  2100.         }
  2101.         if ($this->evm->hasListeners(Events::onClear)) {
  2102.             $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em$entityName));
  2103.         }
  2104.     }
  2105.     /**
  2106.      * INTERNAL:
  2107.      * Schedules an orphaned entity for removal. The remove() operation will be
  2108.      * invoked on that entity at the beginning of the next commit of this
  2109.      * UnitOfWork.
  2110.      *
  2111.      * @ignore
  2112.      *
  2113.      * @param object $entity
  2114.      *
  2115.      * @return void
  2116.      */
  2117.     public function scheduleOrphanRemoval($entity)
  2118.     {
  2119.         $this->orphanRemovals[spl_object_hash($entity)] = $entity;
  2120.     }
  2121.     /**
  2122.      * INTERNAL:
  2123.      * Cancels a previously scheduled orphan removal.
  2124.      *
  2125.      * @ignore
  2126.      *
  2127.      * @param object $entity
  2128.      *
  2129.      * @return void
  2130.      */
  2131.     public function cancelOrphanRemoval($entity)
  2132.     {
  2133.         unset($this->orphanRemovals[spl_object_hash($entity)]);
  2134.     }
  2135.     /**
  2136.      * INTERNAL:
  2137.      * Schedules a complete collection for removal when this UnitOfWork commits.
  2138.      *
  2139.      * @param PersistentCollection $coll
  2140.      *
  2141.      * @return void
  2142.      */
  2143.     public function scheduleCollectionDeletion(PersistentCollection $coll)
  2144.     {
  2145.         $coid spl_object_hash($coll);
  2146.         // TODO: if $coll is already scheduled for recreation ... what to do?
  2147.         // Just remove $coll from the scheduled recreations?
  2148.         unset($this->collectionUpdates[$coid]);
  2149.         $this->collectionDeletions[$coid] = $coll;
  2150.     }
  2151.     /**
  2152.      * @param PersistentCollection $coll
  2153.      *
  2154.      * @return bool
  2155.      */
  2156.     public function isCollectionScheduledForDeletion(PersistentCollection $coll)
  2157.     {
  2158.         return isset($this->collectionDeletions[spl_object_hash($coll)]);
  2159.     }
  2160.     /**
  2161.      * @param ClassMetadata $class
  2162.      *
  2163.      * @return ObjectManagerAware|object
  2164.      */
  2165.     private function newInstance($class)
  2166.     {
  2167.         $entity $class->newInstance();
  2168.         if ($entity instanceof ObjectManagerAware) {
  2169.             $entity->injectObjectManager($this->em$class);
  2170.         }
  2171.         return $entity;
  2172.     }
  2173.     /**
  2174.      * INTERNAL:
  2175.      * Creates an entity. Used for reconstitution of persistent entities.
  2176.      *
  2177.      * Internal note: Highly performance-sensitive method.
  2178.      *
  2179.      * @ignore
  2180.      *
  2181.      * @param string $className The name of the entity class.
  2182.      * @param array  $data      The data for the entity.
  2183.      * @param array  $hints     Any hints to account for during reconstitution/lookup of the entity.
  2184.      *
  2185.      * @return object The managed entity instance.
  2186.      *
  2187.      * @todo Rename: getOrCreateEntity
  2188.      */
  2189.     public function createEntity($className, array $data, &$hints = [])
  2190.     {
  2191.         $class $this->em->getClassMetadata($className);
  2192.         $id $this->identifierFlattener->flattenIdentifier($class$data);
  2193.         $idHash implode(' '$id);
  2194.         if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
  2195.             $entity $this->identityMap[$class->rootEntityName][$idHash];
  2196.             $oid spl_object_hash($entity);
  2197.             if (
  2198.                 isset($hints[Query::HINT_REFRESH])
  2199.                 && isset($hints[Query::HINT_REFRESH_ENTITY])
  2200.                 && ($unmanagedProxy $hints[Query::HINT_REFRESH_ENTITY]) !== $entity
  2201.                 && $unmanagedProxy instanceof Proxy
  2202.                 && $this->isIdentifierEquals($unmanagedProxy$entity)
  2203.             ) {
  2204.                 // DDC-1238 - we have a managed instance, but it isn't the provided one.
  2205.                 // Therefore we clear its identifier. Also, we must re-fetch metadata since the
  2206.                 // refreshed object may be anything
  2207.                 foreach ($class->identifier as $fieldName) {
  2208.                     $class->reflFields[$fieldName]->setValue($unmanagedProxynull);
  2209.                 }
  2210.                 return $unmanagedProxy;
  2211.             }
  2212.             if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  2213.                 $entity->__setInitialized(true);
  2214.                 if ($entity instanceof NotifyPropertyChanged) {
  2215.                     $entity->addPropertyChangedListener($this);
  2216.                 }
  2217.             } else {
  2218.                 if ( ! isset($hints[Query::HINT_REFRESH])
  2219.                     || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) {
  2220.                     return $entity;
  2221.                 }
  2222.             }
  2223.             // inject ObjectManager upon refresh.
  2224.             if ($entity instanceof ObjectManagerAware) {
  2225.                 $entity->injectObjectManager($this->em$class);
  2226.             }
  2227.             $this->originalEntityData[$oid] = $data;
  2228.         } else {
  2229.             $entity $this->newInstance($class);
  2230.             $oid    spl_object_hash($entity);
  2231.             $this->entityIdentifiers[$oid]  = $id;
  2232.             $this->entityStates[$oid]       = self::STATE_MANAGED;
  2233.             $this->originalEntityData[$oid] = $data;
  2234.             $this->identityMap[$class->rootEntityName][$idHash] = $entity;
  2235.             if ($entity instanceof NotifyPropertyChanged) {
  2236.                 $entity->addPropertyChangedListener($this);
  2237.             }
  2238.         }
  2239.         foreach ($data as $field => $value) {
  2240.             if (isset($class->fieldMappings[$field])) {
  2241.                 $class->reflFields[$field]->setValue($entity$value);
  2242.             }
  2243.         }
  2244.         // Loading the entity right here, if its in the eager loading map get rid of it there.
  2245.         unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
  2246.         if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
  2247.             unset($this->eagerLoadingEntities[$class->rootEntityName]);
  2248.         }
  2249.         // Properly initialize any unfetched associations, if partial objects are not allowed.
  2250.         if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
  2251.             return $entity;
  2252.         }
  2253.         foreach ($class->associationMappings as $field => $assoc) {
  2254.             // Check if the association is not among the fetch-joined associations already.
  2255.             if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
  2256.                 continue;
  2257.             }
  2258.             $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  2259.             switch (true) {
  2260.                 case ($assoc['type'] & ClassMetadata::TO_ONE):
  2261.                     if ( ! $assoc['isOwningSide']) {
  2262.                         // use the given entity association
  2263.                         if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
  2264.                             $this->originalEntityData[$oid][$field] = $data[$field];
  2265.                             $class->reflFields[$field]->setValue($entity$data[$field]);
  2266.                             $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity);
  2267.                             continue 2;
  2268.                         }
  2269.                         // Inverse side of x-to-one can never be lazy
  2270.                         $class->reflFields[$field]->setValue($entity$this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc$entity));
  2271.                         continue 2;
  2272.                     }
  2273.                     // use the entity association
  2274.                     if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
  2275.                         $class->reflFields[$field]->setValue($entity$data[$field]);
  2276.                         $this->originalEntityData[$oid][$field] = $data[$field];
  2277.                         break;
  2278.                     }
  2279.                     $associatedId = [];
  2280.                     // TODO: Is this even computed right in all cases of composite keys?
  2281.                     foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
  2282.                         $joinColumnValue $data[$srcColumn] ?? null;
  2283.                         if ($joinColumnValue !== null) {
  2284.                             if ($targetClass->containsForeignIdentifier) {
  2285.                                 $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
  2286.                             } else {
  2287.                                 $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
  2288.                             }
  2289.                         } elseif ($targetClass->containsForeignIdentifier
  2290.                             && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifiertrue)
  2291.                         ) {
  2292.                             // the missing key is part of target's entity primary key
  2293.                             $associatedId = [];
  2294.                             break;
  2295.                         }
  2296.                     }
  2297.                     if ( ! $associatedId) {
  2298.                         // Foreign key is NULL
  2299.                         $class->reflFields[$field]->setValue($entitynull);
  2300.                         $this->originalEntityData[$oid][$field] = null;
  2301.                         break;
  2302.                     }
  2303.                     if ( ! isset($hints['fetchMode'][$class->name][$field])) {
  2304.                         $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
  2305.                     }
  2306.                     // Foreign key is set
  2307.                     // Check identity map first
  2308.                     // FIXME: Can break easily with composite keys if join column values are in
  2309.                     //        wrong order. The correct order is the one in ClassMetadata#identifier.
  2310.                     $relatedIdHash implode(' '$associatedId);
  2311.                     switch (true) {
  2312.                         case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
  2313.                             $newValue $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
  2314.                             // If this is an uninitialized proxy, we are deferring eager loads,
  2315.                             // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
  2316.                             // then we can append this entity for eager loading!
  2317.                             if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
  2318.                                 isset($hints[self::HINT_DEFEREAGERLOAD]) &&
  2319.                                 !$targetClass->isIdentifierComposite &&
  2320.                                 $newValue instanceof Proxy &&
  2321.                                 $newValue->__isInitialized__ === false) {
  2322.                                 $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2323.                             }
  2324.                             break;
  2325.                         case ($targetClass->subClasses):
  2326.                             // If it might be a subtype, it can not be lazy. There isn't even
  2327.                             // a way to solve this with deferred eager loading, which means putting
  2328.                             // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
  2329.                             $newValue $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc$entity$associatedId);
  2330.                             break;
  2331.                         default:
  2332.                             switch (true) {
  2333.                                 // We are negating the condition here. Other cases will assume it is valid!
  2334.                                 case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
  2335.                                     $newValue $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2336.                                     break;
  2337.                                 // Deferred eager load only works for single identifier classes
  2338.                                 case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite):
  2339.                                     // TODO: Is there a faster approach?
  2340.                                     $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2341.                                     $newValue $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2342.                                     break;
  2343.                                 default:
  2344.                                     // TODO: This is very imperformant, ignore it?
  2345.                                     $newValue $this->em->find($assoc['targetEntity'], $associatedId);
  2346.                                     break;
  2347.                             }
  2348.                             // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
  2349.                             $newValueOid spl_object_hash($newValue);
  2350.                             $this->entityIdentifiers[$newValueOid] = $associatedId;
  2351.                             $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
  2352.                             if (
  2353.                                 $newValue instanceof NotifyPropertyChanged &&
  2354.                                 ( ! $newValue instanceof Proxy || $newValue->__isInitialized())
  2355.                             ) {
  2356.                                 $newValue->addPropertyChangedListener($this);
  2357.                             }
  2358.                             $this->entityStates[$newValueOid] = self::STATE_MANAGED;
  2359.                             // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
  2360.                             break;
  2361.                     }
  2362.                     $this->originalEntityData[$oid][$field] = $newValue;
  2363.                     $class->reflFields[$field]->setValue($entity$newValue);
  2364.                     if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
  2365.                         $inverseAssoc $targetClass->associationMappings[$assoc['inversedBy']];
  2366.                         $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue$entity);
  2367.                     }
  2368.                     break;
  2369.                 default:
  2370.                     // Ignore if its a cached collection
  2371.                     if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity$field) instanceof PersistentCollection) {
  2372.                         break;
  2373.                     }
  2374.                     // use the given collection
  2375.                     if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
  2376.                         $data[$field]->setOwner($entity$assoc);
  2377.                         $class->reflFields[$field]->setValue($entity$data[$field]);
  2378.                         $this->originalEntityData[$oid][$field] = $data[$field];
  2379.                         break;
  2380.                     }
  2381.                     // Inject collection
  2382.                     $pColl = new PersistentCollection($this->em$targetClass, new ArrayCollection);
  2383.                     $pColl->setOwner($entity$assoc);
  2384.                     $pColl->setInitialized(false);
  2385.                     $reflField $class->reflFields[$field];
  2386.                     $reflField->setValue($entity$pColl);
  2387.                     if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
  2388.                         $this->loadCollection($pColl);
  2389.                         $pColl->takeSnapshot();
  2390.                     }
  2391.                     $this->originalEntityData[$oid][$field] = $pColl;
  2392.                     break;
  2393.             }
  2394.         }
  2395.         // defer invoking of postLoad event to hydration complete step
  2396.         $this->hydrationCompleteHandler->deferPostLoadInvoking($class$entity);
  2397.         return $entity;
  2398.     }
  2399.     /**
  2400.      * @return void
  2401.      */
  2402.     public function triggerEagerLoads()
  2403.     {
  2404.         if ( ! $this->eagerLoadingEntities) {
  2405.             return;
  2406.         }
  2407.         // avoid infinite recursion
  2408.         $eagerLoadingEntities       $this->eagerLoadingEntities;
  2409.         $this->eagerLoadingEntities = [];
  2410.         foreach ($eagerLoadingEntities as $entityName => $ids) {
  2411.             if ( ! $ids) {
  2412.                 continue;
  2413.             }
  2414.             $class $this->em->getClassMetadata($entityName);
  2415.             $this->getEntityPersister($entityName)->loadAll(
  2416.                 array_combine($class->identifier, [array_values($ids)])
  2417.             );
  2418.         }
  2419.     }
  2420.     /**
  2421.      * Initializes (loads) an uninitialized persistent collection of an entity.
  2422.      *
  2423.      * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
  2424.      *
  2425.      * @return void
  2426.      *
  2427.      * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
  2428.      */
  2429.     public function loadCollection(PersistentCollection $collection)
  2430.     {
  2431.         $assoc     $collection->getMapping();
  2432.         $persister $this->getEntityPersister($assoc['targetEntity']);
  2433.         switch ($assoc['type']) {
  2434.             case ClassMetadata::ONE_TO_MANY:
  2435.                 $persister->loadOneToManyCollection($assoc$collection->getOwner(), $collection);
  2436.                 break;
  2437.             case ClassMetadata::MANY_TO_MANY:
  2438.                 $persister->loadManyToManyCollection($assoc$collection->getOwner(), $collection);
  2439.                 break;
  2440.         }
  2441.         $collection->setInitialized(true);
  2442.     }
  2443.     /**
  2444.      * Gets the identity map of the UnitOfWork.
  2445.      *
  2446.      * @return array
  2447.      */
  2448.     public function getIdentityMap()
  2449.     {
  2450.         return $this->identityMap;
  2451.     }
  2452.     /**
  2453.      * Gets the original data of an entity. The original data is the data that was
  2454.      * present at the time the entity was reconstituted from the database.
  2455.      *
  2456.      * @param object $entity
  2457.      *
  2458.      * @return array
  2459.      */
  2460.     public function getOriginalEntityData($entity)
  2461.     {
  2462.         $oid spl_object_hash($entity);
  2463.         return isset($this->originalEntityData[$oid])
  2464.             ? $this->originalEntityData[$oid]
  2465.             : [];
  2466.     }
  2467.     /**
  2468.      * @ignore
  2469.      *
  2470.      * @param object $entity
  2471.      * @param array  $data
  2472.      *
  2473.      * @return void
  2474.      */
  2475.     public function setOriginalEntityData($entity, array $data)
  2476.     {
  2477.         $this->originalEntityData[spl_object_hash($entity)] = $data;
  2478.     }
  2479.     /**
  2480.      * INTERNAL:
  2481.      * Sets a property value of the original data array of an entity.
  2482.      *
  2483.      * @ignore
  2484.      *
  2485.      * @param string $oid
  2486.      * @param string $property
  2487.      * @param mixed  $value
  2488.      *
  2489.      * @return void
  2490.      */
  2491.     public function setOriginalEntityProperty($oid$property$value)
  2492.     {
  2493.         $this->originalEntityData[$oid][$property] = $value;
  2494.     }
  2495.     /**
  2496.      * Gets the identifier of an entity.
  2497.      * The returned value is always an array of identifier values. If the entity
  2498.      * has a composite identifier then the identifier values are in the same
  2499.      * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
  2500.      *
  2501.      * @param object $entity
  2502.      *
  2503.      * @return array The identifier values.
  2504.      */
  2505.     public function getEntityIdentifier($entity)
  2506.     {
  2507.         return $this->entityIdentifiers[spl_object_hash($entity)];
  2508.     }
  2509.     /**
  2510.      * Processes an entity instance to extract their identifier values.
  2511.      *
  2512.      * @param object $entity The entity instance.
  2513.      *
  2514.      * @return mixed A scalar value.
  2515.      *
  2516.      * @throws \Doctrine\ORM\ORMInvalidArgumentException
  2517.      */
  2518.     public function getSingleIdentifierValue($entity)
  2519.     {
  2520.         $class $this->em->getClassMetadata(get_class($entity));
  2521.         if ($class->isIdentifierComposite) {
  2522.             throw ORMInvalidArgumentException::invalidCompositeIdentifier();
  2523.         }
  2524.         $values $this->isInIdentityMap($entity)
  2525.             ? $this->getEntityIdentifier($entity)
  2526.             : $class->getIdentifierValues($entity);
  2527.         return isset($values[$class->identifier[0]]) ? $values[$class->identifier[0]] : null;
  2528.     }
  2529.     /**
  2530.      * Tries to find an entity with the given identifier in the identity map of
  2531.      * this UnitOfWork.
  2532.      *
  2533.      * @param mixed  $id            The entity identifier to look for.
  2534.      * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
  2535.      *
  2536.      * @return object|false Returns the entity with the specified identifier if it exists in
  2537.      *                      this UnitOfWork, FALSE otherwise.
  2538.      */
  2539.     public function tryGetById($id$rootClassName)
  2540.     {
  2541.         $idHash implode(' ', (array) $id);
  2542.         return isset($this->identityMap[$rootClassName][$idHash])
  2543.             ? $this->identityMap[$rootClassName][$idHash]
  2544.             : false;
  2545.     }
  2546.     /**
  2547.      * Schedules an entity for dirty-checking at commit-time.
  2548.      *
  2549.      * @param object $entity The entity to schedule for dirty-checking.
  2550.      *
  2551.      * @return void
  2552.      *
  2553.      * @todo Rename: scheduleForSynchronization
  2554.      */
  2555.     public function scheduleForDirtyCheck($entity)
  2556.     {
  2557.         $rootClassName $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  2558.         $this->scheduledForSynchronization[$rootClassName][spl_object_hash($entity)] = $entity;
  2559.     }
  2560.     /**
  2561.      * Checks whether the UnitOfWork has any pending insertions.
  2562.      *
  2563.      * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
  2564.      */
  2565.     public function hasPendingInsertions()
  2566.     {
  2567.         return ! empty($this->entityInsertions);
  2568.     }
  2569.     /**
  2570.      * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
  2571.      * number of entities in the identity map.
  2572.      *
  2573.      * @return integer
  2574.      */
  2575.     public function size()
  2576.     {
  2577.         $countArray array_map('count'$this->identityMap);
  2578.         return array_sum($countArray);
  2579.     }
  2580.     /**
  2581.      * Gets the EntityPersister for an Entity.
  2582.      *
  2583.      * @param string $entityName The name of the Entity.
  2584.      *
  2585.      * @return \Doctrine\ORM\Persisters\Entity\EntityPersister
  2586.      */
  2587.     public function getEntityPersister($entityName)
  2588.     {
  2589.         if (isset($this->persisters[$entityName])) {
  2590.             return $this->persisters[$entityName];
  2591.         }
  2592.         $class $this->em->getClassMetadata($entityName);
  2593.         switch (true) {
  2594.             case ($class->isInheritanceTypeNone()):
  2595.                 $persister = new BasicEntityPersister($this->em$class);
  2596.                 break;
  2597.             case ($class->isInheritanceTypeSingleTable()):
  2598.                 $persister = new SingleTablePersister($this->em$class);
  2599.                 break;
  2600.             case ($class->isInheritanceTypeJoined()):
  2601.                 $persister = new JoinedSubclassPersister($this->em$class);
  2602.                 break;
  2603.             default:
  2604.                 throw new \RuntimeException('No persister found for entity.');
  2605.         }
  2606.         if ($this->hasCache && $class->cache !== null) {
  2607.             $persister $this->em->getConfiguration()
  2608.                 ->getSecondLevelCacheConfiguration()
  2609.                 ->getCacheFactory()
  2610.                 ->buildCachedEntityPersister($this->em$persister$class);
  2611.         }
  2612.         $this->persisters[$entityName] = $persister;
  2613.         return $this->persisters[$entityName];
  2614.     }
  2615.     /**
  2616.      * Gets a collection persister for a collection-valued association.
  2617.      *
  2618.      * @param array $association
  2619.      *
  2620.      * @return \Doctrine\ORM\Persisters\Collection\CollectionPersister
  2621.      */
  2622.     public function getCollectionPersister(array $association)
  2623.     {
  2624.         $role = isset($association['cache'])
  2625.             ? $association['sourceEntity'] . '::' $association['fieldName']
  2626.             : $association['type'];
  2627.         if (isset($this->collectionPersisters[$role])) {
  2628.             return $this->collectionPersisters[$role];
  2629.         }
  2630.         $persister ClassMetadata::ONE_TO_MANY === $association['type']
  2631.             ? new OneToManyPersister($this->em)
  2632.             : new ManyToManyPersister($this->em);
  2633.         if ($this->hasCache && isset($association['cache'])) {
  2634.             $persister $this->em->getConfiguration()
  2635.                 ->getSecondLevelCacheConfiguration()
  2636.                 ->getCacheFactory()
  2637.                 ->buildCachedCollectionPersister($this->em$persister$association);
  2638.         }
  2639.         $this->collectionPersisters[$role] = $persister;
  2640.         return $this->collectionPersisters[$role];
  2641.     }
  2642.     /**
  2643.      * INTERNAL:
  2644.      * Registers an entity as managed.
  2645.      *
  2646.      * @param object $entity The entity.
  2647.      * @param array  $id     The identifier values.
  2648.      * @param array  $data   The original entity data.
  2649.      *
  2650.      * @return void
  2651.      */
  2652.     public function registerManaged($entity, array $id, array $data)
  2653.     {
  2654.         $oid spl_object_hash($entity);
  2655.         $this->entityIdentifiers[$oid]  = $id;
  2656.         $this->entityStates[$oid]       = self::STATE_MANAGED;
  2657.         $this->originalEntityData[$oid] = $data;
  2658.         $this->addToIdentityMap($entity);
  2659.         if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
  2660.             $entity->addPropertyChangedListener($this);
  2661.         }
  2662.     }
  2663.     /**
  2664.      * INTERNAL:
  2665.      * Clears the property changeset of the entity with the given OID.
  2666.      *
  2667.      * @param string $oid The entity's OID.
  2668.      *
  2669.      * @return void
  2670.      */
  2671.     public function clearEntityChangeSet($oid)
  2672.     {
  2673.         unset($this->entityChangeSets[$oid]);
  2674.     }
  2675.     /* PropertyChangedListener implementation */
  2676.     /**
  2677.      * Notifies this UnitOfWork of a property change in an entity.
  2678.      *
  2679.      * @param object $sender       The entity that owns the property.
  2680.      * @param string $propertyName The name of the property that changed.
  2681.      * @param mixed  $oldValue     The old value of the property.
  2682.      * @param mixed  $newValue     The new value of the property.
  2683.      *
  2684.      * @return void
  2685.      */
  2686.     public function propertyChanged($sender$propertyName$oldValue$newValue)
  2687.     {
  2688.         $oid   spl_object_hash($sender);
  2689.         $class $this->em->getClassMetadata(get_class($sender));
  2690.         $isAssocField = isset($class->associationMappings[$propertyName]);
  2691.         if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
  2692.             return; // ignore non-persistent fields
  2693.         }
  2694.         // Update changeset and mark entity for synchronization
  2695.         $this->entityChangeSets[$oid][$propertyName] = [$oldValue$newValue];
  2696.         if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) {
  2697.             $this->scheduleForDirtyCheck($sender);
  2698.         }
  2699.     }
  2700.     /**
  2701.      * Gets the currently scheduled entity insertions in this UnitOfWork.
  2702.      *
  2703.      * @return array
  2704.      */
  2705.     public function getScheduledEntityInsertions()
  2706.     {
  2707.         return $this->entityInsertions;
  2708.     }
  2709.     /**
  2710.      * Gets the currently scheduled entity updates in this UnitOfWork.
  2711.      *
  2712.      * @return array
  2713.      */
  2714.     public function getScheduledEntityUpdates()
  2715.     {
  2716.         return $this->entityUpdates;
  2717.     }
  2718.     /**
  2719.      * Gets the currently scheduled entity deletions in this UnitOfWork.
  2720.      *
  2721.      * @return array
  2722.      */
  2723.     public function getScheduledEntityDeletions()
  2724.     {
  2725.         return $this->entityDeletions;
  2726.     }
  2727.     /**
  2728.      * Gets the currently scheduled complete collection deletions
  2729.      *
  2730.      * @return array
  2731.      */
  2732.     public function getScheduledCollectionDeletions()
  2733.     {
  2734.         return $this->collectionDeletions;
  2735.     }
  2736.     /**
  2737.      * Gets the currently scheduled collection inserts, updates and deletes.
  2738.      *
  2739.      * @return array
  2740.      */
  2741.     public function getScheduledCollectionUpdates()
  2742.     {
  2743.         return $this->collectionUpdates;
  2744.     }
  2745.     /**
  2746.      * Helper method to initialize a lazy loading proxy or persistent collection.
  2747.      *
  2748.      * @param object $obj
  2749.      *
  2750.      * @return void
  2751.      */
  2752.     public function initializeObject($obj)
  2753.     {
  2754.         if ($obj instanceof Proxy) {
  2755.             $obj->__load();
  2756.             return;
  2757.         }
  2758.         if ($obj instanceof PersistentCollection) {
  2759.             $obj->initialize();
  2760.         }
  2761.     }
  2762.     /**
  2763.      * Helper method to show an object as string.
  2764.      *
  2765.      * @param object $obj
  2766.      *
  2767.      * @return string
  2768.      */
  2769.     private static function objToStr($obj)
  2770.     {
  2771.         return method_exists($obj'__toString') ? (string) $obj get_class($obj).'@'.spl_object_hash($obj);
  2772.     }
  2773.     /**
  2774.      * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
  2775.      *
  2776.      * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
  2777.      * on this object that might be necessary to perform a correct update.
  2778.      *
  2779.      * @param object $object
  2780.      *
  2781.      * @return void
  2782.      *
  2783.      * @throws ORMInvalidArgumentException
  2784.      */
  2785.     public function markReadOnly($object)
  2786.     {
  2787.         if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
  2788.             throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2789.         }
  2790.         $this->readOnlyObjects[spl_object_hash($object)] = true;
  2791.     }
  2792.     /**
  2793.      * Is this entity read only?
  2794.      *
  2795.      * @param object $object
  2796.      *
  2797.      * @return bool
  2798.      *
  2799.      * @throws ORMInvalidArgumentException
  2800.      */
  2801.     public function isReadOnly($object)
  2802.     {
  2803.         if ( ! is_object($object)) {
  2804.             throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2805.         }
  2806.         return isset($this->readOnlyObjects[spl_object_hash($object)]);
  2807.     }
  2808.     /**
  2809.      * Perform whatever processing is encapsulated here after completion of the transaction.
  2810.      */
  2811.     private function afterTransactionComplete()
  2812.     {
  2813.         $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
  2814.             $persister->afterTransactionComplete();
  2815.         });
  2816.     }
  2817.     /**
  2818.      * Perform whatever processing is encapsulated here after completion of the rolled-back.
  2819.      */
  2820.     private function afterTransactionRolledBack()
  2821.     {
  2822.         $this->performCallbackOnCachedPersister(function (CachedPersister $persister) {
  2823.             $persister->afterTransactionRolledBack();
  2824.         });
  2825.     }
  2826.     /**
  2827.      * Performs an action after the transaction.
  2828.      *
  2829.      * @param callable $callback
  2830.      */
  2831.     private function performCallbackOnCachedPersister(callable $callback)
  2832.     {
  2833.         if ( ! $this->hasCache) {
  2834.             return;
  2835.         }
  2836.         foreach (array_merge($this->persisters$this->collectionPersisters) as $persister) {
  2837.             if ($persister instanceof CachedPersister) {
  2838.                 $callback($persister);
  2839.             }
  2840.         }
  2841.     }
  2842.     private function dispatchOnFlushEvent()
  2843.     {
  2844.         if ($this->evm->hasListeners(Events::onFlush)) {
  2845.             $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
  2846.         }
  2847.     }
  2848.     private function dispatchPostFlushEvent()
  2849.     {
  2850.         if ($this->evm->hasListeners(Events::postFlush)) {
  2851.             $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
  2852.         }
  2853.     }
  2854.     /**
  2855.      * Verifies if two given entities actually are the same based on identifier comparison
  2856.      *
  2857.      * @param object $entity1
  2858.      * @param object $entity2
  2859.      *
  2860.      * @return bool
  2861.      */
  2862.     private function isIdentifierEquals($entity1$entity2)
  2863.     {
  2864.         if ($entity1 === $entity2) {
  2865.             return true;
  2866.         }
  2867.         $class $this->em->getClassMetadata(get_class($entity1));
  2868.         if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
  2869.             return false;
  2870.         }
  2871.         $oid1 spl_object_hash($entity1);
  2872.         $oid2 spl_object_hash($entity2);
  2873.         $id1 = isset($this->entityIdentifiers[$oid1])
  2874.             ? $this->entityIdentifiers[$oid1]
  2875.             : $this->identifierFlattener->flattenIdentifier($class$class->getIdentifierValues($entity1));
  2876.         $id2 = isset($this->entityIdentifiers[$oid2])
  2877.             ? $this->entityIdentifiers[$oid2]
  2878.             : $this->identifierFlattener->flattenIdentifier($class$class->getIdentifierValues($entity2));
  2879.         return $id1 === $id2 || implode(' '$id1) === implode(' '$id2);
  2880.     }
  2881.     /**
  2882.      * @throws ORMInvalidArgumentException
  2883.      */
  2884.     private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void
  2885.     {
  2886.         $entitiesNeedingCascadePersist = \array_diff_key($this->nonCascadedNewDetectedEntities$this->entityInsertions);
  2887.         $this->nonCascadedNewDetectedEntities = [];
  2888.         if ($entitiesNeedingCascadePersist) {
  2889.             throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
  2890.                 \array_values($entitiesNeedingCascadePersist)
  2891.             );
  2892.         }
  2893.     }
  2894.     /**
  2895.      * @param object $entity
  2896.      * @param object $managedCopy
  2897.      *
  2898.      * @throws ORMException
  2899.      * @throws OptimisticLockException
  2900.      * @throws TransactionRequiredException
  2901.      */
  2902.     private function mergeEntityStateIntoManagedCopy($entity$managedCopy)
  2903.     {
  2904.         if (! $this->isLoaded($entity)) {
  2905.             return;
  2906.         }
  2907.         if (! $this->isLoaded($managedCopy)) {
  2908.             $managedCopy->__load();
  2909.         }
  2910.         $class $this->em->getClassMetadata(get_class($entity));
  2911.         foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) {
  2912.             $name $prop->name;
  2913.             $prop->setAccessible(true);
  2914.             if ( ! isset($class->associationMappings[$name])) {
  2915.                 if ( ! $class->isIdentifier($name)) {
  2916.                     $prop->setValue($managedCopy$prop->getValue($entity));
  2917.                 }
  2918.             } else {
  2919.                 $assoc2 $class->associationMappings[$name];
  2920.                 if ($assoc2['type'] & ClassMetadata::TO_ONE) {
  2921.                     $other $prop->getValue($entity);
  2922.                     if ($other === null) {
  2923.                         $prop->setValue($managedCopynull);
  2924.                     } else {
  2925.                         if ($other instanceof Proxy && !$other->__isInitialized()) {
  2926.                             // do not merge fields marked lazy that have not been fetched.
  2927.                             continue;
  2928.                         }
  2929.                         if ( ! $assoc2['isCascadeMerge']) {
  2930.                             if ($this->getEntityState($other) === self::STATE_DETACHED) {
  2931.                                 $targetClass $this->em->getClassMetadata($assoc2['targetEntity']);
  2932.                                 $relatedId   $targetClass->getIdentifierValues($other);
  2933.                                 if ($targetClass->subClasses) {
  2934.                                     $other $this->em->find($targetClass->name$relatedId);
  2935.                                 } else {
  2936.                                     $other $this->em->getProxyFactory()->getProxy(
  2937.                                         $assoc2['targetEntity'],
  2938.                                         $relatedId
  2939.                                     );
  2940.                                     $this->registerManaged($other$relatedId, []);
  2941.                                 }
  2942.                             }
  2943.                             $prop->setValue($managedCopy$other);
  2944.                         }
  2945.                     }
  2946.                 } else {
  2947.                     $mergeCol $prop->getValue($entity);
  2948.                     if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) {
  2949.                         // do not merge fields marked lazy that have not been fetched.
  2950.                         // keep the lazy persistent collection of the managed copy.
  2951.                         continue;
  2952.                     }
  2953.                     $managedCol $prop->getValue($managedCopy);
  2954.                     if ( ! $managedCol) {
  2955.                         $managedCol = new PersistentCollection(
  2956.                             $this->em,
  2957.                             $this->em->getClassMetadata($assoc2['targetEntity']),
  2958.                             new ArrayCollection
  2959.                         );
  2960.                         $managedCol->setOwner($managedCopy$assoc2);
  2961.                         $prop->setValue($managedCopy$managedCol);
  2962.                     }
  2963.                     if ($assoc2['isCascadeMerge']) {
  2964.                         $managedCol->initialize();
  2965.                         // clear and set dirty a managed collection if its not also the same collection to merge from.
  2966.                         if ( ! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
  2967.                             $managedCol->unwrap()->clear();
  2968.                             $managedCol->setDirty(true);
  2969.                             if ($assoc2['isOwningSide']
  2970.                                 && $assoc2['type'] == ClassMetadata::MANY_TO_MANY
  2971.                                 && $class->isChangeTrackingNotify()
  2972.                             ) {
  2973.                                 $this->scheduleForDirtyCheck($managedCopy);
  2974.                             }
  2975.                         }
  2976.                     }
  2977.                 }
  2978.             }
  2979.             if ($class->isChangeTrackingNotify()) {
  2980.                 // Just treat all properties as changed, there is no other choice.
  2981.                 $this->propertyChanged($managedCopy$namenull$prop->getValue($managedCopy));
  2982.             }
  2983.         }
  2984.     }
  2985.     /**
  2986.      * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
  2987.      * Unit of work able to fire deferred events, related to loading events here.
  2988.      *
  2989.      * @internal should be called internally from object hydrators
  2990.      */
  2991.     public function hydrationComplete()
  2992.     {
  2993.         $this->hydrationCompleteHandler->hydrationComplete();
  2994.     }
  2995.     /**
  2996.      * @param string $entityName
  2997.      */
  2998.     private function clearIdentityMapForEntityName($entityName)
  2999.     {
  3000.         if (! isset($this->identityMap[$entityName])) {
  3001.             return;
  3002.         }
  3003.         $visited = [];
  3004.         foreach ($this->identityMap[$entityName] as $entity) {
  3005.             $this->doDetach($entity$visitedfalse);
  3006.         }
  3007.     }
  3008.     /**
  3009.      * @param string $entityName
  3010.      */
  3011.     private function clearEntityInsertionsForEntityName($entityName)
  3012.     {
  3013.         foreach ($this->entityInsertions as $hash => $entity) {
  3014.             // note: performance optimization - `instanceof` is much faster than a function call
  3015.             if ($entity instanceof $entityName && get_class($entity) === $entityName) {
  3016.                 unset($this->entityInsertions[$hash]);
  3017.             }
  3018.         }
  3019.     }
  3020.     /**
  3021.      * @param ClassMetadata $class
  3022.      * @param mixed         $identifierValue
  3023.      *
  3024.      * @return mixed the identifier after type conversion
  3025.      *
  3026.      * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier
  3027.      */
  3028.     private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class$identifierValue)
  3029.     {
  3030.         return $this->em->getConnection()->convertToPHPValue(
  3031.             $identifierValue,
  3032.             $class->getTypeOfField($class->getSingleIdentifierFieldName())
  3033.         );
  3034.     }
  3035. }