vendor/doctrine/orm/src/UnitOfWork.php line 1759

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