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

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