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

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