vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php line 2411

  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ODM\MongoDB;
  4. use Doctrine\Common\Collections\ArrayCollection;
  5. use Doctrine\Common\Collections\Collection;
  6. use Doctrine\Common\EventManager;
  7. use Doctrine\ODM\MongoDB\Hydrator\HydratorFactory;
  8. use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
  9. use Doctrine\ODM\MongoDB\Mapping\MappingException;
  10. use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionException;
  11. use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionInterface;
  12. use Doctrine\ODM\MongoDB\Persisters\CollectionPersister;
  13. use Doctrine\ODM\MongoDB\Persisters\PersistenceBuilder;
  14. use Doctrine\ODM\MongoDB\Query\Query;
  15. use Doctrine\ODM\MongoDB\Types\DateType;
  16. use Doctrine\ODM\MongoDB\Types\Type;
  17. use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
  18. use Doctrine\ODM\MongoDB\Utility\LifecycleEventManager;
  19. use Doctrine\Persistence\Mapping\ReflectionService;
  20. use Doctrine\Persistence\Mapping\RuntimeReflectionService;
  21. use Doctrine\Persistence\NotifyPropertyChanged;
  22. use Doctrine\Persistence\PropertyChangedListener;
  23. use InvalidArgumentException;
  24. use MongoDB\BSON\UTCDateTime;
  25. use MongoDB\Driver\WriteConcern;
  26. use ProxyManager\Proxy\GhostObjectInterface;
  27. use ReflectionProperty;
  28. use UnexpectedValueException;
  29. use function array_filter;
  30. use function assert;
  31. use function count;
  32. use function get_class;
  33. use function in_array;
  34. use function is_array;
  35. use function is_object;
  36. use function method_exists;
  37. use function preg_match;
  38. use function serialize;
  39. use function spl_object_hash;
  40. use function sprintf;
  41. /**
  42.  * The UnitOfWork is responsible for tracking changes to objects during an
  43.  * "object-level" transaction and for writing out changes to the database
  44.  * in the correct order.
  45.  *
  46.  * @psalm-import-type FieldMapping from ClassMetadata
  47.  * @psalm-import-type AssociationFieldMapping from ClassMetadata
  48.  * @psalm-type ChangeSet = array{
  49.  *      0: mixed,
  50.  *      1: mixed
  51.  * }
  52.  * @psalm-type Hints = array<int, mixed>
  53.  * @psalm-type CommitOptions array{
  54.  *      fsync?: bool,
  55.  *      safe?: int,
  56.  *      w?: int,
  57.  *      writeConcern?: WriteConcern
  58.  * }
  59.  */
  60. final class UnitOfWork implements PropertyChangedListener
  61. {
  62.     /**
  63.      * A document is in MANAGED state when its persistence is managed by a DocumentManager.
  64.      */
  65.     public const STATE_MANAGED 1;
  66.     /**
  67.      * A document is new if it has just been instantiated (i.e. using the "new" operator)
  68.      * and is not (yet) managed by a DocumentManager.
  69.      */
  70.     public const STATE_NEW 2;
  71.     /**
  72.      * A detached document is an instance with a persistent identity that is not
  73.      * (or no longer) associated with a DocumentManager (and a UnitOfWork).
  74.      */
  75.     public const STATE_DETACHED 3;
  76.     /**
  77.      * A removed document instance is an instance with a persistent identity,
  78.      * associated with a DocumentManager, whose persistent state has been
  79.      * deleted (or is scheduled for deletion).
  80.      */
  81.     public const STATE_REMOVED 4;
  82.     /**
  83.      * The identity map holds references to all managed documents.
  84.      *
  85.      * Documents are grouped by their class name, and then indexed by the
  86.      * serialized string of their database identifier field or, if the class
  87.      * has no identifier, the SPL object hash. Serializing the identifier allows
  88.      * differentiation of values that may be equal (via type juggling) but not
  89.      * identical.
  90.      *
  91.      * Since all classes in a hierarchy must share the same identifier set,
  92.      * we always take the root class name of the hierarchy.
  93.      *
  94.      * @psalm-var array<class-string, array<string, object>>
  95.      */
  96.     private array $identityMap = [];
  97.     /**
  98.      * Map of all identifiers of managed documents.
  99.      * Keys are object ids (spl_object_hash).
  100.      *
  101.      * @var array<string, mixed>
  102.      */
  103.     private array $documentIdentifiers = [];
  104.     /**
  105.      * Map of the original document data of managed documents.
  106.      * Keys are object ids (spl_object_hash). This is used for calculating changesets
  107.      * at commit time.
  108.      *
  109.      * @internal Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
  110.      *           A value will only really be copied if the value in the document is modified
  111.      *           by the user.
  112.      *
  113.      * @var array<string, array<string, mixed>>
  114.      */
  115.     private array $originalDocumentData = [];
  116.     /**
  117.      * Map of document changes. Keys are object ids (spl_object_hash).
  118.      * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
  119.      *
  120.      * @psalm-var array<string, array<string, ChangeSet>>
  121.      */
  122.     private array $documentChangeSets = [];
  123.     /**
  124.      * The (cached) states of any known documents.
  125.      * Keys are object ids (spl_object_hash).
  126.      *
  127.      * @psalm-var array<string, self::STATE_*>
  128.      */
  129.     private array $documentStates = [];
  130.     /**
  131.      * Map of documents that are scheduled for dirty checking at commit time.
  132.      *
  133.      * Documents are grouped by their class name, and then indexed by their SPL
  134.      * object hash. This is only used for documents with a change tracking
  135.      * policy of DEFERRED_EXPLICIT.
  136.      *
  137.      * @psalm-var array<class-string, array<string, object>>
  138.      */
  139.     private array $scheduledForSynchronization = [];
  140.     /**
  141.      * A list of all pending document insertions.
  142.      *
  143.      * @var array<string, object>
  144.      */
  145.     private array $documentInsertions = [];
  146.     /**
  147.      * A list of all pending document updates.
  148.      *
  149.      * @var array<string, object>
  150.      */
  151.     private array $documentUpdates = [];
  152.     /**
  153.      * A list of all pending document upserts.
  154.      *
  155.      * @var array<string, object>
  156.      */
  157.     private array $documentUpserts = [];
  158.     /**
  159.      * A list of all pending document deletions.
  160.      *
  161.      * @var array<string, object>
  162.      */
  163.     private array $documentDeletions = [];
  164.     /**
  165.      * All pending collection deletions.
  166.      *
  167.      * @psalm-var array<string, PersistentCollectionInterface<array-key, object>>
  168.      */
  169.     private array $collectionDeletions = [];
  170.     /**
  171.      * All pending collection updates.
  172.      *
  173.      * @psalm-var array<string, PersistentCollectionInterface<array-key, object>>
  174.      */
  175.     private array $collectionUpdates = [];
  176.     /**
  177.      * A list of documents related to collections scheduled for update or deletion
  178.      *
  179.      * @psalm-var array<string, array<string, PersistentCollectionInterface<array-key, object>>>
  180.      */
  181.     private array $hasScheduledCollections = [];
  182.     /**
  183.      * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
  184.      * At the end of the UnitOfWork all these collections will make new snapshots
  185.      * of their data.
  186.      *
  187.      * @psalm-var array<string, array<PersistentCollectionInterface<array-key, object>>>
  188.      */
  189.     private array $visitedCollections = [];
  190.     /**
  191.      * The DocumentManager that "owns" this UnitOfWork instance.
  192.      */
  193.     private DocumentManager $dm;
  194.     /**
  195.      * The EventManager used for dispatching events.
  196.      */
  197.     private EventManager $evm;
  198.     /**
  199.      * Additional documents that are scheduled for removal.
  200.      *
  201.      * @var array<string, object>
  202.      */
  203.     private array $orphanRemovals = [];
  204.     /**
  205.      * The HydratorFactory used for hydrating array Mongo documents to Doctrine object documents.
  206.      */
  207.     private HydratorFactory $hydratorFactory;
  208.     /**
  209.      * The document persister instances used to persist document instances.
  210.      *
  211.      * @psalm-var array<class-string, Persisters\DocumentPersister>
  212.      */
  213.     private array $persisters = [];
  214.     /**
  215.      * The collection persister instance used to persist changes to collections.
  216.      */
  217.     private ?CollectionPersister $collectionPersister null;
  218.     /**
  219.      * The persistence builder instance used in DocumentPersisters.
  220.      */
  221.     private ?PersistenceBuilder $persistenceBuilder null;
  222.     /**
  223.      * Array of parent associations between embedded documents.
  224.      *
  225.      * @psalm-var array<string, array{0: AssociationFieldMapping, 1: object|null, 2: string}>
  226.      */
  227.     private array $parentAssociations = [];
  228.     private LifecycleEventManager $lifecycleEventManager;
  229.     private ReflectionService $reflectionService;
  230.     /**
  231.      * Array of embedded documents known to UnitOfWork. We need to hold them to prevent spl_object_hash
  232.      * collisions in case already managed object is lost due to GC (so now it won't). Embedded documents
  233.      * found during doDetach are removed from the registry, to empty it altogether clear() can be utilized.
  234.      *
  235.      * @var array<string, object>
  236.      */
  237.     private array $embeddedDocumentsRegistry = [];
  238.     private int $commitsInProgress 0;
  239.     /**
  240.      * Initializes a new UnitOfWork instance, bound to the given DocumentManager.
  241.      */
  242.     public function __construct(DocumentManager $dmEventManager $evmHydratorFactory $hydratorFactory)
  243.     {
  244.         $this->dm                    $dm;
  245.         $this->evm                   $evm;
  246.         $this->hydratorFactory       $hydratorFactory;
  247.         $this->lifecycleEventManager = new LifecycleEventManager($dm$this$evm);
  248.         $this->reflectionService     = new RuntimeReflectionService();
  249.     }
  250.     /**
  251.      * Factory for returning new PersistenceBuilder instances used for preparing data into
  252.      * queries for insert persistence.
  253.      *
  254.      * @internal
  255.      */
  256.     public function getPersistenceBuilder(): PersistenceBuilder
  257.     {
  258.         if (! $this->persistenceBuilder) {
  259.             $this->persistenceBuilder = new PersistenceBuilder($this->dm$this);
  260.         }
  261.         return $this->persistenceBuilder;
  262.     }
  263.     /**
  264.      * Sets the parent association for a given embedded document.
  265.      *
  266.      * @internal
  267.      *
  268.      * @psalm-param FieldMapping $mapping
  269.      */
  270.     public function setParentAssociation(object $document, array $mapping, ?object $parentstring $propertyPath): void
  271.     {
  272.         $oid                                   spl_object_hash($document);
  273.         $this->embeddedDocumentsRegistry[$oid] = $document;
  274.         $this->parentAssociations[$oid]        = [$mapping$parent$propertyPath];
  275.     }
  276.     /**
  277.      * Gets the parent association for a given embedded document.
  278.      *
  279.      *     <code>
  280.      *     list($mapping, $parent, $propertyPath) = $this->getParentAssociation($embeddedDocument);
  281.      *     </code>
  282.      *
  283.      * @psalm-return array{0: AssociationFieldMapping, 1: object|null, 2: string}|null
  284.      */
  285.     public function getParentAssociation(object $document): ?array
  286.     {
  287.         $oid spl_object_hash($document);
  288.         return $this->parentAssociations[$oid] ?? null;
  289.     }
  290.     /**
  291.      * Get the document persister instance for the given document name
  292.      *
  293.      * @psalm-param class-string<T> $documentName
  294.      *
  295.      * @psalm-return Persisters\DocumentPersister<T>
  296.      *
  297.      * @template T of object
  298.      */
  299.     public function getDocumentPersister(string $documentName): Persisters\DocumentPersister
  300.     {
  301.         if (! isset($this->persisters[$documentName])) {
  302.             $class                           $this->dm->getClassMetadata($documentName);
  303.             $pb                              $this->getPersistenceBuilder();
  304.             $this->persisters[$documentName] = new Persisters\DocumentPersister($pb$this->dm$this$this->hydratorFactory$class);
  305.         }
  306.         /** @psalm-var Persisters\DocumentPersister<T> */
  307.         return $this->persisters[$documentName];
  308.     }
  309.     /**
  310.      * Get the collection persister instance.
  311.      */
  312.     public function getCollectionPersister(): CollectionPersister
  313.     {
  314.         if (! isset($this->collectionPersister)) {
  315.             $pb                        $this->getPersistenceBuilder();
  316.             $this->collectionPersister = new Persisters\CollectionPersister($this->dm$pb$this);
  317.         }
  318.         return $this->collectionPersister;
  319.     }
  320.     /**
  321.      * Set the document persister instance to use for the given document name
  322.      *
  323.      * @internal
  324.      *
  325.      * @psalm-param class-string<T> $documentName
  326.      * @psalm-param Persisters\DocumentPersister<T> $persister
  327.      *
  328.      * @template T of object
  329.      */
  330.     public function setDocumentPersister(string $documentNamePersisters\DocumentPersister $persister): void
  331.     {
  332.         $this->persisters[$documentName] = $persister;
  333.     }
  334.     /**
  335.      * Commits the UnitOfWork, executing all operations that have been postponed
  336.      * up to this point. The state of all managed documents will be synchronized with
  337.      * the database.
  338.      *
  339.      * The operations are executed in the following order:
  340.      *
  341.      * 1) All document insertions
  342.      * 2) All document updates
  343.      * 3) All document deletions
  344.      *
  345.      * @param array $options Array of options to be used with batchInsert(), update() and remove()
  346.      * @psalm-param CommitOptions $options
  347.      */
  348.     public function commit(array $options = []): void
  349.     {
  350.         // Raise preFlush
  351.         $this->evm->dispatchEvent(Events::preFlush, new Event\PreFlushEventArgs($this->dm));
  352.         // Compute changes done since last commit.
  353.         $this->computeChangeSets();
  354.         if (
  355.             ! ($this->documentInsertions ||
  356.             $this->documentUpserts ||
  357.             $this->documentDeletions ||
  358.             $this->documentUpdates ||
  359.             $this->collectionUpdates ||
  360.             $this->collectionDeletions ||
  361.             $this->orphanRemovals)
  362.         ) {
  363.             return; // Nothing to do.
  364.         }
  365.         $this->commitsInProgress++;
  366.         if ($this->commitsInProgress 1) {
  367.             throw MongoDBException::commitInProgress();
  368.         }
  369.         try {
  370.             if ($this->orphanRemovals) {
  371.                 foreach ($this->orphanRemovals as $removal) {
  372.                     $this->remove($removal);
  373.                 }
  374.             }
  375.             // Raise onFlush
  376.             $this->evm->dispatchEvent(Events::onFlush, new Event\OnFlushEventArgs($this->dm));
  377.             foreach ($this->getClassesForCommitAction($this->documentUpserts) as $classAndDocuments) {
  378.                 [$class$documents] = $classAndDocuments;
  379.                 $this->executeUpserts($class$documents$options);
  380.             }
  381.             foreach ($this->getClassesForCommitAction($this->documentInsertions) as $classAndDocuments) {
  382.                 [$class$documents] = $classAndDocuments;
  383.                 $this->executeInserts($class$documents$options);
  384.             }
  385.             foreach ($this->getClassesForCommitAction($this->documentUpdates) as $classAndDocuments) {
  386.                 [$class$documents] = $classAndDocuments;
  387.                 $this->executeUpdates($class$documents$options);
  388.             }
  389.             foreach ($this->getClassesForCommitAction($this->documentDeletionstrue) as $classAndDocuments) {
  390.                 [$class$documents] = $classAndDocuments;
  391.                 $this->executeDeletions($class$documents$options);
  392.             }
  393.             // Raise postFlush
  394.             $this->evm->dispatchEvent(Events::postFlush, new Event\PostFlushEventArgs($this->dm));
  395.             // Clear up
  396.             $this->documentInsertions          =
  397.             $this->documentUpserts             =
  398.             $this->documentUpdates             =
  399.             $this->documentDeletions           =
  400.             $this->documentChangeSets          =
  401.             $this->collectionUpdates           =
  402.             $this->collectionDeletions         =
  403.             $this->visitedCollections          =
  404.             $this->scheduledForSynchronization =
  405.             $this->orphanRemovals              =
  406.             $this->hasScheduledCollections     = [];
  407.         } finally {
  408.             $this->commitsInProgress--;
  409.         }
  410.     }
  411.     /**
  412.      * Groups a list of scheduled documents by their class.
  413.      *
  414.      * @param array<string, object> $documents
  415.      *
  416.      * @psalm-return array<class-string, array{0: ClassMetadata<object>, 1: array<string, object>}>
  417.      */
  418.     private function getClassesForCommitAction(array $documentsbool $includeEmbedded false): array
  419.     {
  420.         if (empty($documents)) {
  421.             return [];
  422.         }
  423.         $divided = [];
  424.         $embeds  = [];
  425.         foreach ($documents as $oid => $d) {
  426.             $className get_class($d);
  427.             if (isset($embeds[$className])) {
  428.                 continue;
  429.             }
  430.             if (isset($divided[$className])) {
  431.                 $divided[$className][1][$oid] = $d;
  432.                 continue;
  433.             }
  434.             $class $this->dm->getClassMetadata($className);
  435.             if ($class->isEmbeddedDocument && ! $includeEmbedded) {
  436.                 $embeds[$className] = true;
  437.                 continue;
  438.             }
  439.             if ($class->isView()) {
  440.                 continue;
  441.             }
  442.             if (empty($divided[$class->name])) {
  443.                 $divided[$class->name] = [$class, [$oid => $d]];
  444.             } else {
  445.                 $divided[$class->name][1][$oid] = $d;
  446.             }
  447.         }
  448.         return $divided;
  449.     }
  450.     /**
  451.      * Compute changesets of all documents scheduled for insertion.
  452.      *
  453.      * Embedded documents will not be processed.
  454.      */
  455.     private function computeScheduleInsertsChangeSets(): void
  456.     {
  457.         foreach ($this->documentInsertions as $document) {
  458.             $class $this->dm->getClassMetadata(get_class($document));
  459.             if ($class->isEmbeddedDocument || $class->isView()) {
  460.                 continue;
  461.             }
  462.             $this->computeChangeSet($class$document);
  463.         }
  464.     }
  465.     /**
  466.      * Compute changesets of all documents scheduled for upsert.
  467.      *
  468.      * Embedded documents will not be processed.
  469.      */
  470.     private function computeScheduleUpsertsChangeSets(): void
  471.     {
  472.         foreach ($this->documentUpserts as $document) {
  473.             $class $this->dm->getClassMetadata(get_class($document));
  474.             if ($class->isEmbeddedDocument || $class->isView()) {
  475.                 continue;
  476.             }
  477.             $this->computeChangeSet($class$document);
  478.         }
  479.     }
  480.     /**
  481.      * Gets the changeset for a document.
  482.      *
  483.      * @return array array('property' => array(0 => mixed, 1 => mixed))
  484.      * @psalm-return array<string, ChangeSet>
  485.      */
  486.     public function getDocumentChangeSet(object $document): array
  487.     {
  488.         $oid spl_object_hash($document);
  489.         return $this->documentChangeSets[$oid] ?? [];
  490.     }
  491.     /**
  492.      * Sets the changeset for a document.
  493.      *
  494.      * @internal
  495.      *
  496.      * @psalm-param array<string, ChangeSet> $changeset
  497.      */
  498.     public function setDocumentChangeSet(object $document, array $changeset): void
  499.     {
  500.         $this->documentChangeSets[spl_object_hash($document)] = $changeset;
  501.     }
  502.     /**
  503.      * Get a documents actual data, flattening all the objects to arrays.
  504.      *
  505.      * @internal
  506.      *
  507.      * @return array<string, mixed>
  508.      */
  509.     public function getDocumentActualData(object $document): array
  510.     {
  511.         $class      $this->dm->getClassMetadata(get_class($document));
  512.         $actualData = [];
  513.         foreach ($class->reflFields as $name => $refProp) {
  514.             $mapping $class->fieldMappings[$name];
  515.             // skip not saved fields
  516.             if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) {
  517.                 continue;
  518.             }
  519.             $value $refProp->getValue($document);
  520.             if (
  521.                 (isset($mapping['association']) && $mapping['type'] === ClassMetadata::MANY)
  522.                 && $value !== null && ! ($value instanceof PersistentCollectionInterface)
  523.             ) {
  524.                 // If $actualData[$name] is not a Collection then use an ArrayCollection.
  525.                 if (! $value instanceof Collection) {
  526.                     $value = new ArrayCollection($value);
  527.                 }
  528.                 // Inject PersistentCollection
  529.                 $coll $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm$mapping$value);
  530.                 $coll->setOwner($document$mapping);
  531.                 $coll->setDirty(! $value->isEmpty());
  532.                 $class->reflFields[$name]->setValue($document$coll);
  533.                 $actualData[$name] = $coll;
  534.             } else {
  535.                 $actualData[$name] = $value;
  536.             }
  537.         }
  538.         return $actualData;
  539.     }
  540.     /**
  541.      * Computes the changes that happened to a single document.
  542.      *
  543.      * Modifies/populates the following properties:
  544.      *
  545.      * {@link originalDocumentData}
  546.      * If the document is NEW or MANAGED but not yet fully persisted (only has an id)
  547.      * then it was not fetched from the database and therefore we have no original
  548.      * document data yet. All of the current document data is stored as the original document data.
  549.      *
  550.      * {@link documentChangeSets}
  551.      * The changes detected on all properties of the document are stored there.
  552.      * A change is a tuple array where the first entry is the old value and the second
  553.      * entry is the new value of the property. Changesets are used by persisters
  554.      * to INSERT/UPDATE the persistent document state.
  555.      *
  556.      * {@link documentUpdates}
  557.      * If the document is already fully MANAGED (has been fetched from the database before)
  558.      * and any changes to its properties are detected, then a reference to the document is stored
  559.      * there to mark it for an update.
  560.      *
  561.      * @psalm-param ClassMetadata<T> $class
  562.      * @psalm-param T $document
  563.      *
  564.      * @template T of object
  565.      */
  566.     public function computeChangeSet(ClassMetadata $classobject $document): void
  567.     {
  568.         if (! $class->isInheritanceTypeNone()) {
  569.             $class $this->dm->getClassMetadata(get_class($document));
  570.         }
  571.         // Fire PreFlush lifecycle callbacks
  572.         if (! empty($class->lifecycleCallbacks[Events::preFlush])) {
  573.             $class->invokeLifecycleCallbacks(Events::preFlush$document, [new Event\PreFlushEventArgs($this->dm)]);
  574.         }
  575.         $this->computeOrRecomputeChangeSet($class$document);
  576.     }
  577.     /**
  578.      * Used to do the common work of computeChangeSet and recomputeSingleDocumentChangeSet
  579.      *
  580.      * @psalm-param ClassMetadata<T> $class
  581.      * @psalm-param T $document
  582.      *
  583.      * @template T of object
  584.      */
  585.     private function computeOrRecomputeChangeSet(ClassMetadata $classobject $documentbool $recompute false): void
  586.     {
  587.         if ($class->isView()) {
  588.             return;
  589.         }
  590.         $oid           spl_object_hash($document);
  591.         $actualData    $this->getDocumentActualData($document);
  592.         $isNewDocument = ! isset($this->originalDocumentData[$oid]);
  593.         if ($isNewDocument) {
  594.             // Document is either NEW or MANAGED but not yet fully persisted (only has an id).
  595.             // These result in an INSERT.
  596.             $this->originalDocumentData[$oid] = $actualData;
  597.             $changeSet                        = [];
  598.             foreach ($actualData as $propName => $actualValue) {
  599.                 /* At this PersistentCollection shouldn't be here, probably it
  600.                  * was cloned and its ownership must be fixed
  601.                  */
  602.                 if ($actualValue instanceof PersistentCollectionInterface && $actualValue->getOwner() !== $document) {
  603.                     $actualData[$propName] = $this->fixPersistentCollectionOwnership($actualValue$document$class$propName);
  604.                     $actualValue           $actualData[$propName];
  605.                 }
  606.                 // ignore inverse side of reference relationship
  607.                 if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['isInverseSide']) {
  608.                     continue;
  609.                 }
  610.                 $changeSet[$propName] = [null$actualValue];
  611.             }
  612.             $this->documentChangeSets[$oid] = $changeSet;
  613.         } else {
  614.             if ($class->isReadOnly) {
  615.                 return;
  616.             }
  617.             // Document is "fully" MANAGED: it was already fully persisted before
  618.             // and we have a copy of the original data
  619.             $originalData           $this->originalDocumentData[$oid];
  620.             $isChangeTrackingNotify $class->isChangeTrackingNotify();
  621.             if ($isChangeTrackingNotify && ! $recompute && isset($this->documentChangeSets[$oid])) {
  622.                 $changeSet $this->documentChangeSets[$oid];
  623.             } else {
  624.                 $changeSet = [];
  625.             }
  626.             $gridFSMetadataProperty null;
  627.             if ($class->isFile) {
  628.                 try {
  629.                     $gridFSMetadata         $class->getFieldMappingByDbFieldName('metadata');
  630.                     $gridFSMetadataProperty $gridFSMetadata['fieldName'];
  631.                 } catch (MappingException $e) {
  632.                 }
  633.             }
  634.             foreach ($actualData as $propName => $actualValue) {
  635.                 // skip not saved fields
  636.                 if (
  637.                     (isset($class->fieldMappings[$propName]['notSaved']) && $class->fieldMappings[$propName]['notSaved'] === true) ||
  638.                     ($class->isFile && $propName !== $gridFSMetadataProperty)
  639.                 ) {
  640.                     continue;
  641.                 }
  642.                 $orgValue $originalData[$propName] ?? null;
  643.                 // skip if value has not changed
  644.                 if ($orgValue === $actualValue) {
  645.                     if (! $actualValue instanceof PersistentCollectionInterface) {
  646.                         continue;
  647.                     }
  648.                     if (! $actualValue->isDirty() && ! $this->isCollectionScheduledForDeletion($actualValue)) {
  649.                         // consider dirty collections as changed as well
  650.                         continue;
  651.                     }
  652.                 }
  653.                 // if relationship is a embed-one, schedule orphan removal to trigger cascade remove operations
  654.                 if (isset($class->fieldMappings[$propName]['embedded']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::ONE) {
  655.                     if ($orgValue !== null) {
  656.                         $this->scheduleOrphanRemoval($orgValue);
  657.                     }
  658.                     $changeSet[$propName] = [$orgValue$actualValue];
  659.                     continue;
  660.                 }
  661.                 // if owning side of reference-one relationship
  662.                 if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::ONE && $class->fieldMappings[$propName]['isOwningSide']) {
  663.                     if ($orgValue !== null && $class->fieldMappings[$propName]['orphanRemoval']) {
  664.                         $this->scheduleOrphanRemoval($orgValue);
  665.                     }
  666.                     $changeSet[$propName] = [$orgValue$actualValue];
  667.                     continue;
  668.                 }
  669.                 if ($isChangeTrackingNotify) {
  670.                     continue;
  671.                 }
  672.                 // ignore inverse side of reference relationship
  673.                 if (isset($class->fieldMappings[$propName]['reference']) && $class->fieldMappings[$propName]['isInverseSide']) {
  674.                     continue;
  675.                 }
  676.                 // Persistent collection was exchanged with the "originally"
  677.                 // created one. This can only mean it was cloned and replaced
  678.                 // on another document.
  679.                 if ($actualValue instanceof PersistentCollectionInterface && $actualValue->getOwner() !== $document) {
  680.                     $actualValue $this->fixPersistentCollectionOwnership($actualValue$document$class$propName);
  681.                 }
  682.                 // if embed-many or reference-many relationship
  683.                 if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === ClassMetadata::MANY) {
  684.                     $changeSet[$propName] = [$orgValue$actualValue];
  685.                     /* If original collection was exchanged with a non-empty value
  686.                      * and $set will be issued, there is no need to $unset it first
  687.                      */
  688.                     if ($actualValue && $actualValue->isDirty() && CollectionHelper::usesSet($class->fieldMappings[$propName]['strategy'])) {
  689.                         continue;
  690.                     }
  691.                     if ($orgValue !== $actualValue && $orgValue instanceof PersistentCollectionInterface) {
  692.                         $this->scheduleCollectionDeletion($orgValue);
  693.                     }
  694.                     continue;
  695.                 }
  696.                 // skip equivalent date values
  697.                 if (isset($class->fieldMappings[$propName]['type']) && $class->fieldMappings[$propName]['type'] === 'date') {
  698.                     $dateType Type::getType('date');
  699.                     assert($dateType instanceof DateType);
  700.                     $dbOrgValue    $dateType->convertToDatabaseValue($orgValue);
  701.                     $dbActualValue $dateType->convertToDatabaseValue($actualValue);
  702.                     $orgTimestamp    $dbOrgValue instanceof UTCDateTime $dbOrgValue->toDateTime()->getTimestamp() : null;
  703.                     $actualTimestamp $dbActualValue instanceof UTCDateTime $dbActualValue->toDateTime()->getTimestamp() : null;
  704.                     if ($orgTimestamp === $actualTimestamp) {
  705.                         continue;
  706.                     }
  707.                 }
  708.                 // regular field
  709.                 $changeSet[$propName] = [$orgValue$actualValue];
  710.             }
  711.             if ($changeSet) {
  712.                 $this->documentChangeSets[$oid] = isset($this->documentChangeSets[$oid])
  713.                     ? $changeSet $this->documentChangeSets[$oid]
  714.                     : $changeSet;
  715.                 $this->originalDocumentData[$oid] = $actualData;
  716.                 $this->scheduleForUpdate($document);
  717.             }
  718.         }
  719.         // Look for changes in associations of the document
  720.         $associationMappings array_filter(
  721.             $class->associationMappings,
  722.             static fn ($assoc) => empty($assoc['notSaved'])
  723.         );
  724.         foreach ($associationMappings as $mapping) {
  725.             $value $class->reflFields[$mapping['fieldName']]->getValue($document);
  726.             if ($value === null) {
  727.                 continue;
  728.             }
  729.             $this->computeAssociationChanges($document$mapping$value);
  730.             if (isset($mapping['reference'])) {
  731.                 continue;
  732.             }
  733.             $values $mapping['type'] === ClassMetadata::ONE ? [$value] : $value->unwrap();
  734.             foreach ($values as $obj) {
  735.                 $oid2 spl_object_hash($obj);
  736.                 if (! isset($this->documentChangeSets[$oid2])) {
  737.                     continue;
  738.                 }
  739.                 if (empty($this->documentChangeSets[$oid][$mapping['fieldName']])) {
  740.                     // instance of $value is the same as it was previously otherwise there would be
  741.                     // change set already in place
  742.                     $this->documentChangeSets[$oid][$mapping['fieldName']] = [$value$value];
  743.                 }
  744.                 if (! $isNewDocument) {
  745.                     $this->scheduleForUpdate($document);
  746.                 }
  747.                 break;
  748.             }
  749.         }
  750.     }
  751.     /**
  752.      * Computes all the changes that have been done to documents and collections
  753.      * since the last commit and stores these changes in the _documentChangeSet map
  754.      * temporarily for access by the persisters, until the UoW commit is finished.
  755.      */
  756.     public function computeChangeSets(): void
  757.     {
  758.         $this->computeScheduleInsertsChangeSets();
  759.         $this->computeScheduleUpsertsChangeSets();
  760.         // Compute changes for other MANAGED documents. Change tracking policies take effect here.
  761.         foreach ($this->identityMap as $className => $documents) {
  762.             $class $this->dm->getClassMetadata($className);
  763.             if ($class->isEmbeddedDocument || $class->isView()) {
  764.                 /* we do not want to compute changes to embedded documents up front
  765.                  * in case embedded document was replaced and its changeset
  766.                  * would corrupt data. Embedded documents' change set will
  767.                  * be calculated by reachability from owning document.
  768.                  */
  769.                 continue;
  770.             }
  771.             // If change tracking is explicit or happens through notification, then only compute
  772.             // changes on document of that type that are explicitly marked for synchronization.
  773.             switch (true) {
  774.                 case $class->isChangeTrackingDeferredImplicit():
  775.                     $documentsToProcess $documents;
  776.                     break;
  777.                 case isset($this->scheduledForSynchronization[$className]):
  778.                     $documentsToProcess $this->scheduledForSynchronization[$className];
  779.                     break;
  780.                 default:
  781.                     $documentsToProcess = [];
  782.             }
  783.             foreach ($documentsToProcess as $document) {
  784.                 // Ignore uninitialized proxy objects
  785.                 if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  786.                     continue;
  787.                 }
  788.                 // Only MANAGED documents that are NOT SCHEDULED FOR INSERTION, UPSERT OR DELETION are processed here.
  789.                 $oid spl_object_hash($document);
  790.                 if (
  791.                     isset($this->documentInsertions[$oid])
  792.                     || isset($this->documentUpserts[$oid])
  793.                     || isset($this->documentDeletions[$oid])
  794.                     || ! isset($this->documentStates[$oid])
  795.                 ) {
  796.                     continue;
  797.                 }
  798.                 $this->computeChangeSet($class$document);
  799.             }
  800.         }
  801.     }
  802.     /**
  803.      * Computes the changes of an association.
  804.      *
  805.      * @param mixed $value The value of the association.
  806.      * @psalm-param AssociationFieldMapping $assoc
  807.      *
  808.      * @throws InvalidArgumentException
  809.      */
  810.     private function computeAssociationChanges(object $parentDocument, array $assoc$value): void
  811.     {
  812.         $isNewParentDocument   = isset($this->documentInsertions[spl_object_hash($parentDocument)]);
  813.         $class                 $this->dm->getClassMetadata(get_class($parentDocument));
  814.         $topOrExistingDocument = ( ! $isNewParentDocument || ! $class->isEmbeddedDocument);
  815.         if ($value instanceof GhostObjectInterface && ! $value->isProxyInitialized()) {
  816.             return;
  817.         }
  818.         if ($value instanceof PersistentCollectionInterface && $value->isDirty() && $value->getOwner() !== null && ($assoc['isOwningSide'] || isset($assoc['embedded']))) {
  819.             if ($topOrExistingDocument || CollectionHelper::usesSet($assoc['strategy'])) {
  820.                 $this->scheduleCollectionUpdate($value);
  821.             }
  822.             $topmostOwner                                               $this->getOwningDocument($value->getOwner());
  823.             $this->visitedCollections[spl_object_hash($topmostOwner)][] = $value;
  824.             if (! empty($assoc['orphanRemoval']) || isset($assoc['embedded'])) {
  825.                 $value->initialize();
  826.                 foreach ($value->getDeletedDocuments() as $orphan) {
  827.                     $this->scheduleOrphanRemoval($orphan);
  828.                 }
  829.             }
  830.         }
  831.         // Look through the documents, and in any of their associations,
  832.         // for transient (new) documents, recursively. ("Persistence by reachability")
  833.         // Unwrap. Uninitialized collections will simply be empty.
  834.         $unwrappedValue $assoc['type'] === ClassMetadata::ONE ? [$value] : $value->unwrap();
  835.         $count 0;
  836.         foreach ($unwrappedValue as $key => $entry) {
  837.             if (! is_object($entry)) {
  838.                 throw new InvalidArgumentException(
  839.                     sprintf('Expected object, found "%s" in %s::%s'$entryget_class($parentDocument), $assoc['name']),
  840.                 );
  841.             }
  842.             $targetClass $this->dm->getClassMetadata(get_class($entry));
  843.             $state $this->getDocumentState($entryself::STATE_NEW);
  844.             // Handle "set" strategy for multi-level hierarchy
  845.             $pathKey = ! isset($assoc['strategy']) || CollectionHelper::isList($assoc['strategy']) ? $count $key;
  846.             $path    $assoc['type'] === ClassMetadata::MANY $assoc['name'] . '.' $pathKey $assoc['name'];
  847.             $count++;
  848.             switch ($state) {
  849.                 case self::STATE_NEW:
  850.                     if (! $assoc['isCascadePersist']) {
  851.                         throw new InvalidArgumentException('A new document was found through a relationship that was not'
  852.                             ' configured to cascade persist operations: ' $this->objToStr($entry) . '.'
  853.                             ' Explicitly persist the new document or configure cascading persist operations'
  854.                             ' on the relationship.');
  855.                     }
  856.                     $this->persistNew($targetClass$entry);
  857.                     $this->setParentAssociation($entry$assoc$parentDocument$path);
  858.                     $this->computeChangeSet($targetClass$entry);
  859.                     break;
  860.                 case self::STATE_MANAGED:
  861.                     if ($targetClass->isEmbeddedDocument) {
  862.                         [, $knownParent] = $this->getParentAssociation($entry);
  863.                         if ($knownParent && $knownParent !== $parentDocument) {
  864.                             $entry = clone $entry;
  865.                             if ($assoc['type'] === ClassMetadata::ONE) {
  866.                                 $class->setFieldValue($parentDocument$assoc['fieldName'], $entry);
  867.                                 $this->setOriginalDocumentProperty(spl_object_hash($parentDocument), $assoc['fieldName'], $entry);
  868.                                 $poid spl_object_hash($parentDocument);
  869.                                 if (isset($this->documentChangeSets[$poid][$assoc['fieldName']])) {
  870.                                     $this->documentChangeSets[$poid][$assoc['fieldName']][1] = $entry;
  871.                                 }
  872.                             } else {
  873.                                 // must use unwrapped value to not trigger orphan removal
  874.                                 $unwrappedValue[$key] = $entry;
  875.                             }
  876.                             $this->persistNew($targetClass$entry);
  877.                         }
  878.                         $this->setParentAssociation($entry$assoc$parentDocument$path);
  879.                         $this->computeChangeSet($targetClass$entry);
  880.                     }
  881.                     break;
  882.                 case self::STATE_REMOVED:
  883.                     // Consume the $value as array (it's either an array or an ArrayAccess)
  884.                     // and remove the element from Collection.
  885.                     if ($assoc['type'] === ClassMetadata::MANY) {
  886.                         unset($value[$key]);
  887.                     }
  888.                     break;
  889.                 case self::STATE_DETACHED:
  890.                     // Can actually not happen right now as we assume STATE_NEW,
  891.                     // so the exception will be raised from the DBAL layer (constraint violation).
  892.                     throw new InvalidArgumentException('A detached document was found through a '
  893.                         'relationship during cascading a persist operation.');
  894.                 default:
  895.                     // MANAGED associated documents are already taken into account
  896.                     // during changeset calculation anyway, since they are in the identity map.
  897.             }
  898.         }
  899.     }
  900.     /**
  901.      * Computes the changeset of an individual document, independently of the
  902.      * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
  903.      *
  904.      * The passed document must be a managed document. If the document already has a change set
  905.      * because this method is invoked during a commit cycle then the change sets are added.
  906.      * whereby changes detected in this method prevail.
  907.      *
  908.      * @psalm-param ClassMetadata<T> $class
  909.      * @psalm-param T $document
  910.      *
  911.      * @throws InvalidArgumentException If the passed document is not MANAGED.
  912.      *
  913.      * @template T of object
  914.      */
  915.     public function recomputeSingleDocumentChangeSet(ClassMetadata $classobject $document): void
  916.     {
  917.         // Ignore uninitialized proxy objects
  918.         if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  919.             return;
  920.         }
  921.         $oid spl_object_hash($document);
  922.         if (! isset($this->documentStates[$oid]) || $this->documentStates[$oid] !== self::STATE_MANAGED) {
  923.             throw new InvalidArgumentException('Document must be managed.');
  924.         }
  925.         if (! $class->isInheritanceTypeNone()) {
  926.             $class $this->dm->getClassMetadata(get_class($document));
  927.         }
  928.         $this->computeOrRecomputeChangeSet($class$documenttrue);
  929.     }
  930.     /**
  931.      * @psalm-param ClassMetadata<T> $class
  932.      * @psalm-param T $document
  933.      *
  934.      * @throws InvalidArgumentException If there is something wrong with document's identifier.
  935.      *
  936.      * @template T of object
  937.      */
  938.     private function persistNew(ClassMetadata $classobject $document): void
  939.     {
  940.         $this->lifecycleEventManager->prePersist($class$document);
  941.         $oid    spl_object_hash($document);
  942.         $upsert false;
  943.         if ($class->identifier) {
  944.             $idValue $class->getIdentifierValue($document);
  945.             $upsert  = ! $class->isEmbeddedDocument && $idValue !== null;
  946.             if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_NONE && $idValue === null) {
  947.                 throw new InvalidArgumentException(sprintf(
  948.                     '%s uses NONE identifier generation strategy but no identifier was provided when persisting.',
  949.                     get_class($document),
  950.                 ));
  951.             }
  952.             if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_AUTO && $idValue !== null && ! preg_match('#^[0-9a-f]{24}$#', (string) $idValue)) {
  953.                 throw new InvalidArgumentException(sprintf(
  954.                     '%s uses AUTO identifier generation strategy but provided identifier is not a valid ObjectId.',
  955.                     get_class($document),
  956.                 ));
  957.             }
  958.             if ($class->generatorType !== ClassMetadata::GENERATOR_TYPE_NONE && $idValue === null && $class->idGenerator !== null) {
  959.                 $idValue $class->idGenerator->generate($this->dm$document);
  960.                 $idValue $class->getPHPIdentifierValue($class->getDatabaseIdentifierValue($idValue));
  961.                 $class->setIdentifierValue($document$idValue);
  962.             }
  963.             $this->documentIdentifiers[$oid] = $idValue;
  964.         } else {
  965.             // this is for embedded documents without identifiers
  966.             $this->documentIdentifiers[$oid] = $oid;
  967.         }
  968.         $this->documentStates[$oid] = self::STATE_MANAGED;
  969.         if ($upsert) {
  970.             $this->scheduleForUpsert($class$document);
  971.         } else {
  972.             $this->scheduleForInsert($class$document);
  973.         }
  974.     }
  975.     /**
  976.      * Executes all document insertions for documents of the specified type.
  977.      *
  978.      * @psalm-param ClassMetadata<T> $class
  979.      * @psalm-param T[] $documents
  980.      * @psalm-param CommitOptions $options
  981.      *
  982.      * @template T of object
  983.      */
  984.     private function executeInserts(ClassMetadata $class, array $documents, array $options = []): void
  985.     {
  986.         $persister $this->getDocumentPersister($class->name);
  987.         foreach ($documents as $oid => $document) {
  988.             $persister->addInsert($document);
  989.             unset($this->documentInsertions[$oid]);
  990.         }
  991.         $persister->executeInserts($options);
  992.         foreach ($documents as $document) {
  993.             $this->lifecycleEventManager->postPersist($class$document);
  994.         }
  995.     }
  996.     /**
  997.      * Executes all document upserts for documents of the specified type.
  998.      *
  999.      * @psalm-param ClassMetadata<T> $class
  1000.      * @psalm-param T[] $documents
  1001.      * @psalm-param CommitOptions $options
  1002.      *
  1003.      * @template T of object
  1004.      */
  1005.     private function executeUpserts(ClassMetadata $class, array $documents, array $options = []): void
  1006.     {
  1007.         $persister $this->getDocumentPersister($class->name);
  1008.         foreach ($documents as $oid => $document) {
  1009.             $persister->addUpsert($document);
  1010.             unset($this->documentUpserts[$oid]);
  1011.         }
  1012.         $persister->executeUpserts($options);
  1013.         foreach ($documents as $document) {
  1014.             $this->lifecycleEventManager->postPersist($class$document);
  1015.         }
  1016.     }
  1017.     /**
  1018.      * Executes all document updates for documents of the specified type.
  1019.      *
  1020.      * @psalm-param ClassMetadata<T> $class
  1021.      * @psalm-param T[] $documents
  1022.      * @psalm-param CommitOptions $options
  1023.      *
  1024.      * @template T of object
  1025.      */
  1026.     private function executeUpdates(ClassMetadata $class, array $documents, array $options = []): void
  1027.     {
  1028.         if ($class->isReadOnly) {
  1029.             return;
  1030.         }
  1031.         $className $class->name;
  1032.         $persister $this->getDocumentPersister($className);
  1033.         foreach ($documents as $oid => $document) {
  1034.             $this->lifecycleEventManager->preUpdate($class$document);
  1035.             if (! empty($this->documentChangeSets[$oid]) || $this->hasScheduledCollections($document)) {
  1036.                 $persister->update($document$options);
  1037.             }
  1038.             unset($this->documentUpdates[$oid]);
  1039.             $this->lifecycleEventManager->postUpdate($class$document);
  1040.         }
  1041.     }
  1042.     /**
  1043.      * Executes all document deletions for documents of the specified type.
  1044.      *
  1045.      * @psalm-param ClassMetadata<T> $class
  1046.      * @psalm-param T[] $documents
  1047.      * @psalm-param CommitOptions $options
  1048.      *
  1049.      * @template T of object
  1050.      */
  1051.     private function executeDeletions(ClassMetadata $class, array $documents, array $options = []): void
  1052.     {
  1053.         $persister $this->getDocumentPersister($class->name);
  1054.         foreach ($documents as $oid => $document) {
  1055.             if (! $class->isEmbeddedDocument) {
  1056.                 $persister->delete($document$options);
  1057.             }
  1058.             unset(
  1059.                 $this->documentDeletions[$oid],
  1060.                 $this->documentIdentifiers[$oid],
  1061.                 $this->originalDocumentData[$oid],
  1062.             );
  1063.             // Clear snapshot information for any referenced PersistentCollection
  1064.             // http://www.doctrine-project.org/jira/browse/MODM-95
  1065.             foreach ($class->associationMappings as $fieldMapping) {
  1066.                 if (! isset($fieldMapping['type']) || $fieldMapping['type'] !== ClassMetadata::MANY) {
  1067.                     continue;
  1068.                 }
  1069.                 $value $class->reflFields[$fieldMapping['fieldName']]->getValue($document);
  1070.                 if (! ($value instanceof PersistentCollectionInterface)) {
  1071.                     continue;
  1072.                 }
  1073.                 $value->clearSnapshot();
  1074.             }
  1075.             // Document with this $oid after deletion treated as NEW, even if the $oid
  1076.             // is obtained by a new document because the old one went out of scope.
  1077.             $this->documentStates[$oid] = self::STATE_NEW;
  1078.             $this->lifecycleEventManager->postRemove($class$document);
  1079.         }
  1080.     }
  1081.     /**
  1082.      * Schedules a document for insertion into the database.
  1083.      * If the document already has an identifier, it will be added to the
  1084.      * identity map.
  1085.      *
  1086.      * @internal
  1087.      *
  1088.      * @psalm-param ClassMetadata<T> $class
  1089.      * @psalm-param T $document
  1090.      *
  1091.      * @throws InvalidArgumentException
  1092.      *
  1093.      * @template T of object
  1094.      */
  1095.     public function scheduleForInsert(ClassMetadata $classobject $document): void
  1096.     {
  1097.         $oid spl_object_hash($document);
  1098.         if (isset($this->documentUpdates[$oid])) {
  1099.             throw new InvalidArgumentException('Dirty document can not be scheduled for insertion.');
  1100.         }
  1101.         if (isset($this->documentDeletions[$oid])) {
  1102.             throw new InvalidArgumentException('Removed document can not be scheduled for insertion.');
  1103.         }
  1104.         if (isset($this->documentInsertions[$oid])) {
  1105.             throw new InvalidArgumentException('Document can not be scheduled for insertion twice.');
  1106.         }
  1107.         $this->documentInsertions[$oid] = $document;
  1108.         if (! isset($this->documentIdentifiers[$oid])) {
  1109.             return;
  1110.         }
  1111.         $this->addToIdentityMap($document);
  1112.     }
  1113.     /**
  1114.      * Schedules a document for upsert into the database and adds it to the
  1115.      * identity map
  1116.      *
  1117.      * @internal
  1118.      *
  1119.      * @psalm-param ClassMetadata<T> $class
  1120.      * @psalm-param T $document
  1121.      *
  1122.      * @throws InvalidArgumentException
  1123.      *
  1124.      * @template T of object
  1125.      */
  1126.     public function scheduleForUpsert(ClassMetadata $classobject $document): void
  1127.     {
  1128.         $oid spl_object_hash($document);
  1129.         if ($class->isEmbeddedDocument) {
  1130.             throw new InvalidArgumentException('Embedded document can not be scheduled for upsert.');
  1131.         }
  1132.         if (isset($this->documentUpdates[$oid])) {
  1133.             throw new InvalidArgumentException('Dirty document can not be scheduled for upsert.');
  1134.         }
  1135.         if (isset($this->documentDeletions[$oid])) {
  1136.             throw new InvalidArgumentException('Removed document can not be scheduled for upsert.');
  1137.         }
  1138.         if (isset($this->documentUpserts[$oid])) {
  1139.             throw new InvalidArgumentException('Document can not be scheduled for upsert twice.');
  1140.         }
  1141.         $this->documentUpserts[$oid]     = $document;
  1142.         $this->documentIdentifiers[$oid] = $class->getIdentifierValue($document);
  1143.         $this->addToIdentityMap($document);
  1144.     }
  1145.     /**
  1146.      * Checks whether a document is scheduled for insertion.
  1147.      */
  1148.     public function isScheduledForInsert(object $document): bool
  1149.     {
  1150.         return isset($this->documentInsertions[spl_object_hash($document)]);
  1151.     }
  1152.     /**
  1153.      * Checks whether a document is scheduled for upsert.
  1154.      */
  1155.     public function isScheduledForUpsert(object $document): bool
  1156.     {
  1157.         return isset($this->documentUpserts[spl_object_hash($document)]);
  1158.     }
  1159.     /**
  1160.      * Schedules a document for being updated.
  1161.      *
  1162.      * @internal
  1163.      *
  1164.      * @throws InvalidArgumentException
  1165.      */
  1166.     public function scheduleForUpdate(object $document): void
  1167.     {
  1168.         $oid spl_object_hash($document);
  1169.         if (! isset($this->documentIdentifiers[$oid])) {
  1170.             throw new InvalidArgumentException('Document has no identity.');
  1171.         }
  1172.         if (isset($this->documentDeletions[$oid])) {
  1173.             throw new InvalidArgumentException('Document is removed.');
  1174.         }
  1175.         if (
  1176.             isset($this->documentUpdates[$oid])
  1177.             || isset($this->documentInsertions[$oid])
  1178.             || isset($this->documentUpserts[$oid])
  1179.         ) {
  1180.             return;
  1181.         }
  1182.         $this->documentUpdates[$oid] = $document;
  1183.     }
  1184.     /**
  1185.      * Checks whether a document is registered as dirty in the unit of work.
  1186.      * Note: Is not very useful currently as dirty documents are only registered
  1187.      * at commit time.
  1188.      */
  1189.     public function isScheduledForUpdate(object $document): bool
  1190.     {
  1191.         return isset($this->documentUpdates[spl_object_hash($document)]);
  1192.     }
  1193.     /**
  1194.      * Checks whether a document is registered to be checked in the unit of work.
  1195.      */
  1196.     public function isScheduledForSynchronization(object $document): bool
  1197.     {
  1198.         $class $this->dm->getClassMetadata(get_class($document));
  1199.         return isset($this->scheduledForSynchronization[$class->name][spl_object_hash($document)]);
  1200.     }
  1201.     /**
  1202.      * Schedules a document for deletion.
  1203.      *
  1204.      * @internal
  1205.      */
  1206.     public function scheduleForDelete(object $documentbool $isView false): void
  1207.     {
  1208.         $oid spl_object_hash($document);
  1209.         if (isset($this->documentInsertions[$oid])) {
  1210.             if ($this->isInIdentityMap($document)) {
  1211.                 $this->removeFromIdentityMap($document);
  1212.             }
  1213.             unset($this->documentInsertions[$oid]);
  1214.             return; // document has not been persisted yet, so nothing more to do.
  1215.         }
  1216.         if (! $this->isInIdentityMap($document)) {
  1217.             return; // ignore
  1218.         }
  1219.         $this->removeFromIdentityMap($document);
  1220.         $this->documentStates[$oid] = self::STATE_REMOVED;
  1221.         if (isset($this->documentUpdates[$oid])) {
  1222.             unset($this->documentUpdates[$oid]);
  1223.         }
  1224.         if (isset($this->documentUpserts[$oid])) {
  1225.             unset($this->documentUpserts[$oid]);
  1226.         }
  1227.         if (isset($this->documentDeletions[$oid])) {
  1228.             return;
  1229.         }
  1230.         if ($isView) {
  1231.             return;
  1232.         }
  1233.         $this->documentDeletions[$oid] = $document;
  1234.     }
  1235.     /**
  1236.      * Checks whether a document is registered as removed/deleted with the unit
  1237.      * of work.
  1238.      */
  1239.     public function isScheduledForDelete(object $document): bool
  1240.     {
  1241.         return isset($this->documentDeletions[spl_object_hash($document)]);
  1242.     }
  1243.     /**
  1244.      * Checks whether a document is scheduled for insertion, update or deletion.
  1245.      *
  1246.      * @internal
  1247.      */
  1248.     public function isDocumentScheduled(object $document): bool
  1249.     {
  1250.         $oid spl_object_hash($document);
  1251.         return isset($this->documentInsertions[$oid]) ||
  1252.             isset($this->documentUpserts[$oid]) ||
  1253.             isset($this->documentUpdates[$oid]) ||
  1254.             isset($this->documentDeletions[$oid]);
  1255.     }
  1256.     /**
  1257.      * Registers a document in the identity map.
  1258.      *
  1259.      * Note that documents in a hierarchy are registered with the class name of
  1260.      * the root document. Identifiers are serialized before being used as array
  1261.      * keys to allow differentiation of equal, but not identical, values.
  1262.      *
  1263.      * @internal
  1264.      */
  1265.     public function addToIdentityMap(object $document): bool
  1266.     {
  1267.         $class $this->dm->getClassMetadata(get_class($document));
  1268.         $id    $this->getIdForIdentityMap($document);
  1269.         if (isset($this->identityMap[$class->name][$id])) {
  1270.             return false;
  1271.         }
  1272.         $this->identityMap[$class->name][$id] = $document;
  1273.         if (
  1274.             $document instanceof NotifyPropertyChanged &&
  1275.             ( ! $document instanceof GhostObjectInterface || $document->isProxyInitialized())
  1276.         ) {
  1277.             $document->addPropertyChangedListener($this);
  1278.         }
  1279.         return true;
  1280.     }
  1281.     /**
  1282.      * Gets the state of a document with regard to the current unit of work.
  1283.      *
  1284.      * @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
  1285.      *                         This parameter can be set to improve performance of document state detection
  1286.      *                         by potentially avoiding a database lookup if the distinction between NEW and DETACHED
  1287.      *                         is either known or does not matter for the caller of the method.
  1288.      */
  1289.     public function getDocumentState(object $document, ?int $assume null): int
  1290.     {
  1291.         $oid spl_object_hash($document);
  1292.         if (isset($this->documentStates[$oid])) {
  1293.             return $this->documentStates[$oid];
  1294.         }
  1295.         $class $this->dm->getClassMetadata(get_class($document));
  1296.         if ($class->isEmbeddedDocument) {
  1297.             return self::STATE_NEW;
  1298.         }
  1299.         if ($assume !== null) {
  1300.             return $assume;
  1301.         }
  1302.         /* State can only be NEW or DETACHED, because MANAGED/REMOVED states are
  1303.          * known. Note that you cannot remember the NEW or DETACHED state in
  1304.          * _documentStates since the UoW does not hold references to such
  1305.          * objects and the object hash can be reused. More generally, because
  1306.          * the state may "change" between NEW/DETACHED without the UoW being
  1307.          * aware of it.
  1308.          */
  1309.         $id $class->getIdentifierObject($document);
  1310.         if ($id === null) {
  1311.             return self::STATE_NEW;
  1312.         }
  1313.         // Check for a version field, if available, to avoid a DB lookup.
  1314.         if ($class->isVersioned && $class->versionField !== null) {
  1315.             return $class->getFieldValue($document$class->versionField)
  1316.                 ? self::STATE_DETACHED
  1317.                 self::STATE_NEW;
  1318.         }
  1319.         // Last try before DB lookup: check the identity map.
  1320.         if ($this->tryGetById($id$class)) {
  1321.             return self::STATE_DETACHED;
  1322.         }
  1323.         // DB lookup
  1324.         if ($this->getDocumentPersister($class->name)->exists($document)) {
  1325.             return self::STATE_DETACHED;
  1326.         }
  1327.         return self::STATE_NEW;
  1328.     }
  1329.     /**
  1330.      * Removes a document from the identity map. This effectively detaches the
  1331.      * document from the persistence management of Doctrine.
  1332.      *
  1333.      * @internal
  1334.      *
  1335.      * @throws InvalidArgumentException
  1336.      */
  1337.     public function removeFromIdentityMap(object $document): bool
  1338.     {
  1339.         $oid spl_object_hash($document);
  1340.         // Check if id is registered first
  1341.         if (! isset($this->documentIdentifiers[$oid])) {
  1342.             return false;
  1343.         }
  1344.         $class $this->dm->getClassMetadata(get_class($document));
  1345.         $id    $this->getIdForIdentityMap($document);
  1346.         if (isset($this->identityMap[$class->name][$id])) {
  1347.             unset($this->identityMap[$class->name][$id]);
  1348.             $this->documentStates[$oid] = self::STATE_DETACHED;
  1349.             return true;
  1350.         }
  1351.         return false;
  1352.     }
  1353.     /**
  1354.      * Gets a document in the identity map by its identifier hash.
  1355.      *
  1356.      * @internal
  1357.      *
  1358.      * @param mixed $id Document identifier
  1359.      * @psalm-param ClassMetadata<T> $class
  1360.      *
  1361.      * @psalm-return T
  1362.      *
  1363.      * @throws InvalidArgumentException If the class does not have an identifier.
  1364.      *
  1365.      * @template T of object
  1366.      *
  1367.      * @psalm-suppress InvalidReturnStatement, InvalidReturnType because of the inability of defining a generic property map
  1368.      */
  1369.     public function getById($idClassMetadata $class): object
  1370.     {
  1371.         if (! $class->identifier) {
  1372.             throw new InvalidArgumentException(sprintf('Class "%s" does not have an identifier'$class->name));
  1373.         }
  1374.         $serializedId serialize($class->getDatabaseIdentifierValue($id));
  1375.         return $this->identityMap[$class->name][$serializedId];
  1376.     }
  1377.     /**
  1378.      * Tries to get a document by its identifier hash. If no document is found
  1379.      * for the given hash, FALSE is returned.
  1380.      *
  1381.      * @internal
  1382.      *
  1383.      * @param mixed $id Document identifier
  1384.      * @psalm-param ClassMetadata<T> $class
  1385.      *
  1386.      * @return mixed The found document or FALSE.
  1387.      * @psalm-return T|false
  1388.      *
  1389.      * @throws InvalidArgumentException If the class does not have an identifier.
  1390.      *
  1391.      * @template T of object
  1392.      *
  1393.      * @psalm-suppress InvalidReturnStatement, InvalidReturnType because of the inability of defining a generic property map
  1394.      */
  1395.     public function tryGetById($idClassMetadata $class)
  1396.     {
  1397.         if (! $class->identifier) {
  1398.             throw new InvalidArgumentException(sprintf('Class "%s" does not have an identifier'$class->name));
  1399.         }
  1400.         $serializedId serialize($class->getDatabaseIdentifierValue($id));
  1401.         return $this->identityMap[$class->name][$serializedId] ?? false;
  1402.     }
  1403.     /**
  1404.      * Schedules a document for dirty-checking at commit-time.
  1405.      *
  1406.      * @internal
  1407.      */
  1408.     public function scheduleForSynchronization(object $document): void
  1409.     {
  1410.         $class                                                                       $this->dm->getClassMetadata(get_class($document));
  1411.         $this->scheduledForSynchronization[$class->name][spl_object_hash($document)] = $document;
  1412.     }
  1413.     /**
  1414.      * Checks whether a document is registered in the identity map.
  1415.      *
  1416.      * @internal
  1417.      */
  1418.     public function isInIdentityMap(object $document): bool
  1419.     {
  1420.         $oid spl_object_hash($document);
  1421.         if (! isset($this->documentIdentifiers[$oid])) {
  1422.             return false;
  1423.         }
  1424.         $class $this->dm->getClassMetadata(get_class($document));
  1425.         $id    $this->getIdForIdentityMap($document);
  1426.         return isset($this->identityMap[$class->name][$id]);
  1427.     }
  1428.     private function getIdForIdentityMap(object $document): string
  1429.     {
  1430.         $class $this->dm->getClassMetadata(get_class($document));
  1431.         if (! $class->identifier) {
  1432.             $id spl_object_hash($document);
  1433.         } else {
  1434.             $id $this->documentIdentifiers[spl_object_hash($document)];
  1435.             $id serialize($class->getDatabaseIdentifierValue($id));
  1436.         }
  1437.         return $id;
  1438.     }
  1439.     /**
  1440.      * Checks whether an identifier exists in the identity map.
  1441.      *
  1442.      * @internal
  1443.      *
  1444.      * @param mixed $id
  1445.      */
  1446.     public function containsId($idstring $rootClassName): bool
  1447.     {
  1448.         return isset($this->identityMap[$rootClassName][serialize($id)]);
  1449.     }
  1450.     /**
  1451.      * Persists a document as part of the current unit of work.
  1452.      *
  1453.      * @internal
  1454.      *
  1455.      * @throws MongoDBException If trying to persist MappedSuperclass.
  1456.      * @throws InvalidArgumentException If there is something wrong with document's identifier.
  1457.      */
  1458.     public function persist(object $document): void
  1459.     {
  1460.         $class $this->dm->getClassMetadata(get_class($document));
  1461.         if ($class->isMappedSuperclass || $class->isQueryResultDocument) {
  1462.             throw MongoDBException::cannotPersistMappedSuperclass($class->name);
  1463.         }
  1464.         $visited = [];
  1465.         $this->doPersist($document$visited);
  1466.     }
  1467.     /**
  1468.      * Saves a document as part of the current unit of work.
  1469.      * This method is internally called during save() cascades as it tracks
  1470.      * the already visited documents to prevent infinite recursions.
  1471.      *
  1472.      * NOTE: This method always considers documents that are not yet known to
  1473.      * this UnitOfWork as NEW.
  1474.      *
  1475.      * @param array<string, object> $visited
  1476.      *
  1477.      * @throws InvalidArgumentException
  1478.      * @throws MongoDBException
  1479.      */
  1480.     private function doPersist(object $document, array &$visited): void
  1481.     {
  1482.         $oid spl_object_hash($document);
  1483.         if (isset($visited[$oid])) {
  1484.             return; // Prevent infinite recursion
  1485.         }
  1486.         $visited[$oid] = $document// Mark visited
  1487.         $class $this->dm->getClassMetadata(get_class($document));
  1488.         $documentState $this->getDocumentState($documentself::STATE_NEW);
  1489.         switch ($documentState) {
  1490.             case self::STATE_MANAGED:
  1491.                 // Nothing to do, except if policy is "deferred explicit"
  1492.                 if ($class->isChangeTrackingDeferredExplicit() && ! $class->isView()) {
  1493.                     $this->scheduleForSynchronization($document);
  1494.                 }
  1495.                 break;
  1496.             case self::STATE_NEW:
  1497.                 if ($class->isFile) {
  1498.                     throw MongoDBException::cannotPersistGridFSFile($class->name);
  1499.                 }
  1500.                 if ($class->isView()) {
  1501.                     return;
  1502.                 }
  1503.                 $this->persistNew($class$document);
  1504.                 break;
  1505.             case self::STATE_REMOVED:
  1506.                 // Document becomes managed again
  1507.                 unset($this->documentDeletions[$oid]);
  1508.                 $this->documentStates[$oid] = self::STATE_MANAGED;
  1509.                 break;
  1510.             case self::STATE_DETACHED:
  1511.                 throw new InvalidArgumentException(
  1512.                     'Behavior of persist() for a detached document is not yet defined.',
  1513.                 );
  1514.             default:
  1515.                 throw MongoDBException::invalidDocumentState($documentState);
  1516.         }
  1517.         $this->cascadePersist($document$visited);
  1518.     }
  1519.     /**
  1520.      * Deletes a document as part of the current unit of work.
  1521.      *
  1522.      * @internal
  1523.      */
  1524.     public function remove(object $document): void
  1525.     {
  1526.         $visited = [];
  1527.         $this->doRemove($document$visited);
  1528.     }
  1529.     /**
  1530.      * Deletes a document as part of the current unit of work.
  1531.      *
  1532.      * This method is internally called during delete() cascades as it tracks
  1533.      * the already visited documents to prevent infinite recursions.
  1534.      *
  1535.      * @param array<string, object> $visited
  1536.      *
  1537.      * @throws MongoDBException
  1538.      */
  1539.     private function doRemove(object $document, array &$visited): void
  1540.     {
  1541.         $oid spl_object_hash($document);
  1542.         if (isset($visited[$oid])) {
  1543.             return; // Prevent infinite recursion
  1544.         }
  1545.         $visited[$oid] = $document// mark visited
  1546.         /* Cascade first, because scheduleForDelete() removes the entity from
  1547.          * the identity map, which can cause problems when a lazy Proxy has to
  1548.          * be initialized for the cascade operation.
  1549.          */
  1550.         $this->cascadeRemove($document$visited);
  1551.         $class         $this->dm->getClassMetadata(get_class($document));
  1552.         $documentState $this->getDocumentState($document);
  1553.         switch ($documentState) {
  1554.             case self::STATE_NEW:
  1555.             case self::STATE_REMOVED:
  1556.                 // nothing to do
  1557.                 break;
  1558.             case self::STATE_MANAGED:
  1559.                 $this->lifecycleEventManager->preRemove($class$document);
  1560.                 $this->scheduleForDelete($document$class->isView());
  1561.                 break;
  1562.             case self::STATE_DETACHED:
  1563.                 throw MongoDBException::detachedDocumentCannotBeRemoved();
  1564.             default:
  1565.                 throw MongoDBException::invalidDocumentState($documentState);
  1566.         }
  1567.     }
  1568.     /**
  1569.      * Merges the state of the given detached document into this UnitOfWork.
  1570.      *
  1571.      * @internal
  1572.      */
  1573.     public function merge(object $document): object
  1574.     {
  1575.         $visited = [];
  1576.         return $this->doMerge($document$visited);
  1577.     }
  1578.     /**
  1579.      * Executes a merge operation on a document.
  1580.      *
  1581.      * @param array<string, object> $visited
  1582.      * @psalm-param AssociationFieldMapping|null $assoc
  1583.      *
  1584.      * @throws InvalidArgumentException If the entity instance is NEW.
  1585.      * @throws LockException If the document uses optimistic locking through a
  1586.      *                       version attribute and the version check against the
  1587.      *                       managed copy fails.
  1588.      */
  1589.     private function doMerge(object $document, array &$visited, ?object $prevManagedCopy null, ?array $assoc null): object
  1590.     {
  1591.         $oid spl_object_hash($document);
  1592.         if (isset($visited[$oid])) {
  1593.             return $visited[$oid]; // Prevent infinite recursion
  1594.         }
  1595.         $visited[$oid] = $document// mark visited
  1596.         $class $this->dm->getClassMetadata(get_class($document));
  1597.         /* First we assume DETACHED, although it can still be NEW but we can
  1598.          * avoid an extra DB round trip this way. If it is not MANAGED but has
  1599.          * an identity, we need to fetch it from the DB anyway in order to
  1600.          * merge. MANAGED documents are ignored by the merge operation.
  1601.          */
  1602.         $managedCopy $document;
  1603.         if ($this->getDocumentState($documentself::STATE_DETACHED) !== self::STATE_MANAGED) {
  1604.             if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  1605.                 $document->initializeProxy();
  1606.             }
  1607.             $identifier $class->getIdentifier();
  1608.             // We always have one element in the identifier array but it might be null
  1609.             $id          $identifier[0] !== null $class->getIdentifierObject($document) : null;
  1610.             $managedCopy null;
  1611.             // Try to fetch document from the database
  1612.             if (! $class->isEmbeddedDocument && $id !== null) {
  1613.                 $managedCopy $this->dm->find($class->name$id);
  1614.                 // Managed copy may be removed in which case we can't merge
  1615.                 if ($managedCopy && $this->getDocumentState($managedCopy) === self::STATE_REMOVED) {
  1616.                     throw new InvalidArgumentException('Removed entity detected during merge. Cannot merge with a removed entity.');
  1617.                 }
  1618.                 if ($managedCopy instanceof GhostObjectInterface && ! $managedCopy->isProxyInitialized()) {
  1619.                     $managedCopy->initializeProxy();
  1620.                 }
  1621.             }
  1622.             if ($managedCopy === null) {
  1623.                 // Create a new managed instance
  1624.                 $managedCopy $class->newInstance();
  1625.                 if ($id !== null) {
  1626.                     $class->setIdentifierValue($managedCopy$id);
  1627.                 }
  1628.                 $this->persistNew($class$managedCopy);
  1629.             }
  1630.             if ($class->isVersioned) {
  1631.                 $managedCopyVersion $class->reflFields[$class->versionField]->getValue($managedCopy);
  1632.                 $documentVersion    $class->reflFields[$class->versionField]->getValue($document);
  1633.                 // Throw exception if versions don't match
  1634.                 if ($managedCopyVersion !== $documentVersion) {
  1635.                     throw LockException::lockFailedVersionMissmatch($document$documentVersion$managedCopyVersion);
  1636.                 }
  1637.             }
  1638.             // Merge state of $document into existing (managed) document
  1639.             foreach ($class->reflClass->getProperties() as $nativeReflection) {
  1640.                 $name $nativeReflection->name;
  1641.                 $prop $this->reflectionService->getAccessibleProperty($class->name$name);
  1642.                 assert($prop instanceof ReflectionProperty);
  1643.                 if (method_exists($prop'isInitialized') && ! $prop->isInitialized($document)) {
  1644.                     continue;
  1645.                 }
  1646.                 if (! isset($class->associationMappings[$name])) {
  1647.                     if (! $class->isIdentifier($name)) {
  1648.                         $prop->setValue($managedCopy$prop->getValue($document));
  1649.                     }
  1650.                 } else {
  1651.                     $assoc2 $class->associationMappings[$name];
  1652.                     if ($assoc2['type'] === ClassMetadata::ONE) {
  1653.                         $other $prop->getValue($document);
  1654.                         if ($other === null) {
  1655.                             $prop->setValue($managedCopynull);
  1656.                         } elseif ($other instanceof GhostObjectInterface && ! $other->isProxyInitialized()) {
  1657.                             // Do not merge fields marked lazy that have not been fetched
  1658.                             continue;
  1659.                         } elseif (! $assoc2['isCascadeMerge']) {
  1660.                             if ($this->getDocumentState($other) === self::STATE_DETACHED) {
  1661.                                 $targetDocument $assoc2['targetDocument'] ?? get_class($other);
  1662.                                 $targetClass    $this->dm->getClassMetadata($targetDocument);
  1663.                                 $relatedId      $targetClass->getIdentifierObject($other);
  1664.                                 $current $prop->getValue($managedCopy);
  1665.                                 if ($current !== null) {
  1666.                                     $this->removeFromIdentityMap($current);
  1667.                                 }
  1668.                                 if ($targetClass->subClasses) {
  1669.                                     $other $this->dm->find($targetClass->name$relatedId);
  1670.                                 } else {
  1671.                                     $other $this
  1672.                                         ->dm
  1673.                                         ->getProxyFactory()
  1674.                                         ->getProxy($targetClass$relatedId);
  1675.                                     $this->registerManaged($other$relatedId, []);
  1676.                                 }
  1677.                             }
  1678.                             $prop->setValue($managedCopy$other);
  1679.                         }
  1680.                     } else {
  1681.                         $mergeCol $prop->getValue($document);
  1682.                         if ($mergeCol instanceof PersistentCollectionInterface && ! $mergeCol->isInitialized() && ! $assoc2['isCascadeMerge']) {
  1683.                             /* Do not merge fields marked lazy that have not
  1684.                              * been fetched. Keep the lazy persistent collection
  1685.                              * of the managed copy.
  1686.                              */
  1687.                             continue;
  1688.                         }
  1689.                         $managedCol $prop->getValue($managedCopy);
  1690.                         if (! $managedCol) {
  1691.                             $managedCol $this->dm->getConfiguration()->getPersistentCollectionFactory()->create($this->dm$assoc2null);
  1692.                             $managedCol->setOwner($managedCopy$assoc2);
  1693.                             $prop->setValue($managedCopy$managedCol);
  1694.                             $this->originalDocumentData[$oid][$name] = $managedCol;
  1695.                         }
  1696.                         /* Note: do not process association's target documents.
  1697.                          * They will be handled during the cascade. Initialize
  1698.                          * and, if necessary, clear $managedCol for now.
  1699.                          */
  1700.                         if ($assoc2['isCascadeMerge']) {
  1701.                             $managedCol->initialize();
  1702.                             // If $managedCol differs from the merged collection, clear and set dirty
  1703.                             if (! $managedCol->isEmpty() && $managedCol !== $mergeCol) {
  1704.                                 $managedCol->unwrap()->clear();
  1705.                                 $managedCol->setDirty(true);
  1706.                                 if ($assoc2['isOwningSide'] && $class->isChangeTrackingNotify()) {
  1707.                                     $this->scheduleForSynchronization($managedCopy);
  1708.                                 }
  1709.                             }
  1710.                         }
  1711.                     }
  1712.                 }
  1713.                 if (! $class->isChangeTrackingNotify()) {
  1714.                     continue;
  1715.                 }
  1716.                 // Just treat all properties as changed, there is no other choice.
  1717.                 $this->propertyChanged($managedCopy$namenull$prop->getValue($managedCopy));
  1718.             }
  1719.             if ($class->isChangeTrackingDeferredExplicit()) {
  1720.                 $this->scheduleForSynchronization($document);
  1721.             }
  1722.         }
  1723.         if ($prevManagedCopy !== null) {
  1724.             $assocField $assoc['fieldName'];
  1725.             $prevClass  $this->dm->getClassMetadata(get_class($prevManagedCopy));
  1726.             if ($assoc['type'] === ClassMetadata::ONE) {
  1727.                 $prevClass->reflFields[$assocField]->setValue($prevManagedCopy$managedCopy);
  1728.             } else {
  1729.                 $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);
  1730.                 if ($assoc['type'] === ClassMetadata::MANY && isset($assoc['mappedBy'])) {
  1731.                     $class->reflFields[$assoc['mappedBy']]->setValue($managedCopy$prevManagedCopy);
  1732.                 }
  1733.             }
  1734.         }
  1735.         // Mark the managed copy visited as well
  1736.         $visited[spl_object_hash($managedCopy)] = $managedCopy;
  1737.         $this->cascadeMerge($document$managedCopy$visited);
  1738.         return $managedCopy;
  1739.     }
  1740.     /**
  1741.      * Detaches a document from the persistence management. It's persistence will
  1742.      * no longer be managed by Doctrine.
  1743.      *
  1744.      * @internal
  1745.      */
  1746.     public function detach(object $document): void
  1747.     {
  1748.         $visited = [];
  1749.         $this->doDetach($document$visited);
  1750.     }
  1751.     /**
  1752.      * Executes a detach operation on the given document.
  1753.      *
  1754.      * @param array<string, object> $visited
  1755.      */
  1756.     private function doDetach(object $document, array &$visited): void
  1757.     {
  1758.         $oid spl_object_hash($document);
  1759.         if (isset($visited[$oid])) {
  1760.             return; // Prevent infinite recursion
  1761.         }
  1762.         $visited[$oid] = $document// mark visited
  1763.         switch ($this->getDocumentState($documentself::STATE_DETACHED)) {
  1764.             case self::STATE_MANAGED:
  1765.                 $this->removeFromIdentityMap($document);
  1766.                 unset(
  1767.                     $this->documentInsertions[$oid],
  1768.                     $this->documentUpdates[$oid],
  1769.                     $this->documentDeletions[$oid],
  1770.                     $this->documentIdentifiers[$oid],
  1771.                     $this->documentStates[$oid],
  1772.                     $this->originalDocumentData[$oid],
  1773.                     $this->parentAssociations[$oid],
  1774.                     $this->documentUpserts[$oid],
  1775.                     $this->hasScheduledCollections[$oid],
  1776.                     $this->embeddedDocumentsRegistry[$oid],
  1777.                 );
  1778.                 break;
  1779.             case self::STATE_NEW:
  1780.             case self::STATE_DETACHED:
  1781.                 return;
  1782.         }
  1783.         $this->cascadeDetach($document$visited);
  1784.     }
  1785.     /**
  1786.      * Refreshes the state of the given document from the database, overwriting
  1787.      * any local, unpersisted changes.
  1788.      *
  1789.      * @internal
  1790.      *
  1791.      * @throws InvalidArgumentException If the document is not MANAGED.
  1792.      */
  1793.     public function refresh(object $document): void
  1794.     {
  1795.         $visited = [];
  1796.         $this->doRefresh($document$visited);
  1797.     }
  1798.     /**
  1799.      * Executes a refresh operation on a document.
  1800.      *
  1801.      * @param array<string, object> $visited
  1802.      *
  1803.      * @throws InvalidArgumentException If the document is not MANAGED.
  1804.      */
  1805.     private function doRefresh(object $document, array &$visited): void
  1806.     {
  1807.         $oid spl_object_hash($document);
  1808.         if (isset($visited[$oid])) {
  1809.             return; // Prevent infinite recursion
  1810.         }
  1811.         $visited[$oid] = $document// mark visited
  1812.         $class $this->dm->getClassMetadata(get_class($document));
  1813.         if (! $class->isEmbeddedDocument) {
  1814.             if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
  1815.                 throw new InvalidArgumentException('Document is not MANAGED.');
  1816.             }
  1817.             $this->getDocumentPersister($class->name)->refresh($document);
  1818.         }
  1819.         $this->cascadeRefresh($document$visited);
  1820.     }
  1821.     /**
  1822.      * Cascades a refresh operation to associated documents.
  1823.      *
  1824.      * @param array<string, object> $visited
  1825.      */
  1826.     private function cascadeRefresh(object $document, array &$visited): void
  1827.     {
  1828.         $class $this->dm->getClassMetadata(get_class($document));
  1829.         $associationMappings array_filter(
  1830.             $class->associationMappings,
  1831.             static fn ($assoc) => $assoc['isCascadeRefresh']
  1832.         );
  1833.         foreach ($associationMappings as $mapping) {
  1834.             $relatedDocuments $class->reflFields[$mapping['fieldName']]->getValue($document);
  1835.             if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
  1836.                 if ($relatedDocuments instanceof PersistentCollectionInterface) {
  1837.                     // Unwrap so that foreach() does not initialize
  1838.                     $relatedDocuments $relatedDocuments->unwrap();
  1839.                 }
  1840.                 foreach ($relatedDocuments as $relatedDocument) {
  1841.                     $this->doRefresh($relatedDocument$visited);
  1842.                 }
  1843.             } elseif ($relatedDocuments !== null) {
  1844.                 $this->doRefresh($relatedDocuments$visited);
  1845.             }
  1846.         }
  1847.     }
  1848.     /**
  1849.      * Cascades a detach operation to associated documents.
  1850.      *
  1851.      * @param array<string, object> $visited
  1852.      */
  1853.     private function cascadeDetach(object $document, array &$visited): void
  1854.     {
  1855.         $class $this->dm->getClassMetadata(get_class($document));
  1856.         foreach ($class->fieldMappings as $mapping) {
  1857.             if (! $mapping['isCascadeDetach']) {
  1858.                 continue;
  1859.             }
  1860.             $relatedDocuments $class->reflFields[$mapping['fieldName']]->getValue($document);
  1861.             if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
  1862.                 if ($relatedDocuments instanceof PersistentCollectionInterface) {
  1863.                     // Unwrap so that foreach() does not initialize
  1864.                     $relatedDocuments $relatedDocuments->unwrap();
  1865.                 }
  1866.                 foreach ($relatedDocuments as $relatedDocument) {
  1867.                     $this->doDetach($relatedDocument$visited);
  1868.                 }
  1869.             } elseif ($relatedDocuments !== null) {
  1870.                 $this->doDetach($relatedDocuments$visited);
  1871.             }
  1872.         }
  1873.     }
  1874.     /**
  1875.      * Cascades a merge operation to associated documents.
  1876.      *
  1877.      * @param array<string, object> $visited
  1878.      */
  1879.     private function cascadeMerge(object $documentobject $managedCopy, array &$visited): void
  1880.     {
  1881.         $class $this->dm->getClassMetadata(get_class($document));
  1882.         $associationMappings array_filter(
  1883.             $class->associationMappings,
  1884.             static fn ($assoc) => $assoc['isCascadeMerge']
  1885.         );
  1886.         foreach ($associationMappings as $assoc) {
  1887.             $relatedDocuments $class->reflFields[$assoc['fieldName']]->getValue($document);
  1888.             if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
  1889.                 if ($relatedDocuments === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
  1890.                     // Collections are the same, so there is nothing to do
  1891.                     continue;
  1892.                 }
  1893.                 foreach ($relatedDocuments as $relatedDocument) {
  1894.                     $this->doMerge($relatedDocument$visited$managedCopy$assoc);
  1895.                 }
  1896.             } elseif ($relatedDocuments !== null) {
  1897.                 $this->doMerge($relatedDocuments$visited$managedCopy$assoc);
  1898.             }
  1899.         }
  1900.     }
  1901.     /**
  1902.      * Cascades the save operation to associated documents.
  1903.      *
  1904.      * @param array<string, object> $visited
  1905.      */
  1906.     private function cascadePersist(object $document, array &$visited): void
  1907.     {
  1908.         $class $this->dm->getClassMetadata(get_class($document));
  1909.         $associationMappings array_filter(
  1910.             $class->associationMappings,
  1911.             static fn ($assoc) => $assoc['isCascadePersist']
  1912.         );
  1913.         foreach ($associationMappings as $fieldName => $mapping) {
  1914.             $relatedDocuments $class->reflFields[$fieldName]->getValue($document);
  1915.             if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
  1916.                 if ($relatedDocuments instanceof PersistentCollectionInterface) {
  1917.                     if ($relatedDocuments->getOwner() !== $document) {
  1918.                         $relatedDocuments $this->fixPersistentCollectionOwnership($relatedDocuments$document$class$mapping['fieldName']);
  1919.                     }
  1920.                     // Unwrap so that foreach() does not initialize
  1921.                     $relatedDocuments $relatedDocuments->unwrap();
  1922.                 }
  1923.                 $count 0;
  1924.                 foreach ($relatedDocuments as $relatedKey => $relatedDocument) {
  1925.                     if (! empty($mapping['embedded'])) {
  1926.                         [, $knownParent] = $this->getParentAssociation($relatedDocument);
  1927.                         if ($knownParent && $knownParent !== $document) {
  1928.                             $relatedDocument               = clone $relatedDocument;
  1929.                             $relatedDocuments[$relatedKey] = $relatedDocument;
  1930.                         }
  1931.                         $pathKey CollectionHelper::isList($mapping['strategy']) ? $count++ : $relatedKey;
  1932.                         $this->setParentAssociation($relatedDocument$mapping$document$mapping['fieldName'] . '.' $pathKey);
  1933.                     }
  1934.                     $this->doPersist($relatedDocument$visited);
  1935.                 }
  1936.             } elseif ($relatedDocuments !== null) {
  1937.                 if (! empty($mapping['embedded'])) {
  1938.                     [, $knownParent] = $this->getParentAssociation($relatedDocuments);
  1939.                     if ($knownParent && $knownParent !== $document) {
  1940.                         $relatedDocuments = clone $relatedDocuments;
  1941.                         $class->setFieldValue($document$mapping['fieldName'], $relatedDocuments);
  1942.                     }
  1943.                     $this->setParentAssociation($relatedDocuments$mapping$document$mapping['fieldName']);
  1944.                 }
  1945.                 $this->doPersist($relatedDocuments$visited);
  1946.             }
  1947.         }
  1948.     }
  1949.     /**
  1950.      * Cascades the delete operation to associated documents.
  1951.      *
  1952.      * @param array<string, object> $visited
  1953.      */
  1954.     private function cascadeRemove(object $document, array &$visited): void
  1955.     {
  1956.         $class $this->dm->getClassMetadata(get_class($document));
  1957.         foreach ($class->fieldMappings as $mapping) {
  1958.             if (! $mapping['isCascadeRemove'] && ( ! isset($mapping['orphanRemoval']) || ! $mapping['orphanRemoval'])) {
  1959.                 continue;
  1960.             }
  1961.             if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  1962.                 $document->initializeProxy();
  1963.             }
  1964.             $relatedDocuments $class->reflFields[$mapping['fieldName']]->getValue($document);
  1965.             if ($relatedDocuments instanceof Collection || is_array($relatedDocuments)) {
  1966.                 // If its a PersistentCollection initialization is intended! No unwrap!
  1967.                 foreach ($relatedDocuments as $relatedDocument) {
  1968.                     $this->doRemove($relatedDocument$visited);
  1969.                 }
  1970.             } elseif ($relatedDocuments !== null) {
  1971.                 $this->doRemove($relatedDocuments$visited);
  1972.             }
  1973.         }
  1974.     }
  1975.     /**
  1976.      * Acquire a lock on the given document.
  1977.      *
  1978.      * @internal
  1979.      *
  1980.      * @throws LockException
  1981.      * @throws InvalidArgumentException
  1982.      */
  1983.     public function lock(object $documentint $lockMode, ?int $lockVersion null): void
  1984.     {
  1985.         if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
  1986.             throw new InvalidArgumentException('Document is not MANAGED.');
  1987.         }
  1988.         $documentName get_class($document);
  1989.         $class        $this->dm->getClassMetadata($documentName);
  1990.         if ($lockMode === LockMode::OPTIMISTIC) {
  1991.             if (! $class->isVersioned) {
  1992.                 throw LockException::notVersioned($documentName);
  1993.             }
  1994.             if ($lockVersion !== null) {
  1995.                 $documentVersion $class->reflFields[$class->versionField]->getValue($document);
  1996.                 if ($documentVersion !== $lockVersion) {
  1997.                     throw LockException::lockFailedVersionMissmatch($document$lockVersion$documentVersion);
  1998.                 }
  1999.             }
  2000.         } elseif (in_array($lockMode, [LockMode::PESSIMISTIC_READLockMode::PESSIMISTIC_WRITE])) {
  2001.             $this->getDocumentPersister($class->name)->lock($document$lockMode);
  2002.         }
  2003.     }
  2004.     /**
  2005.      * Releases a lock on the given document.
  2006.      *
  2007.      * @internal
  2008.      *
  2009.      * @throws InvalidArgumentException
  2010.      */
  2011.     public function unlock(object $document): void
  2012.     {
  2013.         if ($this->getDocumentState($document) !== self::STATE_MANAGED) {
  2014.             throw new InvalidArgumentException('Document is not MANAGED.');
  2015.         }
  2016.         $documentName get_class($document);
  2017.         $this->getDocumentPersister($documentName)->unlock($document);
  2018.     }
  2019.     /**
  2020.      * Clears the UnitOfWork.
  2021.      *
  2022.      * @internal
  2023.      */
  2024.     public function clear(?string $documentName null): void
  2025.     {
  2026.         if ($documentName === null) {
  2027.             $this->identityMap                 =
  2028.             $this->documentIdentifiers         =
  2029.             $this->originalDocumentData        =
  2030.             $this->documentChangeSets          =
  2031.             $this->documentStates              =
  2032.             $this->scheduledForSynchronization =
  2033.             $this->documentInsertions          =
  2034.             $this->documentUpserts             =
  2035.             $this->documentUpdates             =
  2036.             $this->documentDeletions           =
  2037.             $this->collectionUpdates           =
  2038.             $this->collectionDeletions         =
  2039.             $this->parentAssociations          =
  2040.             $this->embeddedDocumentsRegistry   =
  2041.             $this->orphanRemovals              =
  2042.             $this->hasScheduledCollections     = [];
  2043.         } else {
  2044.             $visited = [];
  2045.             foreach ($this->identityMap as $className => $documents) {
  2046.                 if ($className !== $documentName) {
  2047.                     continue;
  2048.                 }
  2049.                 foreach ($documents as $document) {
  2050.                     $this->doDetach($document$visited);
  2051.                 }
  2052.             }
  2053.         }
  2054.         $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->dm$documentName));
  2055.     }
  2056.     /**
  2057.      * Schedules an embedded document for removal. The remove() operation will be
  2058.      * invoked on that document at the beginning of the next commit of this
  2059.      * UnitOfWork.
  2060.      *
  2061.      * @internal
  2062.      */
  2063.     public function scheduleOrphanRemoval(object $document): void
  2064.     {
  2065.         $this->orphanRemovals[spl_object_hash($document)] = $document;
  2066.     }
  2067.     /**
  2068.      * Unschedules an embedded or referenced object for removal.
  2069.      *
  2070.      * @internal
  2071.      */
  2072.     public function unscheduleOrphanRemoval(object $document): void
  2073.     {
  2074.         $oid spl_object_hash($document);
  2075.         unset($this->orphanRemovals[$oid]);
  2076.     }
  2077.     /**
  2078.      * Fixes PersistentCollection state if it wasn't used exactly as we had in mind:
  2079.      *  1) sets owner if it was cloned
  2080.      *  2) clones collection, sets owner, updates document's property and, if necessary, updates originalData
  2081.      *  3) NOP if state is OK
  2082.      * Returned collection should be used from now on (only important with 2nd point)
  2083.      *
  2084.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2085.      * @psalm-param T $document
  2086.      * @psalm-param ClassMetadata<T> $class
  2087.      *
  2088.      * @psalm-return PersistentCollectionInterface<array-key, object>
  2089.      *
  2090.      * @template T of object
  2091.      */
  2092.     private function fixPersistentCollectionOwnership(PersistentCollectionInterface $collobject $documentClassMetadata $classstring $propName): PersistentCollectionInterface
  2093.     {
  2094.         $owner $coll->getOwner();
  2095.         if ($owner === null) { // cloned
  2096.             $coll->setOwner($document$class->fieldMappings[$propName]);
  2097.         } elseif ($owner !== $document) { // no clone, we have to fix
  2098.             if (! $coll->isInitialized()) {
  2099.                 $coll->initialize(); // we have to do this otherwise the cols share state
  2100.             }
  2101.             $newValue = clone $coll;
  2102.             $newValue->setOwner($document$class->fieldMappings[$propName]);
  2103.             $class->reflFields[$propName]->setValue($document$newValue);
  2104.             if ($this->isScheduledForUpdate($document)) {
  2105.                 // @todo following line should be superfluous once collections are stored in change sets
  2106.                 $this->setOriginalDocumentProperty(spl_object_hash($document), $propName$newValue);
  2107.             }
  2108.             return $newValue;
  2109.         }
  2110.         return $coll;
  2111.     }
  2112.     /**
  2113.      * Schedules a complete collection for removal when this UnitOfWork commits.
  2114.      *
  2115.      * @internal
  2116.      *
  2117.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2118.      */
  2119.     public function scheduleCollectionDeletion(PersistentCollectionInterface $coll): void
  2120.     {
  2121.         $oid spl_object_hash($coll);
  2122.         unset($this->collectionUpdates[$oid]);
  2123.         if (isset($this->collectionDeletions[$oid])) {
  2124.             return;
  2125.         }
  2126.         $this->collectionDeletions[$oid] = $coll;
  2127.         $this->scheduleCollectionOwner($coll);
  2128.     }
  2129.     /**
  2130.      * Checks whether a PersistentCollection is scheduled for deletion.
  2131.      *
  2132.      * @internal
  2133.      *
  2134.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2135.      */
  2136.     public function isCollectionScheduledForDeletion(PersistentCollectionInterface $coll): bool
  2137.     {
  2138.         return isset($this->collectionDeletions[spl_object_hash($coll)]);
  2139.     }
  2140.     /**
  2141.      * Unschedules a collection from being deleted when this UnitOfWork commits.
  2142.      *
  2143.      * @internal
  2144.      *
  2145.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2146.      */
  2147.     public function unscheduleCollectionDeletion(PersistentCollectionInterface $coll): void
  2148.     {
  2149.         if ($coll->getOwner() === null) {
  2150.             return;
  2151.         }
  2152.         $oid spl_object_hash($coll);
  2153.         if (! isset($this->collectionDeletions[$oid])) {
  2154.             return;
  2155.         }
  2156.         $topmostOwner $this->getOwningDocument($coll->getOwner());
  2157.         unset($this->collectionDeletions[$oid]);
  2158.         unset($this->hasScheduledCollections[spl_object_hash($topmostOwner)][$oid]);
  2159.     }
  2160.     /**
  2161.      * Schedules a collection for update when this UnitOfWork commits.
  2162.      *
  2163.      * @internal
  2164.      *
  2165.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2166.      */
  2167.     public function scheduleCollectionUpdate(PersistentCollectionInterface $coll): void
  2168.     {
  2169.         $mapping $coll->getMapping();
  2170.         if (CollectionHelper::usesSet($mapping['strategy'])) {
  2171.             /* There is no need to $unset collection if it will be $set later
  2172.              * This is NOP if collection is not scheduled for deletion
  2173.              */
  2174.             $this->unscheduleCollectionDeletion($coll);
  2175.         }
  2176.         $oid spl_object_hash($coll);
  2177.         if (isset($this->collectionUpdates[$oid])) {
  2178.             return;
  2179.         }
  2180.         $this->collectionUpdates[$oid] = $coll;
  2181.         $this->scheduleCollectionOwner($coll);
  2182.     }
  2183.     /**
  2184.      * Unschedules a collection from being updated when this UnitOfWork commits.
  2185.      *
  2186.      * @internal
  2187.      *
  2188.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2189.      */
  2190.     public function unscheduleCollectionUpdate(PersistentCollectionInterface $coll): void
  2191.     {
  2192.         if ($coll->getOwner() === null) {
  2193.             return;
  2194.         }
  2195.         $oid spl_object_hash($coll);
  2196.         if (! isset($this->collectionUpdates[$oid])) {
  2197.             return;
  2198.         }
  2199.         $topmostOwner $this->getOwningDocument($coll->getOwner());
  2200.         unset($this->collectionUpdates[$oid]);
  2201.         unset($this->hasScheduledCollections[spl_object_hash($topmostOwner)][$oid]);
  2202.     }
  2203.     /**
  2204.      * Checks whether a PersistentCollection is scheduled for update.
  2205.      *
  2206.      * @internal
  2207.      *
  2208.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2209.      */
  2210.     public function isCollectionScheduledForUpdate(PersistentCollectionInterface $coll): bool
  2211.     {
  2212.         return isset($this->collectionUpdates[spl_object_hash($coll)]);
  2213.     }
  2214.     /**
  2215.      * Gets PersistentCollections that have been visited during computing change
  2216.      * set of $document
  2217.      *
  2218.      * @internal
  2219.      *
  2220.      * @return PersistentCollectionInterface[]
  2221.      * @psalm-return array<PersistentCollectionInterface<array-key, object>>
  2222.      */
  2223.     public function getVisitedCollections(object $document): array
  2224.     {
  2225.         $oid spl_object_hash($document);
  2226.         return $this->visitedCollections[$oid] ?? [];
  2227.     }
  2228.     /**
  2229.      * Gets PersistentCollections that are scheduled to update and related to $document
  2230.      *
  2231.      * @internal
  2232.      *
  2233.      * @return PersistentCollectionInterface[]
  2234.      * @psalm-return array<string, PersistentCollectionInterface<array-key, object>>
  2235.      */
  2236.     public function getScheduledCollections(object $document): array
  2237.     {
  2238.         $oid spl_object_hash($document);
  2239.         return $this->hasScheduledCollections[$oid] ?? [];
  2240.     }
  2241.     /**
  2242.      * Checks whether the document is related to a PersistentCollection
  2243.      * scheduled for update or deletion.
  2244.      *
  2245.      * @internal
  2246.      */
  2247.     public function hasScheduledCollections(object $document): bool
  2248.     {
  2249.         return isset($this->hasScheduledCollections[spl_object_hash($document)]);
  2250.     }
  2251.     /**
  2252.      * Marks the PersistentCollection's top-level owner as having a relation to
  2253.      * a collection scheduled for update or deletion.
  2254.      *
  2255.      * If the owner is not scheduled for any lifecycle action, it will be
  2256.      * scheduled for update to ensure that versioning takes place if necessary.
  2257.      *
  2258.      * If the collection is nested within atomic collection, it is immediately
  2259.      * unscheduled and atomic one is scheduled for update instead. This makes
  2260.      * calculating update data way easier.
  2261.      *
  2262.      * @psalm-param PersistentCollectionInterface<array-key, object> $coll
  2263.      */
  2264.     private function scheduleCollectionOwner(PersistentCollectionInterface $coll): void
  2265.     {
  2266.         if ($coll->getOwner() === null) {
  2267.             return;
  2268.         }
  2269.         $document                                                                          $this->getOwningDocument($coll->getOwner());
  2270.         $this->hasScheduledCollections[spl_object_hash($document)][spl_object_hash($coll)] = $coll;
  2271.         if ($document !== $coll->getOwner()) {
  2272.             $parent  $coll->getOwner();
  2273.             $mapping = [];
  2274.             while (($parentAssoc $this->getParentAssociation($parent)) !== null) {
  2275.                 [$mapping$parent] = $parentAssoc;
  2276.             }
  2277.             if (CollectionHelper::isAtomic($mapping['strategy'])) {
  2278.                 $class            $this->dm->getClassMetadata(get_class($document));
  2279.                 $atomicCollection $class->getFieldValue($document$mapping['fieldName']);
  2280.                 $this->scheduleCollectionUpdate($atomicCollection);
  2281.                 $this->unscheduleCollectionDeletion($coll);
  2282.                 $this->unscheduleCollectionUpdate($coll);
  2283.             }
  2284.         }
  2285.         if ($this->isDocumentScheduled($document)) {
  2286.             return;
  2287.         }
  2288.         $this->scheduleForUpdate($document);
  2289.     }
  2290.     /**
  2291.      * Get the top-most owning document of a given document
  2292.      *
  2293.      * If a top-level document is provided, that same document will be returned.
  2294.      * For an embedded document, we will walk through parent associations until
  2295.      * we find a top-level document.
  2296.      *
  2297.      * @throws UnexpectedValueException When a top-level document could not be found.
  2298.      */
  2299.     public function getOwningDocument(object $document): object
  2300.     {
  2301.         $class $this->dm->getClassMetadata(get_class($document));
  2302.         while ($class->isEmbeddedDocument) {
  2303.             $parentAssociation $this->getParentAssociation($document);
  2304.             if (! $parentAssociation) {
  2305.                 throw new UnexpectedValueException('Could not determine parent association for ' get_class($document));
  2306.             }
  2307.             [, $document] = $parentAssociation;
  2308.             $class        $this->dm->getClassMetadata(get_class($document));
  2309.         }
  2310.         return $document;
  2311.     }
  2312.     /**
  2313.      * Gets the class name for an association (embed or reference) with respect
  2314.      * to any discriminator value.
  2315.      *
  2316.      * @internal
  2317.      *
  2318.      * @param FieldMapping              $mapping
  2319.      * @param array<string, mixed>|null $data
  2320.      *
  2321.      * @psalm-return class-string
  2322.      */
  2323.     public function getClassNameForAssociation(array $mapping$data): string
  2324.     {
  2325.         $discriminatorField $mapping['discriminatorField'] ?? null;
  2326.         $discriminatorValue null;
  2327.         if (isset($discriminatorField$data[$discriminatorField])) {
  2328.             $discriminatorValue $data[$discriminatorField];
  2329.         } elseif (isset($mapping['defaultDiscriminatorValue'])) {
  2330.             $discriminatorValue $mapping['defaultDiscriminatorValue'];
  2331.         }
  2332.         if ($discriminatorValue !== null) {
  2333.             return $mapping['discriminatorMap'][$discriminatorValue]
  2334.                 ?? (string) $discriminatorValue;
  2335.         }
  2336.         $class $this->dm->getClassMetadata($mapping['targetDocument']);
  2337.         if (isset($class->discriminatorField$data[$class->discriminatorField])) {
  2338.             $discriminatorValue $data[$class->discriminatorField];
  2339.         } elseif ($class->defaultDiscriminatorValue !== null) {
  2340.             $discriminatorValue $class->defaultDiscriminatorValue;
  2341.         }
  2342.         if ($discriminatorValue !== null) {
  2343.             return $class->discriminatorMap[$discriminatorValue] ?? $discriminatorValue;
  2344.         }
  2345.         return $mapping['targetDocument'];
  2346.     }
  2347.     /**
  2348.      * Creates a document. Used for reconstitution of documents during hydration.
  2349.      *
  2350.      * @psalm-param class-string<T> $className
  2351.      * @psalm-param array<string, mixed> $data
  2352.      * @psalm-param T|null $document
  2353.      * @psalm-param Hints $hints
  2354.      *
  2355.      * @psalm-return T
  2356.      *
  2357.      * @template T of object
  2358.      */
  2359.     public function getOrCreateDocument(string $className, array $data, array &$hints = [], ?object $document null): object
  2360.     {
  2361.         $class $this->dm->getClassMetadata($className);
  2362.         // @TODO figure out how to remove this
  2363.         $discriminatorValue null;
  2364.         if (isset($class->discriminatorField$data[$class->discriminatorField])) {
  2365.             $discriminatorValue $data[$class->discriminatorField];
  2366.         } elseif (isset($class->defaultDiscriminatorValue)) {
  2367.             $discriminatorValue $class->defaultDiscriminatorValue;
  2368.         }
  2369.         if ($discriminatorValue !== null) {
  2370.             /** @psalm-var class-string<T> $className */
  2371.             $className =  $class->discriminatorMap[$discriminatorValue] ?? $discriminatorValue;
  2372.             $class $this->dm->getClassMetadata($className);
  2373.             unset($data[$class->discriminatorField]);
  2374.         }
  2375.         if (! empty($hints[Query::HINT_READ_ONLY])) {
  2376.             /** @psalm-var T $document */
  2377.             $document $class->newInstance();
  2378.             $this->hydratorFactory->hydrate($document$data$hints);
  2379.             return $document;
  2380.         }
  2381.         $isManagedObject false;
  2382.         $serializedId    null;
  2383.         $id              null;
  2384.         if (! $class->isQueryResultDocument) {
  2385.             $id              $class->getDatabaseIdentifierValue($data['_id']);
  2386.             $serializedId    serialize($id);
  2387.             $isManagedObject = isset($this->identityMap[$class->name][$serializedId]);
  2388.         }
  2389.         $oid null;
  2390.         if ($isManagedObject) {
  2391.             /** @psalm-var T $document */
  2392.             $document $this->identityMap[$class->name][$serializedId];
  2393.             $oid      spl_object_hash($document);
  2394.             if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  2395.                 $document->setProxyInitializer(null);
  2396.                 $overrideLocalValues true;
  2397.                 if ($document instanceof NotifyPropertyChanged) {
  2398.                     $document->addPropertyChangedListener($this);
  2399.                 }
  2400.             } else {
  2401.                 $overrideLocalValues = ! empty($hints[Query::HINT_REFRESH]);
  2402.             }
  2403.             if ($overrideLocalValues) {
  2404.                 $data                             $this->hydratorFactory->hydrate($document$data$hints);
  2405.                 $this->originalDocumentData[$oid] = $data;
  2406.             }
  2407.         } else {
  2408.             if ($document === null) {
  2409.                 /** @psalm-var T $document */
  2410.                 $document $class->newInstance();
  2411.             }
  2412.             if (! $class->isQueryResultDocument) {
  2413.                 $this->registerManaged($document$id$data);
  2414.                 $oid                                            spl_object_hash($document);
  2415.                 $this->documentStates[$oid]                     = self::STATE_MANAGED;
  2416.                 $this->identityMap[$class->name][$serializedId] = $document;
  2417.             }
  2418.             $data $this->hydratorFactory->hydrate($document$data$hints);
  2419.             if (! $class->isQueryResultDocument && ! $class->isView()) {
  2420.                 $this->originalDocumentData[$oid] = $data;
  2421.             }
  2422.         }
  2423.         return $document;
  2424.     }
  2425.     /**
  2426.      * Initializes (loads) an uninitialized persistent collection of a document.
  2427.      *
  2428.      * @internal
  2429.      *
  2430.      * @psalm-param PersistentCollectionInterface<array-key, object> $collection
  2431.      */
  2432.     public function loadCollection(PersistentCollectionInterface $collection): void
  2433.     {
  2434.         if ($collection->getOwner() === null) {
  2435.             throw PersistentCollectionException::ownerRequiredToLoadCollection();
  2436.         }
  2437.         $this->getDocumentPersister(get_class($collection->getOwner()))->loadCollection($collection);
  2438.         $this->lifecycleEventManager->postCollectionLoad($collection);
  2439.     }
  2440.     /**
  2441.      * Gets the identity map of the UnitOfWork.
  2442.      *
  2443.      * @internal
  2444.      *
  2445.      * @psalm-return array<class-string, array<string, object>>
  2446.      */
  2447.     public function getIdentityMap(): array
  2448.     {
  2449.         return $this->identityMap;
  2450.     }
  2451.     /**
  2452.      * Gets the original data of a document. The original data is the data that was
  2453.      * present at the time the document was reconstituted from the database.
  2454.      *
  2455.      * @return array<string, mixed>
  2456.      */
  2457.     public function getOriginalDocumentData(object $document): array
  2458.     {
  2459.         $oid spl_object_hash($document);
  2460.         return $this->originalDocumentData[$oid] ?? [];
  2461.     }
  2462.     /**
  2463.      * @internal
  2464.      *
  2465.      * @param array<string, mixed> $data
  2466.      */
  2467.     public function setOriginalDocumentData(object $document, array $data): void
  2468.     {
  2469.         $oid                              spl_object_hash($document);
  2470.         $this->originalDocumentData[$oid] = $data;
  2471.         unset($this->documentChangeSets[$oid]);
  2472.     }
  2473.     /**
  2474.      * Sets a property value of the original data array of a document.
  2475.      *
  2476.      * @internal
  2477.      *
  2478.      * @param mixed $value
  2479.      */
  2480.     public function setOriginalDocumentProperty(string $oidstring $property$value): void
  2481.     {
  2482.         $this->originalDocumentData[$oid][$property] = $value;
  2483.     }
  2484.     /**
  2485.      * Gets the identifier of a document.
  2486.      *
  2487.      * @return mixed The identifier value
  2488.      */
  2489.     public function getDocumentIdentifier(object $document)
  2490.     {
  2491.         return $this->documentIdentifiers[spl_object_hash($document)] ?? null;
  2492.     }
  2493.     /**
  2494.      * Checks whether the UnitOfWork has any pending insertions.
  2495.      *
  2496.      * @internal
  2497.      *
  2498.      * @return bool TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
  2499.      */
  2500.     public function hasPendingInsertions(): bool
  2501.     {
  2502.         return ! empty($this->documentInsertions);
  2503.     }
  2504.     /**
  2505.      * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
  2506.      * number of documents in the identity map.
  2507.      *
  2508.      * @internal
  2509.      */
  2510.     public function size(): int
  2511.     {
  2512.         $count 0;
  2513.         foreach ($this->identityMap as $documentSet) {
  2514.             $count += count($documentSet);
  2515.         }
  2516.         return $count;
  2517.     }
  2518.     /**
  2519.      * Registers a document as managed.
  2520.      *
  2521.      * TODO: This method assumes that $id is a valid PHP identifier for the
  2522.      * document class. If the class expects its database identifier to be an
  2523.      * ObjectId, and an incompatible $id is registered (e.g. an integer), the
  2524.      * document identifiers map will become inconsistent with the identity map.
  2525.      * In the future, we may want to round-trip $id through a PHP and database
  2526.      * conversion and throw an exception if it's inconsistent.
  2527.      *
  2528.      * @internal
  2529.      *
  2530.      * @param mixed                $id   The identifier values.
  2531.      * @param array<string, mixed> $data
  2532.      */
  2533.     public function registerManaged(object $document$id, array $data): void
  2534.     {
  2535.         $oid   spl_object_hash($document);
  2536.         $class $this->dm->getClassMetadata(get_class($document));
  2537.         if (! $class->identifier || $id === null) {
  2538.             $this->documentIdentifiers[$oid] = $oid;
  2539.         } else {
  2540.             $this->documentIdentifiers[$oid] = $class->getPHPIdentifierValue($id);
  2541.         }
  2542.         $this->documentStates[$oid]       = self::STATE_MANAGED;
  2543.         $this->originalDocumentData[$oid] = $data;
  2544.         $this->addToIdentityMap($document);
  2545.     }
  2546.     /**
  2547.      * Clears the property changeset of the document with the given OID.
  2548.      *
  2549.      * @internal
  2550.      */
  2551.     public function clearDocumentChangeSet(string $oid): void
  2552.     {
  2553.         $this->documentChangeSets[$oid] = [];
  2554.     }
  2555.     /* PropertyChangedListener implementation */
  2556.     /**
  2557.      * Notifies this UnitOfWork of a property change in a document.
  2558.      *
  2559.      * @param object $sender       The document that owns the property.
  2560.      * @param string $propertyName The name of the property that changed.
  2561.      * @param mixed  $oldValue     The old value of the property.
  2562.      * @param mixed  $newValue     The new value of the property.
  2563.      */
  2564.     public function propertyChanged($sender$propertyName$oldValue$newValue)
  2565.     {
  2566.         $oid   spl_object_hash($sender);
  2567.         $class $this->dm->getClassMetadata(get_class($sender));
  2568.         if (! isset($class->fieldMappings[$propertyName])) {
  2569.             return; // ignore non-persistent fields
  2570.         }
  2571.         // Update changeset and mark document for synchronization
  2572.         $this->documentChangeSets[$oid][$propertyName] = [$oldValue$newValue];
  2573.         if (isset($this->scheduledForSynchronization[$class->name][$oid])) {
  2574.             return;
  2575.         }
  2576.         $this->scheduleForSynchronization($sender);
  2577.     }
  2578.     /**
  2579.      * Gets the currently scheduled document insertions in this UnitOfWork.
  2580.      *
  2581.      * @psalm-return array<string, object>
  2582.      */
  2583.     public function getScheduledDocumentInsertions(): array
  2584.     {
  2585.         return $this->documentInsertions;
  2586.     }
  2587.     /**
  2588.      * Gets the currently scheduled document upserts in this UnitOfWork.
  2589.      *
  2590.      * @psalm-return array<string, object>
  2591.      */
  2592.     public function getScheduledDocumentUpserts(): array
  2593.     {
  2594.         return $this->documentUpserts;
  2595.     }
  2596.     /**
  2597.      * Gets the currently scheduled document updates in this UnitOfWork.
  2598.      *
  2599.      * @psalm-return array<string, object>
  2600.      */
  2601.     public function getScheduledDocumentUpdates(): array
  2602.     {
  2603.         return $this->documentUpdates;
  2604.     }
  2605.     /**
  2606.      * Gets the currently scheduled document deletions in this UnitOfWork.
  2607.      *
  2608.      * @psalm-return array<string, object>
  2609.      */
  2610.     public function getScheduledDocumentDeletions(): array
  2611.     {
  2612.         return $this->documentDeletions;
  2613.     }
  2614.     /**
  2615.      * Get the currently scheduled complete collection deletions
  2616.      *
  2617.      * @internal
  2618.      *
  2619.      * @psalm-return array<string, PersistentCollectionInterface<array-key, object>>
  2620.      */
  2621.     public function getScheduledCollectionDeletions(): array
  2622.     {
  2623.         return $this->collectionDeletions;
  2624.     }
  2625.     /**
  2626.      * Gets the currently scheduled collection inserts, updates and deletes.
  2627.      *
  2628.      * @internal
  2629.      *
  2630.      * @psalm-return array<string, PersistentCollectionInterface<array-key, object>>
  2631.      */
  2632.     public function getScheduledCollectionUpdates(): array
  2633.     {
  2634.         return $this->collectionUpdates;
  2635.     }
  2636.     /**
  2637.      * Helper method to initialize a lazy loading proxy or persistent collection.
  2638.      *
  2639.      * @internal
  2640.      */
  2641.     public function initializeObject(object $obj): void
  2642.     {
  2643.         if ($obj instanceof GhostObjectInterface) {
  2644.             $obj->initializeProxy();
  2645.         } elseif ($obj instanceof PersistentCollectionInterface) {
  2646.             $obj->initialize();
  2647.         }
  2648.     }
  2649.     private function objToStr(object $obj): string
  2650.     {
  2651.         return method_exists($obj'__toString') ? (string) $obj get_class($obj) . '@' spl_object_hash($obj);
  2652.     }
  2653. }