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

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