Deprecated: Return type of Google\Model::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Model.php on line 256

Deprecated: Return type of Google\Model::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Model.php on line 261

Deprecated: Return type of Google\Model::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Model.php on line 268

Deprecated: Return type of Google\Model::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Model.php on line 278

Deprecated: Return type of Google\Collection::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 22

Deprecated: Return type of Google\Collection::next() should either be compatible with Iterator::next(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 38

Deprecated: Return type of Google\Collection::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 30

Deprecated: Return type of Google\Collection::valid() should either be compatible with Iterator::valid(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 43

Deprecated: Return type of Google\Collection::rewind() should either be compatible with Iterator::rewind(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 14

Deprecated: Return type of Google\Collection::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/html/sanralsmme/vendor/google/apiclient/src/Collection.php on line 49
Symfony Profiler

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

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