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

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