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

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