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

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