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

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