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

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM;
  4. use 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.             $value $class->getFieldValue($entity$idField);
  975.             if (isset($class->associationMappings[$idField])) {
  976.                 // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
  977.                 $value $this->getSingleIdentifierValue($value);
  978.             }
  979.             $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value;
  980.         }
  981.         $this->entityStates[$oid]      = self::STATE_MANAGED;
  982.         $this->entityIdentifiers[$oid] = $identifier;
  983.         $this->addToIdentityMap($entity);
  984.     }
  985.     /**
  986.      * Executes all entity updates for entities of the specified type.
  987.      */
  988.     private function executeUpdates(ClassMetadata $class): void
  989.     {
  990.         $className        $class->name;
  991.         $persister        $this->getEntityPersister($className);
  992.         $preUpdateInvoke  $this->listenersInvoker->getSubscribedSystems($classEvents::preUpdate);
  993.         $postUpdateInvoke $this->listenersInvoker->getSubscribedSystems($classEvents::postUpdate);
  994.         foreach ($this->entityUpdates as $oid => $entity) {
  995.             if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  996.                 continue;
  997.             }
  998.             if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
  999.                 $this->listenersInvoker->invoke($classEvents::preUpdate$entity, new PreUpdateEventArgs($entity$this->em$this->getEntityChangeSet($entity)), $preUpdateInvoke);
  1000.                 $this->recomputeSingleEntityChangeSet($class$entity);
  1001.             }
  1002.             if (! empty($this->entityChangeSets[$oid])) {
  1003.                 $persister->update($entity);
  1004.             }
  1005.             unset($this->entityUpdates[$oid]);
  1006.             if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
  1007.                 $this->listenersInvoker->invoke($classEvents::postUpdate$entity, new LifecycleEventArgs($entity$this->em), $postUpdateInvoke);
  1008.             }
  1009.         }
  1010.     }
  1011.     /**
  1012.      * Executes all entity deletions for entities of the specified type.
  1013.      */
  1014.     private function executeDeletions(ClassMetadata $class): void
  1015.     {
  1016.         $className $class->name;
  1017.         $persister $this->getEntityPersister($className);
  1018.         $invoke    $this->listenersInvoker->getSubscribedSystems($classEvents::postRemove);
  1019.         foreach ($this->entityDeletions as $oid => $entity) {
  1020.             if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  1021.                 continue;
  1022.             }
  1023.             $persister->delete($entity);
  1024.             unset(
  1025.                 $this->entityDeletions[$oid],
  1026.                 $this->entityIdentifiers[$oid],
  1027.                 $this->originalEntityData[$oid],
  1028.                 $this->entityStates[$oid]
  1029.             );
  1030.             // Entity with this $oid after deletion treated as NEW, even if the $oid
  1031.             // is obtained by a new entity because the old one went out of scope.
  1032.             //$this->entityStates[$oid] = self::STATE_NEW;
  1033.             if (! $class->isIdentifierNatural()) {
  1034.                 $class->reflFields[$class->identifier[0]]->setValue($entitynull);
  1035.             }
  1036.             if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  1037.                 $this->listenersInvoker->invoke($classEvents::postRemove$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  1038.             }
  1039.         }
  1040.     }
  1041.     /**
  1042.      * Gets the commit order.
  1043.      *
  1044.      * @return list<object>
  1045.      */
  1046.     private function getCommitOrder(): array
  1047.     {
  1048.         $calc $this->getCommitOrderCalculator();
  1049.         // See if there are any new classes in the changeset, that are not in the
  1050.         // commit order graph yet (don't have a node).
  1051.         // We have to inspect changeSet to be able to correctly build dependencies.
  1052.         // It is not possible to use IdentityMap here because post inserted ids
  1053.         // are not yet available.
  1054.         $newNodes = [];
  1055.         foreach (array_merge($this->entityInsertions$this->entityUpdates$this->entityDeletions) as $entity) {
  1056.             $class $this->em->getClassMetadata(get_class($entity));
  1057.             if ($calc->hasNode($class->name)) {
  1058.                 continue;
  1059.             }
  1060.             $calc->addNode($class->name$class);
  1061.             $newNodes[] = $class;
  1062.         }
  1063.         // Calculate dependencies for new nodes
  1064.         while ($class array_pop($newNodes)) {
  1065.             foreach ($class->associationMappings as $assoc) {
  1066.                 if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1067.                     continue;
  1068.                 }
  1069.                 $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  1070.                 if (! $calc->hasNode($targetClass->name)) {
  1071.                     $calc->addNode($targetClass->name$targetClass);
  1072.                     $newNodes[] = $targetClass;
  1073.                 }
  1074.                 $joinColumns reset($assoc['joinColumns']);
  1075.                 $calc->addDependency($targetClass->name$class->name, (int) empty($joinColumns['nullable']));
  1076.                 // If the target class has mapped subclasses, these share the same dependency.
  1077.                 if (! $targetClass->subClasses) {
  1078.                     continue;
  1079.                 }
  1080.                 foreach ($targetClass->subClasses as $subClassName) {
  1081.                     $targetSubClass $this->em->getClassMetadata($subClassName);
  1082.                     if (! $calc->hasNode($subClassName)) {
  1083.                         $calc->addNode($targetSubClass->name$targetSubClass);
  1084.                         $newNodes[] = $targetSubClass;
  1085.                     }
  1086.                     $calc->addDependency($targetSubClass->name$class->name1);
  1087.                 }
  1088.             }
  1089.         }
  1090.         return $calc->sort();
  1091.     }
  1092.     /**
  1093.      * Schedules an entity for insertion into the database.
  1094.      * If the entity already has an identifier, it will be added to the identity map.
  1095.      *
  1096.      * @param object $entity The entity to schedule for insertion.
  1097.      *
  1098.      * @return void
  1099.      *
  1100.      * @throws ORMInvalidArgumentException
  1101.      * @throws InvalidArgumentException
  1102.      */
  1103.     public function scheduleForInsert($entity)
  1104.     {
  1105.         $oid spl_object_id($entity);
  1106.         if (isset($this->entityUpdates[$oid])) {
  1107.             throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
  1108.         }
  1109.         if (isset($this->entityDeletions[$oid])) {
  1110.             throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
  1111.         }
  1112.         if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1113.             throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
  1114.         }
  1115.         if (isset($this->entityInsertions[$oid])) {
  1116.             throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
  1117.         }
  1118.         $this->entityInsertions[$oid] = $entity;
  1119.         if (isset($this->entityIdentifiers[$oid])) {
  1120.             $this->addToIdentityMap($entity);
  1121.         }
  1122.         if ($entity instanceof NotifyPropertyChanged) {
  1123.             $entity->addPropertyChangedListener($this);
  1124.         }
  1125.     }
  1126.     /**
  1127.      * Checks whether an entity is scheduled for insertion.
  1128.      *
  1129.      * @param object $entity
  1130.      *
  1131.      * @return bool
  1132.      */
  1133.     public function isScheduledForInsert($entity)
  1134.     {
  1135.         return isset($this->entityInsertions[spl_object_id($entity)]);
  1136.     }
  1137.     /**
  1138.      * Schedules an entity for being updated.
  1139.      *
  1140.      * @param object $entity The entity to schedule for being updated.
  1141.      *
  1142.      * @return void
  1143.      *
  1144.      * @throws ORMInvalidArgumentException
  1145.      */
  1146.     public function scheduleForUpdate($entity)
  1147.     {
  1148.         $oid spl_object_id($entity);
  1149.         if (! isset($this->entityIdentifiers[$oid])) {
  1150.             throw ORMInvalidArgumentException::entityHasNoIdentity($entity'scheduling for update');
  1151.         }
  1152.         if (isset($this->entityDeletions[$oid])) {
  1153.             throw ORMInvalidArgumentException::entityIsRemoved($entity'schedule for update');
  1154.         }
  1155.         if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1156.             $this->entityUpdates[$oid] = $entity;
  1157.         }
  1158.     }
  1159.     /**
  1160.      * INTERNAL:
  1161.      * Schedules an extra update that will be executed immediately after the
  1162.      * regular entity updates within the currently running commit cycle.
  1163.      *
  1164.      * Extra updates for entities are stored as (entity, changeset) tuples.
  1165.      *
  1166.      * @param object $entity The entity for which to schedule an extra update.
  1167.      * @psalm-param array<string, array{mixed, mixed}>  $changeset The changeset of the entity (what to update).
  1168.      *
  1169.      * @return void
  1170.      *
  1171.      * @ignore
  1172.      */
  1173.     public function scheduleExtraUpdate($entity, array $changeset)
  1174.     {
  1175.         $oid         spl_object_id($entity);
  1176.         $extraUpdate = [$entity$changeset];
  1177.         if (isset($this->extraUpdates[$oid])) {
  1178.             [, $changeset2] = $this->extraUpdates[$oid];
  1179.             $extraUpdate = [$entity$changeset $changeset2];
  1180.         }
  1181.         $this->extraUpdates[$oid] = $extraUpdate;
  1182.     }
  1183.     /**
  1184.      * Checks whether an entity is registered as dirty in the unit of work.
  1185.      * Note: Is not very useful currently as dirty entities are only registered
  1186.      * at commit time.
  1187.      *
  1188.      * @param object $entity
  1189.      *
  1190.      * @return bool
  1191.      */
  1192.     public function isScheduledForUpdate($entity)
  1193.     {
  1194.         return isset($this->entityUpdates[spl_object_id($entity)]);
  1195.     }
  1196.     /**
  1197.      * Checks whether an entity is registered to be checked in the unit of work.
  1198.      *
  1199.      * @param object $entity
  1200.      *
  1201.      * @return bool
  1202.      */
  1203.     public function isScheduledForDirtyCheck($entity)
  1204.     {
  1205.         $rootEntityName $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  1206.         return isset($this->scheduledForSynchronization[$rootEntityName][spl_object_id($entity)]);
  1207.     }
  1208.     /**
  1209.      * INTERNAL:
  1210.      * Schedules an entity for deletion.
  1211.      *
  1212.      * @param object $entity
  1213.      *
  1214.      * @return void
  1215.      */
  1216.     public function scheduleForDelete($entity)
  1217.     {
  1218.         $oid spl_object_id($entity);
  1219.         if (isset($this->entityInsertions[$oid])) {
  1220.             if ($this->isInIdentityMap($entity)) {
  1221.                 $this->removeFromIdentityMap($entity);
  1222.             }
  1223.             unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
  1224.             return; // entity has not been persisted yet, so nothing more to do.
  1225.         }
  1226.         if (! $this->isInIdentityMap($entity)) {
  1227.             return;
  1228.         }
  1229.         $this->removeFromIdentityMap($entity);
  1230.         unset($this->entityUpdates[$oid]);
  1231.         if (! isset($this->entityDeletions[$oid])) {
  1232.             $this->entityDeletions[$oid] = $entity;
  1233.             $this->entityStates[$oid]    = self::STATE_REMOVED;
  1234.         }
  1235.     }
  1236.     /**
  1237.      * Checks whether an entity is registered as removed/deleted with the unit
  1238.      * of work.
  1239.      *
  1240.      * @param object $entity
  1241.      *
  1242.      * @return bool
  1243.      */
  1244.     public function isScheduledForDelete($entity)
  1245.     {
  1246.         return isset($this->entityDeletions[spl_object_id($entity)]);
  1247.     }
  1248.     /**
  1249.      * Checks whether an entity is scheduled for insertion, update or deletion.
  1250.      *
  1251.      * @param object $entity
  1252.      *
  1253.      * @return bool
  1254.      */
  1255.     public function isEntityScheduled($entity)
  1256.     {
  1257.         $oid spl_object_id($entity);
  1258.         return isset($this->entityInsertions[$oid])
  1259.             || isset($this->entityUpdates[$oid])
  1260.             || isset($this->entityDeletions[$oid]);
  1261.     }
  1262.     /**
  1263.      * INTERNAL:
  1264.      * Registers an entity in the identity map.
  1265.      * Note that entities in a hierarchy are registered with the class name of
  1266.      * the root entity.
  1267.      *
  1268.      * @param object $entity The entity to register.
  1269.      *
  1270.      * @return bool TRUE if the registration was successful, FALSE if the identity of
  1271.      * the entity in question is already managed.
  1272.      *
  1273.      * @throws ORMInvalidArgumentException
  1274.      *
  1275.      * @ignore
  1276.      */
  1277.     public function addToIdentityMap($entity)
  1278.     {
  1279.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1280.         $identifier    $this->entityIdentifiers[spl_object_id($entity)];
  1281.         if (empty($identifier) || in_array(null$identifiertrue)) {
  1282.             throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name$entity);
  1283.         }
  1284.         $idHash    implode(' '$identifier);
  1285.         $className $classMetadata->rootEntityName;
  1286.         if (isset($this->identityMap[$className][$idHash])) {
  1287.             return false;
  1288.         }
  1289.         $this->identityMap[$className][$idHash] = $entity;
  1290.         return true;
  1291.     }
  1292.     /**
  1293.      * Gets the state of an entity with regard to the current unit of work.
  1294.      *
  1295.      * @param object   $entity
  1296.      * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
  1297.      *                         This parameter can be set to improve performance of entity state detection
  1298.      *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
  1299.      *                         is either known or does not matter for the caller of the method.
  1300.      *
  1301.      * @return int The entity state.
  1302.      */
  1303.     public function getEntityState($entity$assume null)
  1304.     {
  1305.         $oid spl_object_id($entity);
  1306.         if (isset($this->entityStates[$oid])) {
  1307.             return $this->entityStates[$oid];
  1308.         }
  1309.         if ($assume !== null) {
  1310.             return $assume;
  1311.         }
  1312.         // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
  1313.         // Note that you can not remember the NEW or DETACHED state in _entityStates since
  1314.         // the UoW does not hold references to such objects and the object hash can be reused.
  1315.         // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
  1316.         $class $this->em->getClassMetadata(get_class($entity));
  1317.         $id    $class->getIdentifierValues($entity);
  1318.         if (! $id) {
  1319.             return self::STATE_NEW;
  1320.         }
  1321.         if ($class->containsForeignIdentifier) {
  1322.             $id $this->identifierFlattener->flattenIdentifier($class$id);
  1323.         }
  1324.         switch (true) {
  1325.             case $class->isIdentifierNatural():
  1326.                 // Check for a version field, if available, to avoid a db lookup.
  1327.                 if ($class->isVersioned) {
  1328.                     return $class->getFieldValue($entity$class->versionField)
  1329.                         ? self::STATE_DETACHED
  1330.                         self::STATE_NEW;
  1331.                 }
  1332.                 // Last try before db lookup: check the identity map.
  1333.                 if ($this->tryGetById($id$class->rootEntityName)) {
  1334.                     return self::STATE_DETACHED;
  1335.                 }
  1336.                 // db lookup
  1337.                 if ($this->getEntityPersister($class->name)->exists($entity)) {
  1338.                     return self::STATE_DETACHED;
  1339.                 }
  1340.                 return self::STATE_NEW;
  1341.             case ! $class->idGenerator->isPostInsertGenerator():
  1342.                 // if we have a pre insert generator we can't be sure that having an id
  1343.                 // really means that the entity exists. We have to verify this through
  1344.                 // the last resort: a db lookup
  1345.                 // Last try before db lookup: check the identity map.
  1346.                 if ($this->tryGetById($id$class->rootEntityName)) {
  1347.                     return self::STATE_DETACHED;
  1348.                 }
  1349.                 // db lookup
  1350.                 if ($this->getEntityPersister($class->name)->exists($entity)) {
  1351.                     return self::STATE_DETACHED;
  1352.                 }
  1353.                 return self::STATE_NEW;
  1354.             default:
  1355.                 return self::STATE_DETACHED;
  1356.         }
  1357.     }
  1358.     /**
  1359.      * INTERNAL:
  1360.      * Removes an entity from the identity map. This effectively detaches the
  1361.      * entity from the persistence management of Doctrine.
  1362.      *
  1363.      * @param object $entity
  1364.      *
  1365.      * @return bool
  1366.      *
  1367.      * @throws ORMInvalidArgumentException
  1368.      *
  1369.      * @ignore
  1370.      */
  1371.     public function removeFromIdentityMap($entity)
  1372.     {
  1373.         $oid           spl_object_id($entity);
  1374.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1375.         $idHash        implode(' '$this->entityIdentifiers[$oid]);
  1376.         if ($idHash === '') {
  1377.             throw ORMInvalidArgumentException::entityHasNoIdentity($entity'remove from identity map');
  1378.         }
  1379.         $className $classMetadata->rootEntityName;
  1380.         if (isset($this->identityMap[$className][$idHash])) {
  1381.             unset($this->identityMap[$className][$idHash], $this->readOnlyObjects[$oid]);
  1382.             //$this->entityStates[$oid] = self::STATE_DETACHED;
  1383.             return true;
  1384.         }
  1385.         return false;
  1386.     }
  1387.     /**
  1388.      * INTERNAL:
  1389.      * Gets an entity in the identity map by its identifier hash.
  1390.      *
  1391.      * @param string $idHash
  1392.      * @param string $rootClassName
  1393.      *
  1394.      * @return object
  1395.      *
  1396.      * @ignore
  1397.      */
  1398.     public function getByIdHash($idHash$rootClassName)
  1399.     {
  1400.         return $this->identityMap[$rootClassName][$idHash];
  1401.     }
  1402.     /**
  1403.      * INTERNAL:
  1404.      * Tries to get an entity by its identifier hash. If no entity is found for
  1405.      * the given hash, FALSE is returned.
  1406.      *
  1407.      * @param mixed  $idHash        (must be possible to cast it to string)
  1408.      * @param string $rootClassName
  1409.      *
  1410.      * @return false|object The found entity or FALSE.
  1411.      *
  1412.      * @ignore
  1413.      */
  1414.     public function tryGetByIdHash($idHash$rootClassName)
  1415.     {
  1416.         $stringIdHash = (string) $idHash;
  1417.         return $this->identityMap[$rootClassName][$stringIdHash] ?? false;
  1418.     }
  1419.     /**
  1420.      * Checks whether an entity is registered in the identity map of this UnitOfWork.
  1421.      *
  1422.      * @param object $entity
  1423.      *
  1424.      * @return bool
  1425.      */
  1426.     public function isInIdentityMap($entity)
  1427.     {
  1428.         $oid spl_object_id($entity);
  1429.         if (empty($this->entityIdentifiers[$oid])) {
  1430.             return false;
  1431.         }
  1432.         $classMetadata $this->em->getClassMetadata(get_class($entity));
  1433.         $idHash        implode(' '$this->entityIdentifiers[$oid]);
  1434.         return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
  1435.     }
  1436.     /**
  1437.      * INTERNAL:
  1438.      * Checks whether an identifier hash exists in the identity map.
  1439.      *
  1440.      * @param string $idHash
  1441.      * @param string $rootClassName
  1442.      *
  1443.      * @return bool
  1444.      *
  1445.      * @ignore
  1446.      */
  1447.     public function containsIdHash($idHash$rootClassName)
  1448.     {
  1449.         return isset($this->identityMap[$rootClassName][$idHash]);
  1450.     }
  1451.     /**
  1452.      * Persists an entity as part of the current unit of work.
  1453.      *
  1454.      * @param object $entity The entity to persist.
  1455.      *
  1456.      * @return void
  1457.      */
  1458.     public function persist($entity)
  1459.     {
  1460.         $visited = [];
  1461.         $this->doPersist($entity$visited);
  1462.     }
  1463.     /**
  1464.      * Persists an entity as part of the current unit of work.
  1465.      *
  1466.      * This method is internally called during persist() cascades as it tracks
  1467.      * the already visited entities to prevent infinite recursions.
  1468.      *
  1469.      * @param object $entity The entity to persist.
  1470.      * @psalm-param array<int, object> $visited The already visited entities.
  1471.      *
  1472.      * @throws ORMInvalidArgumentException
  1473.      * @throws UnexpectedValueException
  1474.      */
  1475.     private function doPersist($entity, array &$visited): void
  1476.     {
  1477.         $oid spl_object_id($entity);
  1478.         if (isset($visited[$oid])) {
  1479.             return; // Prevent infinite recursion
  1480.         }
  1481.         $visited[$oid] = $entity// Mark visited
  1482.         $class $this->em->getClassMetadata(get_class($entity));
  1483.         // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
  1484.         // If we would detect DETACHED here we would throw an exception anyway with the same
  1485.         // consequences (not recoverable/programming error), so just assuming NEW here
  1486.         // lets us avoid some database lookups for entities with natural identifiers.
  1487.         $entityState $this->getEntityState($entityself::STATE_NEW);
  1488.         switch ($entityState) {
  1489.             case self::STATE_MANAGED:
  1490.                 // Nothing to do, except if policy is "deferred explicit"
  1491.                 if ($class->isChangeTrackingDeferredExplicit()) {
  1492.                     $this->scheduleForDirtyCheck($entity);
  1493.                 }
  1494.                 break;
  1495.             case self::STATE_NEW:
  1496.                 $this->persistNew($class$entity);
  1497.                 break;
  1498.             case self::STATE_REMOVED:
  1499.                 // Entity becomes managed again
  1500.                 unset($this->entityDeletions[$oid]);
  1501.                 $this->addToIdentityMap($entity);
  1502.                 $this->entityStates[$oid] = self::STATE_MANAGED;
  1503.                 if ($class->isChangeTrackingDeferredExplicit()) {
  1504.                     $this->scheduleForDirtyCheck($entity);
  1505.                 }
  1506.                 break;
  1507.             case self::STATE_DETACHED:
  1508.                 // Can actually not happen right now since we assume STATE_NEW.
  1509.                 throw ORMInvalidArgumentException::detachedEntityCannot($entity'persisted');
  1510.             default:
  1511.                 throw new UnexpectedValueException(sprintf(
  1512.                     'Unexpected entity state: %s. %s',
  1513.                     $entityState,
  1514.                     self::objToStr($entity)
  1515.                 ));
  1516.         }
  1517.         $this->cascadePersist($entity$visited);
  1518.     }
  1519.     /**
  1520.      * Deletes an entity as part of the current unit of work.
  1521.      *
  1522.      * @param object $entity The entity to remove.
  1523.      *
  1524.      * @return void
  1525.      */
  1526.     public function remove($entity)
  1527.     {
  1528.         $visited = [];
  1529.         $this->doRemove($entity$visited);
  1530.     }
  1531.     /**
  1532.      * Deletes an entity as part of the current unit of work.
  1533.      *
  1534.      * This method is internally called during delete() cascades as it tracks
  1535.      * the already visited entities to prevent infinite recursions.
  1536.      *
  1537.      * @param object $entity The entity to delete.
  1538.      * @psalm-param array<int, object> $visited The map of the already visited entities.
  1539.      *
  1540.      * @throws ORMInvalidArgumentException If the instance is a detached entity.
  1541.      * @throws UnexpectedValueException
  1542.      */
  1543.     private function doRemove($entity, array &$visited): void
  1544.     {
  1545.         $oid spl_object_id($entity);
  1546.         if (isset($visited[$oid])) {
  1547.             return; // Prevent infinite recursion
  1548.         }
  1549.         $visited[$oid] = $entity// mark visited
  1550.         // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
  1551.         // can cause problems when a lazy proxy has to be initialized for the cascade operation.
  1552.         $this->cascadeRemove($entity$visited);
  1553.         $class       $this->em->getClassMetadata(get_class($entity));
  1554.         $entityState $this->getEntityState($entity);
  1555.         switch ($entityState) {
  1556.             case self::STATE_NEW:
  1557.             case self::STATE_REMOVED:
  1558.                 // nothing to do
  1559.                 break;
  1560.             case self::STATE_MANAGED:
  1561.                 $invoke $this->listenersInvoker->getSubscribedSystems($classEvents::preRemove);
  1562.                 if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  1563.                     $this->listenersInvoker->invoke($classEvents::preRemove$entity, new LifecycleEventArgs($entity$this->em), $invoke);
  1564.                 }
  1565.                 $this->scheduleForDelete($entity);
  1566.                 break;
  1567.             case self::STATE_DETACHED:
  1568.                 throw ORMInvalidArgumentException::detachedEntityCannot($entity'removed');
  1569.             default:
  1570.                 throw new UnexpectedValueException(sprintf(
  1571.                     'Unexpected entity state: %s. %s',
  1572.                     $entityState,
  1573.                     self::objToStr($entity)
  1574.                 ));
  1575.         }
  1576.     }
  1577.     /**
  1578.      * Merges the state of the given detached entity into this UnitOfWork.
  1579.      *
  1580.      * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
  1581.      *
  1582.      * @param object $entity
  1583.      *
  1584.      * @return object The managed copy of the entity.
  1585.      *
  1586.      * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1587.      *         attribute and the version check against the managed copy fails.
  1588.      */
  1589.     public function merge($entity)
  1590.     {
  1591.         $visited = [];
  1592.         return $this->doMerge($entity$visited);
  1593.     }
  1594.     /**
  1595.      * Executes a merge operation on an entity.
  1596.      *
  1597.      * @param object   $entity
  1598.      * @param string[] $assoc
  1599.      * @psalm-param array<int, object> $visited
  1600.      *
  1601.      * @return object The managed copy of the entity.
  1602.      *
  1603.      * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1604.      *         attribute and the version check against the managed copy fails.
  1605.      * @throws ORMInvalidArgumentException If the entity instance is NEW.
  1606.      * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided.
  1607.      */
  1608.     private function doMerge(
  1609.         $entity,
  1610.         array &$visited,
  1611.         $prevManagedCopy null,
  1612.         array $assoc = []
  1613.     ) {
  1614.         $oid spl_object_id($entity);
  1615.         if (isset($visited[$oid])) {
  1616.             $managedCopy $visited[$oid];
  1617.             if ($prevManagedCopy !== null) {
  1618.                 $this->updateAssociationWithMergedEntity($entity$assoc$prevManagedCopy$managedCopy);
  1619.             }
  1620.             return $managedCopy;
  1621.         }
  1622.         $class $this->em->getClassMetadata(get_class($entity));
  1623.         // First we assume DETACHED, although it can still be NEW but we can avoid
  1624.         // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
  1625.         // we need to fetch it from the db anyway in order to merge.
  1626.         // MANAGED entities are ignored by the merge operation.
  1627.         $managedCopy $entity;
  1628.         if ($this->getEntityState($entityself::STATE_DETACHED) !== self::STATE_MANAGED) {
  1629.             // Try to look the entity up in the identity map.
  1630.             $id $class->getIdentifierValues($entity);
  1631.             // If there is no ID, it is actually NEW.
  1632.             if (! $id) {
  1633.                 $managedCopy $this->newInstance($class);
  1634.                 $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1635.                 $this->persistNew($class$managedCopy);
  1636.             } else {
  1637.                 $flatId $class->containsForeignIdentifier
  1638.                     $this->identifierFlattener->flattenIdentifier($class$id)
  1639.                     : $id;
  1640.                 $managedCopy $this->tryGetById($flatId$class->rootEntityName);
  1641.                 if ($managedCopy) {
  1642.                     // We have the entity in-memory already, just make sure its not removed.
  1643.                     if ($this->getEntityState($managedCopy) === self::STATE_REMOVED) {
  1644.                         throw ORMInvalidArgumentException::entityIsRemoved($managedCopy'merge');
  1645.                     }
  1646.                 } else {
  1647.                     // We need to fetch the managed copy in order to merge.
  1648.                     $managedCopy $this->em->find($class->name$flatId);
  1649.                 }
  1650.                 if ($managedCopy === null) {
  1651.                     // If the identifier is ASSIGNED, it is NEW, otherwise an error
  1652.                     // since the managed entity was not found.
  1653.                     if (! $class->isIdentifierNatural()) {
  1654.                         throw EntityNotFoundException::fromClassNameAndIdentifier(
  1655.                             $class->getName(),
  1656.                             $this->identifierFlattener->flattenIdentifier($class$id)
  1657.                         );
  1658.                     }
  1659.                     $managedCopy $this->newInstance($class);
  1660.                     $class->setIdentifierValues($managedCopy$id);
  1661.                     $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1662.                     $this->persistNew($class$managedCopy);
  1663.                 } else {
  1664.                     $this->ensureVersionMatch($class$entity$managedCopy);
  1665.                     $this->mergeEntityStateIntoManagedCopy($entity$managedCopy);
  1666.                 }
  1667.             }
  1668.             $visited[$oid] = $managedCopy// mark visited
  1669.             if ($class->isChangeTrackingDeferredExplicit()) {
  1670.                 $this->scheduleForDirtyCheck($entity);
  1671.             }
  1672.         }
  1673.         if ($prevManagedCopy !== null) {
  1674.             $this->updateAssociationWithMergedEntity($entity$assoc$prevManagedCopy$managedCopy);
  1675.         }
  1676.         // Mark the managed copy visited as well
  1677.         $visited[spl_object_id($managedCopy)] = $managedCopy;
  1678.         $this->cascadeMerge($entity$managedCopy$visited);
  1679.         return $managedCopy;
  1680.     }
  1681.     /**
  1682.      * @param object $entity
  1683.      * @param object $managedCopy
  1684.      * @psalm-param ClassMetadata<T> $class
  1685.      * @psalm-param T $entity
  1686.      * @psalm-param T $managedCopy
  1687.      *
  1688.      * @throws OptimisticLockException
  1689.      *
  1690.      * @template T of object
  1691.      */
  1692.     private function ensureVersionMatch(
  1693.         ClassMetadata $class,
  1694.         $entity,
  1695.         $managedCopy
  1696.     ): void {
  1697.         if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) {
  1698.             return;
  1699.         }
  1700.         $reflField          $class->reflFields[$class->versionField];
  1701.         $managedCopyVersion $reflField->getValue($managedCopy);
  1702.         $entityVersion      $reflField->getValue($entity);
  1703.         // Throw exception if versions don't match.
  1704.         // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedEqualOperator
  1705.         if ($managedCopyVersion == $entityVersion) {
  1706.             return;
  1707.         }
  1708.         throw OptimisticLockException::lockFailedVersionMismatch($entity$entityVersion$managedCopyVersion);
  1709.     }
  1710.     /**
  1711.      * Tests if an entity is loaded - must either be a loaded proxy or not a proxy
  1712.      *
  1713.      * @param object $entity
  1714.      */
  1715.     private function isLoaded($entity): bool
  1716.     {
  1717.         return ! ($entity instanceof Proxy) || $entity->__isInitialized();
  1718.     }
  1719.     /**
  1720.      * Sets/adds associated managed copies into the previous entity's association field
  1721.      *
  1722.      * @param object   $entity
  1723.      * @param string[] $association
  1724.      */
  1725.     private function updateAssociationWithMergedEntity(
  1726.         $entity,
  1727.         array $association,
  1728.         $previousManagedCopy,
  1729.         $managedCopy
  1730.     ): void {
  1731.         $assocField $association['fieldName'];
  1732.         $prevClass  $this->em->getClassMetadata(get_class($previousManagedCopy));
  1733.         if ($association['type'] & ClassMetadata::TO_ONE) {
  1734.             $prevClass->reflFields[$assocField]->setValue($previousManagedCopy$managedCopy);
  1735.             return;
  1736.         }
  1737.         $value   $prevClass->reflFields[$assocField]->getValue($previousManagedCopy);
  1738.         $value[] = $managedCopy;
  1739.         if ($association['type'] === ClassMetadata::ONE_TO_MANY) {
  1740.             $class $this->em->getClassMetadata(get_class($entity));
  1741.             $class->reflFields[$association['mappedBy']]->setValue($managedCopy$previousManagedCopy);
  1742.         }
  1743.     }
  1744.     /**
  1745.      * Detaches an entity from the persistence management. It's persistence will
  1746.      * no longer be managed by Doctrine.
  1747.      *
  1748.      * @param object $entity The entity to detach.
  1749.      *
  1750.      * @return void
  1751.      */
  1752.     public function detach($entity)
  1753.     {
  1754.         $visited = [];
  1755.         $this->doDetach($entity$visited);
  1756.     }
  1757.     /**
  1758.      * Executes a detach operation on the given entity.
  1759.      *
  1760.      * @param object  $entity
  1761.      * @param mixed[] $visited
  1762.      * @param bool    $noCascade if true, don't cascade detach operation.
  1763.      */
  1764.     private function doDetach(
  1765.         $entity,
  1766.         array &$visited,
  1767.         bool $noCascade false
  1768.     ): void {
  1769.         $oid spl_object_id($entity);
  1770.         if (isset($visited[$oid])) {
  1771.             return; // Prevent infinite recursion
  1772.         }
  1773.         $visited[$oid] = $entity// mark visited
  1774.         switch ($this->getEntityState($entityself::STATE_DETACHED)) {
  1775.             case self::STATE_MANAGED:
  1776.                 if ($this->isInIdentityMap($entity)) {
  1777.                     $this->removeFromIdentityMap($entity);
  1778.                 }
  1779.                 unset(
  1780.                     $this->entityInsertions[$oid],
  1781.                     $this->entityUpdates[$oid],
  1782.                     $this->entityDeletions[$oid],
  1783.                     $this->entityIdentifiers[$oid],
  1784.                     $this->entityStates[$oid],
  1785.                     $this->originalEntityData[$oid]
  1786.                 );
  1787.                 break;
  1788.             case self::STATE_NEW:
  1789.             case self::STATE_DETACHED:
  1790.                 return;
  1791.         }
  1792.         if (! $noCascade) {
  1793.             $this->cascadeDetach($entity$visited);
  1794.         }
  1795.     }
  1796.     /**
  1797.      * Refreshes the state of the given entity from the database, overwriting
  1798.      * any local, unpersisted changes.
  1799.      *
  1800.      * @param object $entity The entity to refresh.
  1801.      *
  1802.      * @return void
  1803.      *
  1804.      * @throws InvalidArgumentException If the entity is not MANAGED.
  1805.      */
  1806.     public function refresh($entity)
  1807.     {
  1808.         $visited = [];
  1809.         $this->doRefresh($entity$visited);
  1810.     }
  1811.     /**
  1812.      * Executes a refresh operation on an entity.
  1813.      *
  1814.      * @param object $entity The entity to refresh.
  1815.      * @psalm-param array<int, object>  $visited The already visited entities during cascades.
  1816.      *
  1817.      * @throws ORMInvalidArgumentException If the entity is not MANAGED.
  1818.      */
  1819.     private function doRefresh($entity, array &$visited): void
  1820.     {
  1821.         $oid spl_object_id($entity);
  1822.         if (isset($visited[$oid])) {
  1823.             return; // Prevent infinite recursion
  1824.         }
  1825.         $visited[$oid] = $entity// mark visited
  1826.         $class $this->em->getClassMetadata(get_class($entity));
  1827.         if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
  1828.             throw ORMInvalidArgumentException::entityNotManaged($entity);
  1829.         }
  1830.         $this->getEntityPersister($class->name)->refresh(
  1831.             array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1832.             $entity
  1833.         );
  1834.         $this->cascadeRefresh($entity$visited);
  1835.     }
  1836.     /**
  1837.      * Cascades a refresh operation to associated entities.
  1838.      *
  1839.      * @param object $entity
  1840.      * @psalm-param array<int, object> $visited
  1841.      */
  1842.     private function cascadeRefresh($entity, array &$visited): void
  1843.     {
  1844.         $class $this->em->getClassMetadata(get_class($entity));
  1845.         $associationMappings array_filter(
  1846.             $class->associationMappings,
  1847.             static function ($assoc) {
  1848.                 return $assoc['isCascadeRefresh'];
  1849.             }
  1850.         );
  1851.         foreach ($associationMappings as $assoc) {
  1852.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1853.             switch (true) {
  1854.                 case $relatedEntities instanceof PersistentCollection:
  1855.                     // Unwrap so that foreach() does not initialize
  1856.                     $relatedEntities $relatedEntities->unwrap();
  1857.                     // break; is commented intentionally!
  1858.                 case $relatedEntities instanceof Collection:
  1859.                 case is_array($relatedEntities):
  1860.                     foreach ($relatedEntities as $relatedEntity) {
  1861.                         $this->doRefresh($relatedEntity$visited);
  1862.                     }
  1863.                     break;
  1864.                 case $relatedEntities !== null:
  1865.                     $this->doRefresh($relatedEntities$visited);
  1866.                     break;
  1867.                 default:
  1868.                     // Do nothing
  1869.             }
  1870.         }
  1871.     }
  1872.     /**
  1873.      * Cascades a detach operation to associated entities.
  1874.      *
  1875.      * @param object             $entity
  1876.      * @param array<int, object> $visited
  1877.      */
  1878.     private function cascadeDetach($entity, array &$visited): void
  1879.     {
  1880.         $class $this->em->getClassMetadata(get_class($entity));
  1881.         $associationMappings array_filter(
  1882.             $class->associationMappings,
  1883.             static function ($assoc) {
  1884.                 return $assoc['isCascadeDetach'];
  1885.             }
  1886.         );
  1887.         foreach ($associationMappings as $assoc) {
  1888.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1889.             switch (true) {
  1890.                 case $relatedEntities instanceof PersistentCollection:
  1891.                     // Unwrap so that foreach() does not initialize
  1892.                     $relatedEntities $relatedEntities->unwrap();
  1893.                     // break; is commented intentionally!
  1894.                 case $relatedEntities instanceof Collection:
  1895.                 case is_array($relatedEntities):
  1896.                     foreach ($relatedEntities as $relatedEntity) {
  1897.                         $this->doDetach($relatedEntity$visited);
  1898.                     }
  1899.                     break;
  1900.                 case $relatedEntities !== null:
  1901.                     $this->doDetach($relatedEntities$visited);
  1902.                     break;
  1903.                 default:
  1904.                     // Do nothing
  1905.             }
  1906.         }
  1907.     }
  1908.     /**
  1909.      * Cascades a merge operation to associated entities.
  1910.      *
  1911.      * @param object $entity
  1912.      * @param object $managedCopy
  1913.      * @psalm-param array<int, object> $visited
  1914.      */
  1915.     private function cascadeMerge($entity$managedCopy, array &$visited): void
  1916.     {
  1917.         $class $this->em->getClassMetadata(get_class($entity));
  1918.         $associationMappings array_filter(
  1919.             $class->associationMappings,
  1920.             static function ($assoc) {
  1921.                 return $assoc['isCascadeMerge'];
  1922.             }
  1923.         );
  1924.         foreach ($associationMappings as $assoc) {
  1925.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1926.             if ($relatedEntities instanceof Collection) {
  1927.                 if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
  1928.                     continue;
  1929.                 }
  1930.                 if ($relatedEntities instanceof PersistentCollection) {
  1931.                     // Unwrap so that foreach() does not initialize
  1932.                     $relatedEntities $relatedEntities->unwrap();
  1933.                 }
  1934.                 foreach ($relatedEntities as $relatedEntity) {
  1935.                     $this->doMerge($relatedEntity$visited$managedCopy$assoc);
  1936.                 }
  1937.             } elseif ($relatedEntities !== null) {
  1938.                 $this->doMerge($relatedEntities$visited$managedCopy$assoc);
  1939.             }
  1940.         }
  1941.     }
  1942.     /**
  1943.      * Cascades the save operation to associated entities.
  1944.      *
  1945.      * @param object $entity
  1946.      * @psalm-param array<int, object> $visited
  1947.      */
  1948.     private function cascadePersist($entity, array &$visited): void
  1949.     {
  1950.         $class $this->em->getClassMetadata(get_class($entity));
  1951.         $associationMappings array_filter(
  1952.             $class->associationMappings,
  1953.             static function ($assoc) {
  1954.                 return $assoc['isCascadePersist'];
  1955.             }
  1956.         );
  1957.         foreach ($associationMappings as $assoc) {
  1958.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1959.             switch (true) {
  1960.                 case $relatedEntities instanceof PersistentCollection:
  1961.                     // Unwrap so that foreach() does not initialize
  1962.                     $relatedEntities $relatedEntities->unwrap();
  1963.                     // break; is commented intentionally!
  1964.                 case $relatedEntities instanceof Collection:
  1965.                 case is_array($relatedEntities):
  1966.                     if (($assoc['type'] & ClassMetadata::TO_MANY) <= 0) {
  1967.                         throw ORMInvalidArgumentException::invalidAssociation(
  1968.                             $this->em->getClassMetadata($assoc['targetEntity']),
  1969.                             $assoc,
  1970.                             $relatedEntities
  1971.                         );
  1972.                     }
  1973.                     foreach ($relatedEntities as $relatedEntity) {
  1974.                         $this->doPersist($relatedEntity$visited);
  1975.                     }
  1976.                     break;
  1977.                 case $relatedEntities !== null:
  1978.                     if (! $relatedEntities instanceof $assoc['targetEntity']) {
  1979.                         throw ORMInvalidArgumentException::invalidAssociation(
  1980.                             $this->em->getClassMetadata($assoc['targetEntity']),
  1981.                             $assoc,
  1982.                             $relatedEntities
  1983.                         );
  1984.                     }
  1985.                     $this->doPersist($relatedEntities$visited);
  1986.                     break;
  1987.                 default:
  1988.                     // Do nothing
  1989.             }
  1990.         }
  1991.     }
  1992.     /**
  1993.      * Cascades the delete operation to associated entities.
  1994.      *
  1995.      * @param object $entity
  1996.      * @psalm-param array<int, object> $visited
  1997.      */
  1998.     private function cascadeRemove($entity, array &$visited): void
  1999.     {
  2000.         $class $this->em->getClassMetadata(get_class($entity));
  2001.         $associationMappings array_filter(
  2002.             $class->associationMappings,
  2003.             static function ($assoc) {
  2004.                 return $assoc['isCascadeRemove'];
  2005.             }
  2006.         );
  2007.         $entitiesToCascade = [];
  2008.         foreach ($associationMappings as $assoc) {
  2009.             if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  2010.                 $entity->__load();
  2011.             }
  2012.             $relatedEntities $class->reflFields[$assoc['fieldName']]->getValue($entity);
  2013.             switch (true) {
  2014.                 case $relatedEntities instanceof Collection:
  2015.                 case is_array($relatedEntities):
  2016.                     // If its a PersistentCollection initialization is intended! No unwrap!
  2017.                     foreach ($relatedEntities as $relatedEntity) {
  2018.                         $entitiesToCascade[] = $relatedEntity;
  2019.                     }
  2020.                     break;
  2021.                 case $relatedEntities !== null:
  2022.                     $entitiesToCascade[] = $relatedEntities;
  2023.                     break;
  2024.                 default:
  2025.                     // Do nothing
  2026.             }
  2027.         }
  2028.         foreach ($entitiesToCascade as $relatedEntity) {
  2029.             $this->doRemove($relatedEntity$visited);
  2030.         }
  2031.     }
  2032.     /**
  2033.      * Acquire a lock on the given entity.
  2034.      *
  2035.      * @param object                     $entity
  2036.      * @param int|DateTimeInterface|null $lockVersion
  2037.      *
  2038.      * @throws ORMInvalidArgumentException
  2039.      * @throws TransactionRequiredException
  2040.      * @throws OptimisticLockException
  2041.      */
  2042.     public function lock($entityint $lockMode$lockVersion null): void
  2043.     {
  2044.         if ($this->getEntityState($entityself::STATE_DETACHED) !== self::STATE_MANAGED) {
  2045.             throw ORMInvalidArgumentException::entityNotManaged($entity);
  2046.         }
  2047.         $class $this->em->getClassMetadata(get_class($entity));
  2048.         switch (true) {
  2049.             case $lockMode === LockMode::OPTIMISTIC:
  2050.                 if (! $class->isVersioned) {
  2051.                     throw OptimisticLockException::notVersioned($class->name);
  2052.                 }
  2053.                 if ($lockVersion === null) {
  2054.                     return;
  2055.                 }
  2056.                 if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  2057.                     $entity->__load();
  2058.                 }
  2059.                 $entityVersion $class->reflFields[$class->versionField]->getValue($entity);
  2060.                 // phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedNotEqualOperator
  2061.                 if ($entityVersion != $lockVersion) {
  2062.                     throw OptimisticLockException::lockFailedVersionMismatch($entity$lockVersion$entityVersion);
  2063.                 }
  2064.                 break;
  2065.             case $lockMode === LockMode::NONE:
  2066.             case $lockMode === LockMode::PESSIMISTIC_READ:
  2067.             case $lockMode === LockMode::PESSIMISTIC_WRITE:
  2068.                 if (! $this->em->getConnection()->isTransactionActive()) {
  2069.                     throw TransactionRequiredException::transactionRequired();
  2070.                 }
  2071.                 $oid spl_object_id($entity);
  2072.                 $this->getEntityPersister($class->name)->lock(
  2073.                     array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  2074.                     $lockMode
  2075.                 );
  2076.                 break;
  2077.             default:
  2078.                 // Do nothing
  2079.         }
  2080.     }
  2081.     /**
  2082.      * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
  2083.      *
  2084.      * @return CommitOrderCalculator
  2085.      */
  2086.     public function getCommitOrderCalculator()
  2087.     {
  2088.         return new Internal\CommitOrderCalculator();
  2089.     }
  2090.     /**
  2091.      * Clears the UnitOfWork.
  2092.      *
  2093.      * @param string|null $entityName if given, only entities of this type will get detached.
  2094.      *
  2095.      * @return void
  2096.      *
  2097.      * @throws ORMInvalidArgumentException if an invalid entity name is given.
  2098.      */
  2099.     public function clear($entityName null)
  2100.     {
  2101.         if ($entityName === null) {
  2102.             $this->identityMap                    =
  2103.             $this->entityIdentifiers              =
  2104.             $this->originalEntityData             =
  2105.             $this->entityChangeSets               =
  2106.             $this->entityStates                   =
  2107.             $this->scheduledForSynchronization    =
  2108.             $this->entityInsertions               =
  2109.             $this->entityUpdates                  =
  2110.             $this->entityDeletions                =
  2111.             $this->nonCascadedNewDetectedEntities =
  2112.             $this->collectionDeletions            =
  2113.             $this->collectionUpdates              =
  2114.             $this->extraUpdates                   =
  2115.             $this->readOnlyObjects                =
  2116.             $this->visitedCollections             =
  2117.             $this->eagerLoadingEntities           =
  2118.             $this->orphanRemovals                 = [];
  2119.         } else {
  2120.             $this->clearIdentityMapForEntityName($entityName);
  2121.             $this->clearEntityInsertionsForEntityName($entityName);
  2122.         }
  2123.         if ($this->evm->hasListeners(Events::onClear)) {
  2124.             $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em$entityName));
  2125.         }
  2126.     }
  2127.     /**
  2128.      * INTERNAL:
  2129.      * Schedules an orphaned entity for removal. The remove() operation will be
  2130.      * invoked on that entity at the beginning of the next commit of this
  2131.      * UnitOfWork.
  2132.      *
  2133.      * @param object $entity
  2134.      *
  2135.      * @return void
  2136.      *
  2137.      * @ignore
  2138.      */
  2139.     public function scheduleOrphanRemoval($entity)
  2140.     {
  2141.         $this->orphanRemovals[spl_object_id($entity)] = $entity;
  2142.     }
  2143.     /**
  2144.      * INTERNAL:
  2145.      * Cancels a previously scheduled orphan removal.
  2146.      *
  2147.      * @param object $entity
  2148.      *
  2149.      * @return void
  2150.      *
  2151.      * @ignore
  2152.      */
  2153.     public function cancelOrphanRemoval($entity)
  2154.     {
  2155.         unset($this->orphanRemovals[spl_object_id($entity)]);
  2156.     }
  2157.     /**
  2158.      * INTERNAL:
  2159.      * Schedules a complete collection for removal when this UnitOfWork commits.
  2160.      *
  2161.      * @return void
  2162.      */
  2163.     public function scheduleCollectionDeletion(PersistentCollection $coll)
  2164.     {
  2165.         $coid spl_object_id($coll);
  2166.         // TODO: if $coll is already scheduled for recreation ... what to do?
  2167.         // Just remove $coll from the scheduled recreations?
  2168.         unset($this->collectionUpdates[$coid]);
  2169.         $this->collectionDeletions[$coid] = $coll;
  2170.     }
  2171.     /**
  2172.      * @return bool
  2173.      */
  2174.     public function isCollectionScheduledForDeletion(PersistentCollection $coll)
  2175.     {
  2176.         return isset($this->collectionDeletions[spl_object_id($coll)]);
  2177.     }
  2178.     /**
  2179.      * @return object
  2180.      */
  2181.     private function newInstance(ClassMetadata $class)
  2182.     {
  2183.         $entity $class->newInstance();
  2184.         if ($entity instanceof ObjectManagerAware) {
  2185.             $entity->injectObjectManager($this->em$class);
  2186.         }
  2187.         return $entity;
  2188.     }
  2189.     /**
  2190.      * INTERNAL:
  2191.      * Creates an entity. Used for reconstitution of persistent entities.
  2192.      *
  2193.      * Internal note: Highly performance-sensitive method.
  2194.      *
  2195.      * @param string  $className The name of the entity class.
  2196.      * @param mixed[] $data      The data for the entity.
  2197.      * @param mixed[] $hints     Any hints to account for during reconstitution/lookup of the entity.
  2198.      * @psalm-param class-string $className
  2199.      * @psalm-param array<string, mixed> $hints
  2200.      *
  2201.      * @return object The managed entity instance.
  2202.      *
  2203.      * @ignore
  2204.      * @todo Rename: getOrCreateEntity
  2205.      */
  2206.     public function createEntity($className, array $data, &$hints = [])
  2207.     {
  2208.         $class $this->em->getClassMetadata($className);
  2209.         $id     $this->identifierFlattener->flattenIdentifier($class$data);
  2210.         $idHash implode(' '$id);
  2211.         if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
  2212.             $entity $this->identityMap[$class->rootEntityName][$idHash];
  2213.             $oid    spl_object_id($entity);
  2214.             if (
  2215.                 isset($hints[Query::HINT_REFRESH], $hints[Query::HINT_REFRESH_ENTITY])
  2216.             ) {
  2217.                 $unmanagedProxy $hints[Query::HINT_REFRESH_ENTITY];
  2218.                 if (
  2219.                     $unmanagedProxy !== $entity
  2220.                     && $unmanagedProxy instanceof Proxy
  2221.                     && $this->isIdentifierEquals($unmanagedProxy$entity)
  2222.                 ) {
  2223.                     // DDC-1238 - we have a managed instance, but it isn't the provided one.
  2224.                     // Therefore we clear its identifier. Also, we must re-fetch metadata since the
  2225.                     // refreshed object may be anything
  2226.                     foreach ($class->identifier as $fieldName) {
  2227.                         $class->reflFields[$fieldName]->setValue($unmanagedProxynull);
  2228.                     }
  2229.                     return $unmanagedProxy;
  2230.                 }
  2231.             }
  2232.             if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  2233.                 $entity->__setInitialized(true);
  2234.                 if ($entity instanceof NotifyPropertyChanged) {
  2235.                     $entity->addPropertyChangedListener($this);
  2236.                 }
  2237.             } else {
  2238.                 if (
  2239.                     ! isset($hints[Query::HINT_REFRESH])
  2240.                     || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)
  2241.                 ) {
  2242.                     return $entity;
  2243.                 }
  2244.             }
  2245.             // inject ObjectManager upon refresh.
  2246.             if ($entity instanceof ObjectManagerAware) {
  2247.                 $entity->injectObjectManager($this->em$class);
  2248.             }
  2249.             $this->originalEntityData[$oid] = $data;
  2250.         } else {
  2251.             $entity $this->newInstance($class);
  2252.             $oid    spl_object_id($entity);
  2253.             $this->entityIdentifiers[$oid]  = $id;
  2254.             $this->entityStates[$oid]       = self::STATE_MANAGED;
  2255.             $this->originalEntityData[$oid] = $data;
  2256.             $this->identityMap[$class->rootEntityName][$idHash] = $entity;
  2257.             if ($entity instanceof NotifyPropertyChanged) {
  2258.                 $entity->addPropertyChangedListener($this);
  2259.             }
  2260.             if (isset($hints[Query::HINT_READ_ONLY])) {
  2261.                 $this->readOnlyObjects[$oid] = true;
  2262.             }
  2263.         }
  2264.         foreach ($data as $field => $value) {
  2265.             if (isset($class->fieldMappings[$field])) {
  2266.                 $class->reflFields[$field]->setValue($entity$value);
  2267.             }
  2268.         }
  2269.         // Loading the entity right here, if its in the eager loading map get rid of it there.
  2270.         unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
  2271.         if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
  2272.             unset($this->eagerLoadingEntities[$class->rootEntityName]);
  2273.         }
  2274.         // Properly initialize any unfetched associations, if partial objects are not allowed.
  2275.         if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
  2276.             Deprecation::trigger(
  2277.                 'doctrine/orm',
  2278.                 'https://github.com/doctrine/orm/issues/8471',
  2279.                 'Partial Objects are deprecated (here entity %s)',
  2280.                 $className
  2281.             );
  2282.             return $entity;
  2283.         }
  2284.         foreach ($class->associationMappings as $field => $assoc) {
  2285.             // Check if the association is not among the fetch-joined associations already.
  2286.             if (isset($hints['fetchAlias'], $hints['fetched'][$hints['fetchAlias']][$field])) {
  2287.                 continue;
  2288.             }
  2289.             $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  2290.             switch (true) {
  2291.                 case $assoc['type'] & ClassMetadata::TO_ONE:
  2292.                     if (! $assoc['isOwningSide']) {
  2293.                         // use the given entity association
  2294.                         if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_id($data[$field])])) {
  2295.                             $this->originalEntityData[$oid][$field] = $data[$field];
  2296.                             $class->reflFields[$field]->setValue($entity$data[$field]);
  2297.                             $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity);
  2298.                             continue 2;
  2299.                         }
  2300.                         // Inverse side of x-to-one can never be lazy
  2301.                         $class->reflFields[$field]->setValue($entity$this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc$entity));
  2302.                         continue 2;
  2303.                     }
  2304.                     // use the entity association
  2305.                     if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_id($data[$field])])) {
  2306.                         $class->reflFields[$field]->setValue($entity$data[$field]);
  2307.                         $this->originalEntityData[$oid][$field] = $data[$field];
  2308.                         break;
  2309.                     }
  2310.                     $associatedId = [];
  2311.                     // TODO: Is this even computed right in all cases of composite keys?
  2312.                     foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
  2313.                         $joinColumnValue $data[$srcColumn] ?? null;
  2314.                         if ($joinColumnValue !== null) {
  2315.                             if ($targetClass->containsForeignIdentifier) {
  2316.                                 $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
  2317.                             } else {
  2318.                                 $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
  2319.                             }
  2320.                         } elseif (
  2321.                             $targetClass->containsForeignIdentifier
  2322.                             && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifiertrue)
  2323.                         ) {
  2324.                             // the missing key is part of target's entity primary key
  2325.                             $associatedId = [];
  2326.                             break;
  2327.                         }
  2328.                     }
  2329.                     if (! $associatedId) {
  2330.                         // Foreign key is NULL
  2331.                         $class->reflFields[$field]->setValue($entitynull);
  2332.                         $this->originalEntityData[$oid][$field] = null;
  2333.                         break;
  2334.                     }
  2335.                     if (! isset($hints['fetchMode'][$class->name][$field])) {
  2336.                         $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
  2337.                     }
  2338.                     // Foreign key is set
  2339.                     // Check identity map first
  2340.                     // FIXME: Can break easily with composite keys if join column values are in
  2341.                     //        wrong order. The correct order is the one in ClassMetadata#identifier.
  2342.                     $relatedIdHash implode(' '$associatedId);
  2343.                     switch (true) {
  2344.                         case isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash]):
  2345.                             $newValue $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
  2346.                             // If this is an uninitialized proxy, we are deferring eager loads,
  2347.                             // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
  2348.                             // then we can append this entity for eager loading!
  2349.                             if (
  2350.                                 $hints['fetchMode'][$class->name][$field] === ClassMetadata::FETCH_EAGER &&
  2351.                                 isset($hints[self::HINT_DEFEREAGERLOAD]) &&
  2352.                                 ! $targetClass->isIdentifierComposite &&
  2353.                                 $newValue instanceof Proxy &&
  2354.                                 $newValue->__isInitialized() === false
  2355.                             ) {
  2356.                                 $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2357.                             }
  2358.                             break;
  2359.                         case $targetClass->subClasses:
  2360.                             // If it might be a subtype, it can not be lazy. There isn't even
  2361.                             // a way to solve this with deferred eager loading, which means putting
  2362.                             // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
  2363.                             $newValue $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc$entity$associatedId);
  2364.                             break;
  2365.                         default:
  2366.                             switch (true) {
  2367.                                 // We are negating the condition here. Other cases will assume it is valid!
  2368.                                 case $hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER:
  2369.                                     $newValue $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2370.                                     break;
  2371.                                 // Deferred eager load only works for single identifier classes
  2372.                                 case isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite:
  2373.                                     // TODO: Is there a faster approach?
  2374.                                     $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2375.                                     $newValue $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2376.                                     break;
  2377.                                 default:
  2378.                                     // TODO: This is very imperformant, ignore it?
  2379.                                     $newValue $this->em->find($assoc['targetEntity'], $associatedId);
  2380.                                     break;
  2381.                             }
  2382.                             if ($newValue === null) {
  2383.                                 break;
  2384.                             }
  2385.                             // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
  2386.                             $newValueOid                                                     spl_object_id($newValue);
  2387.                             $this->entityIdentifiers[$newValueOid]                           = $associatedId;
  2388.                             $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
  2389.                             if (
  2390.                                 $newValue instanceof NotifyPropertyChanged &&
  2391.                                 ( ! $newValue instanceof Proxy || $newValue->__isInitialized())
  2392.                             ) {
  2393.                                 $newValue->addPropertyChangedListener($this);
  2394.                             }
  2395.                             $this->entityStates[$newValueOid] = self::STATE_MANAGED;
  2396.                             // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
  2397.                             break;
  2398.                     }
  2399.                     $this->originalEntityData[$oid][$field] = $newValue;
  2400.                     $class->reflFields[$field]->setValue($entity$newValue);
  2401.                     if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE && $newValue !== null) {
  2402.                         $inverseAssoc $targetClass->associationMappings[$assoc['inversedBy']];
  2403.                         $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue$entity);
  2404.                     }
  2405.                     break;
  2406.                 default:
  2407.                     // Ignore if its a cached collection
  2408.                     if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity$field) instanceof PersistentCollection) {
  2409.                         break;
  2410.                     }
  2411.                     // use the given collection
  2412.                     if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
  2413.                         $data[$field]->setOwner($entity$assoc);
  2414.                         $class->reflFields[$field]->setValue($entity$data[$field]);
  2415.                         $this->originalEntityData[$oid][$field] = $data[$field];
  2416.                         break;
  2417.                     }
  2418.                     // Inject collection
  2419.                     $pColl = new PersistentCollection($this->em$targetClass, new ArrayCollection());
  2420.                     $pColl->setOwner($entity$assoc);
  2421.                     $pColl->setInitialized(false);
  2422.                     $reflField $class->reflFields[$field];
  2423.                     $reflField->setValue($entity$pColl);
  2424.                     if ($assoc['fetch'] === ClassMetadata::FETCH_EAGER) {
  2425.                         $this->loadCollection($pColl);
  2426.                         $pColl->takeSnapshot();
  2427.                     }
  2428.                     $this->originalEntityData[$oid][$field] = $pColl;
  2429.                     break;
  2430.             }
  2431.         }
  2432.         // defer invoking of postLoad event to hydration complete step
  2433.         $this->hydrationCompleteHandler->deferPostLoadInvoking($class$entity);
  2434.         return $entity;
  2435.     }
  2436.     /**
  2437.      * @return void
  2438.      */
  2439.     public function triggerEagerLoads()
  2440.     {
  2441.         if (! $this->eagerLoadingEntities) {
  2442.             return;
  2443.         }
  2444.         // avoid infinite recursion
  2445.         $eagerLoadingEntities       $this->eagerLoadingEntities;
  2446.         $this->eagerLoadingEntities = [];
  2447.         foreach ($eagerLoadingEntities as $entityName => $ids) {
  2448.             if (! $ids) {
  2449.                 continue;
  2450.             }
  2451.             $class $this->em->getClassMetadata($entityName);
  2452.             $this->getEntityPersister($entityName)->loadAll(
  2453.                 array_combine($class->identifier, [array_values($ids)])
  2454.             );
  2455.         }
  2456.     }
  2457.     /**
  2458.      * Initializes (loads) an uninitialized persistent collection of an entity.
  2459.      *
  2460.      * @param PersistentCollection $collection The collection to initialize.
  2461.      *
  2462.      * @return void
  2463.      *
  2464.      * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
  2465.      */
  2466.     public function loadCollection(PersistentCollection $collection)
  2467.     {
  2468.         $assoc     $collection->getMapping();
  2469.         $persister $this->getEntityPersister($assoc['targetEntity']);
  2470.         switch ($assoc['type']) {
  2471.             case ClassMetadata::ONE_TO_MANY:
  2472.                 $persister->loadOneToManyCollection($assoc$collection->getOwner(), $collection);
  2473.                 break;
  2474.             case ClassMetadata::MANY_TO_MANY:
  2475.                 $persister->loadManyToManyCollection($assoc$collection->getOwner(), $collection);
  2476.                 break;
  2477.         }
  2478.         $collection->setInitialized(true);
  2479.     }
  2480.     /**
  2481.      * Gets the identity map of the UnitOfWork.
  2482.      *
  2483.      * @psalm-return array<class-string, array<string, object|null>>
  2484.      */
  2485.     public function getIdentityMap()
  2486.     {
  2487.         return $this->identityMap;
  2488.     }
  2489.     /**
  2490.      * Gets the original data of an entity. The original data is the data that was
  2491.      * present at the time the entity was reconstituted from the database.
  2492.      *
  2493.      * @param object $entity
  2494.      *
  2495.      * @return mixed[]
  2496.      * @psalm-return array<string, mixed>
  2497.      */
  2498.     public function getOriginalEntityData($entity)
  2499.     {
  2500.         $oid spl_object_id($entity);
  2501.         return $this->originalEntityData[$oid] ?? [];
  2502.     }
  2503.     /**
  2504.      * @param object  $entity
  2505.      * @param mixed[] $data
  2506.      *
  2507.      * @return void
  2508.      *
  2509.      * @ignore
  2510.      */
  2511.     public function setOriginalEntityData($entity, array $data)
  2512.     {
  2513.         $this->originalEntityData[spl_object_id($entity)] = $data;
  2514.     }
  2515.     /**
  2516.      * INTERNAL:
  2517.      * Sets a property value of the original data array of an entity.
  2518.      *
  2519.      * @param int    $oid
  2520.      * @param string $property
  2521.      * @param mixed  $value
  2522.      *
  2523.      * @return void
  2524.      *
  2525.      * @ignore
  2526.      */
  2527.     public function setOriginalEntityProperty($oid$property$value)
  2528.     {
  2529.         $this->originalEntityData[$oid][$property] = $value;
  2530.     }
  2531.     /**
  2532.      * Gets the identifier of an entity.
  2533.      * The returned value is always an array of identifier values. If the entity
  2534.      * has a composite identifier then the identifier values are in the same
  2535.      * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
  2536.      *
  2537.      * @param object $entity
  2538.      *
  2539.      * @return mixed[] The identifier values.
  2540.      */
  2541.     public function getEntityIdentifier($entity)
  2542.     {
  2543.         if (! isset($this->entityIdentifiers[spl_object_id($entity)])) {
  2544.             throw EntityNotFoundException::noIdentifierFound(get_class($entity));
  2545.         }
  2546.         return $this->entityIdentifiers[spl_object_id($entity)];
  2547.     }
  2548.     /**
  2549.      * Processes an entity instance to extract their identifier values.
  2550.      *
  2551.      * @param object $entity The entity instance.
  2552.      *
  2553.      * @return mixed A scalar value.
  2554.      *
  2555.      * @throws ORMInvalidArgumentException
  2556.      */
  2557.     public function getSingleIdentifierValue($entity)
  2558.     {
  2559.         $class $this->em->getClassMetadata(get_class($entity));
  2560.         if ($class->isIdentifierComposite) {
  2561.             throw ORMInvalidArgumentException::invalidCompositeIdentifier();
  2562.         }
  2563.         $values $this->isInIdentityMap($entity)
  2564.             ? $this->getEntityIdentifier($entity)
  2565.             : $class->getIdentifierValues($entity);
  2566.         return $values[$class->identifier[0]] ?? null;
  2567.     }
  2568.     /**
  2569.      * Tries to find an entity with the given identifier in the identity map of
  2570.      * this UnitOfWork.
  2571.      *
  2572.      * @param mixed  $id            The entity identifier to look for.
  2573.      * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
  2574.      * @psalm-param class-string $rootClassName
  2575.      *
  2576.      * @return object|false Returns the entity with the specified identifier if it exists in
  2577.      *                      this UnitOfWork, FALSE otherwise.
  2578.      */
  2579.     public function tryGetById($id$rootClassName)
  2580.     {
  2581.         $idHash implode(' ', (array) $id);
  2582.         return $this->identityMap[$rootClassName][$idHash] ?? false;
  2583.     }
  2584.     /**
  2585.      * Schedules an entity for dirty-checking at commit-time.
  2586.      *
  2587.      * @param object $entity The entity to schedule for dirty-checking.
  2588.      *
  2589.      * @return void
  2590.      *
  2591.      * @todo Rename: scheduleForSynchronization
  2592.      */
  2593.     public function scheduleForDirtyCheck($entity)
  2594.     {
  2595.         $rootClassName $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  2596.         $this->scheduledForSynchronization[$rootClassName][spl_object_id($entity)] = $entity;
  2597.     }
  2598.     /**
  2599.      * Checks whether the UnitOfWork has any pending insertions.
  2600.      *
  2601.      * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
  2602.      */
  2603.     public function hasPendingInsertions()
  2604.     {
  2605.         return ! empty($this->entityInsertions);
  2606.     }
  2607.     /**
  2608.      * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
  2609.      * number of entities in the identity map.
  2610.      *
  2611.      * @return int
  2612.      */
  2613.     public function size()
  2614.     {
  2615.         return array_sum(array_map('count'$this->identityMap));
  2616.     }
  2617.     /**
  2618.      * Gets the EntityPersister for an Entity.
  2619.      *
  2620.      * @param string $entityName The name of the Entity.
  2621.      * @psalm-param class-string $entityName
  2622.      *
  2623.      * @return EntityPersister
  2624.      */
  2625.     public function getEntityPersister($entityName)
  2626.     {
  2627.         if (isset($this->persisters[$entityName])) {
  2628.             return $this->persisters[$entityName];
  2629.         }
  2630.         $class $this->em->getClassMetadata($entityName);
  2631.         switch (true) {
  2632.             case $class->isInheritanceTypeNone():
  2633.                 $persister = new BasicEntityPersister($this->em$class);
  2634.                 break;
  2635.             case $class->isInheritanceTypeSingleTable():
  2636.                 $persister = new SingleTablePersister($this->em$class);
  2637.                 break;
  2638.             case $class->isInheritanceTypeJoined():
  2639.                 $persister = new JoinedSubclassPersister($this->em$class);
  2640.                 break;
  2641.             default:
  2642.                 throw new RuntimeException('No persister found for entity.');
  2643.         }
  2644.         if ($this->hasCache && $class->cache !== null) {
  2645.             $persister $this->em->getConfiguration()
  2646.                 ->getSecondLevelCacheConfiguration()
  2647.                 ->getCacheFactory()
  2648.                 ->buildCachedEntityPersister($this->em$persister$class);
  2649.         }
  2650.         $this->persisters[$entityName] = $persister;
  2651.         return $this->persisters[$entityName];
  2652.     }
  2653.     /**
  2654.      * Gets a collection persister for a collection-valued association.
  2655.      *
  2656.      * @psalm-param array<string, mixed> $association
  2657.      *
  2658.      * @return CollectionPersister
  2659.      */
  2660.     public function getCollectionPersister(array $association)
  2661.     {
  2662.         $role = isset($association['cache'])
  2663.             ? $association['sourceEntity'] . '::' $association['fieldName']
  2664.             : $association['type'];
  2665.         if (isset($this->collectionPersisters[$role])) {
  2666.             return $this->collectionPersisters[$role];
  2667.         }
  2668.         $persister $association['type'] === ClassMetadata::ONE_TO_MANY
  2669.             ? new OneToManyPersister($this->em)
  2670.             : new ManyToManyPersister($this->em);
  2671.         if ($this->hasCache && isset($association['cache'])) {
  2672.             $persister $this->em->getConfiguration()
  2673.                 ->getSecondLevelCacheConfiguration()
  2674.                 ->getCacheFactory()
  2675.                 ->buildCachedCollectionPersister($this->em$persister$association);
  2676.         }
  2677.         $this->collectionPersisters[$role] = $persister;
  2678.         return $this->collectionPersisters[$role];
  2679.     }
  2680.     /**
  2681.      * INTERNAL:
  2682.      * Registers an entity as managed.
  2683.      *
  2684.      * @param object  $entity The entity.
  2685.      * @param mixed[] $id     The identifier values.
  2686.      * @param mixed[] $data   The original entity data.
  2687.      *
  2688.      * @return void
  2689.      */
  2690.     public function registerManaged($entity, array $id, array $data)
  2691.     {
  2692.         $oid spl_object_id($entity);
  2693.         $this->entityIdentifiers[$oid]  = $id;
  2694.         $this->entityStates[$oid]       = self::STATE_MANAGED;
  2695.         $this->originalEntityData[$oid] = $data;
  2696.         $this->addToIdentityMap($entity);
  2697.         if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
  2698.             $entity->addPropertyChangedListener($this);
  2699.         }
  2700.     }
  2701.     /**
  2702.      * INTERNAL:
  2703.      * Clears the property changeset of the entity with the given OID.
  2704.      *
  2705.      * @param int $oid The entity's OID.
  2706.      *
  2707.      * @return void
  2708.      */
  2709.     public function clearEntityChangeSet($oid)
  2710.     {
  2711.         unset($this->entityChangeSets[$oid]);
  2712.     }
  2713.     /* PropertyChangedListener implementation */
  2714.     /**
  2715.      * Notifies this UnitOfWork of a property change in an entity.
  2716.      *
  2717.      * @param object $sender       The entity that owns the property.
  2718.      * @param string $propertyName The name of the property that changed.
  2719.      * @param mixed  $oldValue     The old value of the property.
  2720.      * @param mixed  $newValue     The new value of the property.
  2721.      *
  2722.      * @return void
  2723.      */
  2724.     public function propertyChanged($sender$propertyName$oldValue$newValue)
  2725.     {
  2726.         $oid   spl_object_id($sender);
  2727.         $class $this->em->getClassMetadata(get_class($sender));
  2728.         $isAssocField = isset($class->associationMappings[$propertyName]);
  2729.         if (! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
  2730.             return; // ignore non-persistent fields
  2731.         }
  2732.         // Update changeset and mark entity for synchronization
  2733.         $this->entityChangeSets[$oid][$propertyName] = [$oldValue$newValue];
  2734.         if (! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) {
  2735.             $this->scheduleForDirtyCheck($sender);
  2736.         }
  2737.     }
  2738.     /**
  2739.      * Gets the currently scheduled entity insertions in this UnitOfWork.
  2740.      *
  2741.      * @psalm-return array<int, object>
  2742.      */
  2743.     public function getScheduledEntityInsertions()
  2744.     {
  2745.         return $this->entityInsertions;
  2746.     }
  2747.     /**
  2748.      * Gets the currently scheduled entity updates in this UnitOfWork.
  2749.      *
  2750.      * @psalm-return array<int, object>
  2751.      */
  2752.     public function getScheduledEntityUpdates()
  2753.     {
  2754.         return $this->entityUpdates;
  2755.     }
  2756.     /**
  2757.      * Gets the currently scheduled entity deletions in this UnitOfWork.
  2758.      *
  2759.      * @psalm-return array<int, object>
  2760.      */
  2761.     public function getScheduledEntityDeletions()
  2762.     {
  2763.         return $this->entityDeletions;
  2764.     }
  2765.     /**
  2766.      * Gets the currently scheduled complete collection deletions
  2767.      *
  2768.      * @psalm-return array<int, Collection<array-key, object>>
  2769.      */
  2770.     public function getScheduledCollectionDeletions()
  2771.     {
  2772.         return $this->collectionDeletions;
  2773.     }
  2774.     /**
  2775.      * Gets the currently scheduled collection inserts, updates and deletes.
  2776.      *
  2777.      * @psalm-return array<int, Collection<array-key, object>>
  2778.      */
  2779.     public function getScheduledCollectionUpdates()
  2780.     {
  2781.         return $this->collectionUpdates;
  2782.     }
  2783.     /**
  2784.      * Helper method to initialize a lazy loading proxy or persistent collection.
  2785.      *
  2786.      * @param object $obj
  2787.      *
  2788.      * @return void
  2789.      */
  2790.     public function initializeObject($obj)
  2791.     {
  2792.         if ($obj instanceof Proxy) {
  2793.             $obj->__load();
  2794.             return;
  2795.         }
  2796.         if ($obj instanceof PersistentCollection) {
  2797.             $obj->initialize();
  2798.         }
  2799.     }
  2800.     /**
  2801.      * Helper method to show an object as string.
  2802.      *
  2803.      * @param object $obj
  2804.      */
  2805.     private static function objToStr($obj): string
  2806.     {
  2807.         return method_exists($obj'__toString') ? (string) $obj get_class($obj) . '@' spl_object_id($obj);
  2808.     }
  2809.     /**
  2810.      * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
  2811.      *
  2812.      * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
  2813.      * on this object that might be necessary to perform a correct update.
  2814.      *
  2815.      * @param object $object
  2816.      *
  2817.      * @return void
  2818.      *
  2819.      * @throws ORMInvalidArgumentException
  2820.      */
  2821.     public function markReadOnly($object)
  2822.     {
  2823.         if (! is_object($object) || ! $this->isInIdentityMap($object)) {
  2824.             throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2825.         }
  2826.         $this->readOnlyObjects[spl_object_id($object)] = true;
  2827.     }
  2828.     /**
  2829.      * Is this entity read only?
  2830.      *
  2831.      * @param object $object
  2832.      *
  2833.      * @return bool
  2834.      *
  2835.      * @throws ORMInvalidArgumentException
  2836.      */
  2837.     public function isReadOnly($object)
  2838.     {
  2839.         if (! is_object($object)) {
  2840.             throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2841.         }
  2842.         return isset($this->readOnlyObjects[spl_object_id($object)]);
  2843.     }
  2844.     /**
  2845.      * Perform whatever processing is encapsulated here after completion of the transaction.
  2846.      */
  2847.     private function afterTransactionComplete(): void
  2848.     {
  2849.         $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
  2850.             $persister->afterTransactionComplete();
  2851.         });
  2852.     }
  2853.     /**
  2854.      * Perform whatever processing is encapsulated here after completion of the rolled-back.
  2855.      */
  2856.     private function afterTransactionRolledBack(): void
  2857.     {
  2858.         $this->performCallbackOnCachedPersister(static function (CachedPersister $persister) {
  2859.             $persister->afterTransactionRolledBack();
  2860.         });
  2861.     }
  2862.     /**
  2863.      * Performs an action after the transaction.
  2864.      */
  2865.     private function performCallbackOnCachedPersister(callable $callback): void
  2866.     {
  2867.         if (! $this->hasCache) {
  2868.             return;
  2869.         }
  2870.         foreach (array_merge($this->persisters$this->collectionPersisters) as $persister) {
  2871.             if ($persister instanceof CachedPersister) {
  2872.                 $callback($persister);
  2873.             }
  2874.         }
  2875.     }
  2876.     private function dispatchOnFlushEvent(): void
  2877.     {
  2878.         if ($this->evm->hasListeners(Events::onFlush)) {
  2879.             $this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
  2880.         }
  2881.     }
  2882.     private function dispatchPostFlushEvent(): void
  2883.     {
  2884.         if ($this->evm->hasListeners(Events::postFlush)) {
  2885.             $this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
  2886.         }
  2887.     }
  2888.     /**
  2889.      * Verifies if two given entities actually are the same based on identifier comparison
  2890.      *
  2891.      * @param object $entity1
  2892.      * @param object $entity2
  2893.      */
  2894.     private function isIdentifierEquals($entity1$entity2): bool
  2895.     {
  2896.         if ($entity1 === $entity2) {
  2897.             return true;
  2898.         }
  2899.         $class $this->em->getClassMetadata(get_class($entity1));
  2900.         if ($class !== $this->em->getClassMetadata(get_class($entity2))) {
  2901.             return false;
  2902.         }
  2903.         $oid1 spl_object_id($entity1);
  2904.         $oid2 spl_object_id($entity2);
  2905.         $id1 $this->entityIdentifiers[$oid1] ?? $this->identifierFlattener->flattenIdentifier($class$class->getIdentifierValues($entity1));
  2906.         $id2 $this->entityIdentifiers[$oid2] ?? $this->identifierFlattener->flattenIdentifier($class$class->getIdentifierValues($entity2));
  2907.         return $id1 === $id2 || implode(' '$id1) === implode(' '$id2);
  2908.     }
  2909.     /**
  2910.      * @throws ORMInvalidArgumentException
  2911.      */
  2912.     private function assertThatThereAreNoUnintentionallyNonPersistedAssociations(): void
  2913.     {
  2914.         $entitiesNeedingCascadePersist array_diff_key($this->nonCascadedNewDetectedEntities$this->entityInsertions);
  2915.         $this->nonCascadedNewDetectedEntities = [];
  2916.         if ($entitiesNeedingCascadePersist) {
  2917.             throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships(
  2918.                 array_values($entitiesNeedingCascadePersist)
  2919.             );
  2920.         }
  2921.     }
  2922.     /**
  2923.      * @param object $entity
  2924.      * @param object $managedCopy
  2925.      *
  2926.      * @throws ORMException
  2927.      * @throws OptimisticLockException
  2928.      * @throws TransactionRequiredException
  2929.      */
  2930.     private function mergeEntityStateIntoManagedCopy($entity$managedCopy): void
  2931.     {
  2932.         if (! $this->isLoaded($entity)) {
  2933.             return;
  2934.         }
  2935.         if (! $this->isLoaded($managedCopy)) {
  2936.             $managedCopy->__load();
  2937.         }
  2938.         $class $this->em->getClassMetadata(get_class($entity));
  2939.         foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) {
  2940.             $name $prop->name;
  2941.             $prop->setAccessible(true);
  2942.             if (! isset($class->associationMappings[$name])) {
  2943.                 if (! $class->isIdentifier($name)) {
  2944.                     $prop->setValue($managedCopy$prop->getValue($entity));
  2945.                 }
  2946.             } else {
  2947.                 $assoc2 $class->associationMappings[$name];
  2948.                 if ($assoc2['type'] & ClassMetadata::TO_ONE) {
  2949.                     $other $prop->getValue($entity);
  2950.                     if ($other === null) {
  2951.                         $prop->setValue($managedCopynull);
  2952.                     } else {
  2953.                         if ($other instanceof Proxy && ! $other->__isInitialized()) {
  2954.                             // do not merge fields marked lazy that have not been fetched.
  2955.                             continue;
  2956.                         }
  2957.                         if (! $assoc2['isCascadeMerge']) {
  2958.                             if ($this->getEntityState($other) === self::STATE_DETACHED) {
  2959.                                 $targetClass $this->em->getClassMetadata($assoc2['targetEntity']);
  2960.                                 $relatedId   $targetClass->getIdentifierValues($other);
  2961.                                 if ($targetClass->subClasses) {
  2962.                                     $other $this->em->find($targetClass->name$relatedId);
  2963.                                 } else {
  2964.                                     $other $this->em->getProxyFactory()->getProxy(
  2965.                                         $assoc2['targetEntity'],
  2966.                                         $relatedId
  2967.                                     );
  2968.                                     $this->registerManaged($other$relatedId, []);
  2969.                                 }
  2970.                             }
  2971.                             $prop->setValue($managedCopy$other);
  2972.                         }
  2973.                     }
  2974.                 } else {
  2975.                     $mergeCol $prop->getValue($entity);
  2976.                     if ($mergeCol instanceof PersistentCollection && ! $mergeCol->isInitialized()) {
  2977.                         // do not merge fields marked lazy that have not been fetched.
  2978.                         // keep the lazy persistent collection of the managed copy.
  2979.                         continue;
  2980.                     }
  2981.                     $managedCol $prop->getValue($managedCopy);
  2982.                     if (! $managedCol) {
  2983.                         $managedCol = new PersistentCollection(
  2984.                             $this->em,
  2985.                             $this->em->getClassMetadata($assoc2['targetEntity']),
  2986.                             new ArrayCollection()
  2987.                         );
  2988.                         $managedCol->setOwner($managedCopy$assoc2);
  2989.                         $prop->setValue($managedCopy$managedCol);
  2990.                     }
  2991.                     if ($assoc2['isCascadeMerge']) {
  2992.                         $managedCol->initialize();
  2993.                         // clear and set dirty a managed collection if its not also the same collection to merge from.
  2994.                         if (! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
  2995.                             $managedCol->unwrap()->clear();
  2996.                             $managedCol->setDirty(true);
  2997.                             if (
  2998.                                 $assoc2['isOwningSide']
  2999.                                 && $assoc2['type'] === ClassMetadata::MANY_TO_MANY
  3000.                                 && $class->isChangeTrackingNotify()
  3001.                             ) {
  3002.                                 $this->scheduleForDirtyCheck($managedCopy);
  3003.                             }
  3004.                         }
  3005.                     }
  3006.                 }
  3007.             }
  3008.             if ($class->isChangeTrackingNotify()) {
  3009.                 // Just treat all properties as changed, there is no other choice.
  3010.                 $this->propertyChanged($managedCopy$namenull$prop->getValue($managedCopy));
  3011.             }
  3012.         }
  3013.     }
  3014.     /**
  3015.      * This method called by hydrators, and indicates that hydrator totally completed current hydration cycle.
  3016.      * Unit of work able to fire deferred events, related to loading events here.
  3017.      *
  3018.      * @internal should be called internally from object hydrators
  3019.      *
  3020.      * @return void
  3021.      */
  3022.     public function hydrationComplete()
  3023.     {
  3024.         $this->hydrationCompleteHandler->hydrationComplete();
  3025.     }
  3026.     private function clearIdentityMapForEntityName(string $entityName): void
  3027.     {
  3028.         if (! isset($this->identityMap[$entityName])) {
  3029.             return;
  3030.         }
  3031.         $visited = [];
  3032.         foreach ($this->identityMap[$entityName] as $entity) {
  3033.             $this->doDetach($entity$visitedfalse);
  3034.         }
  3035.     }
  3036.     private function clearEntityInsertionsForEntityName(string $entityName): void
  3037.     {
  3038.         foreach ($this->entityInsertions as $hash => $entity) {
  3039.             // note: performance optimization - `instanceof` is much faster than a function call
  3040.             if ($entity instanceof $entityName && get_class($entity) === $entityName) {
  3041.                 unset($this->entityInsertions[$hash]);
  3042.             }
  3043.         }
  3044.     }
  3045.     /**
  3046.      * @param mixed $identifierValue
  3047.      *
  3048.      * @return mixed the identifier after type conversion
  3049.      *
  3050.      * @throws MappingException if the entity has more than a single identifier.
  3051.      */
  3052.     private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class$identifierValue)
  3053.     {
  3054.         return $this->em->getConnection()->convertToPHPValue(
  3055.             $identifierValue,
  3056.             $class->getTypeOfField($class->getSingleIdentifierFieldName())
  3057.         );
  3058.     }
  3059. }