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