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

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