vendor/doctrine/orm/src/UnitOfWork.php line 3011

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