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

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