PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Doctrine/ORM/UnitOfWork.php

http://github.com/doctrine/doctrine2
PHP | 3658 lines | 1941 code | 604 blank | 1113 comment | 316 complexity | b10434a12a688f2066144639583d2bba MD5 | raw file
Possible License(s): Unlicense

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM;
  4. use DateTimeInterface;
  5. use Doctrine\Common\Collections\ArrayCollection;
  6. use Doctrine\Common\Collections\Collection;
  7. use Doctrine\Common\EventManager;
  8. use Doctrine\Common\Proxy\Proxy;
  9. use Doctrine\DBAL\LockMode;
  10. use Doctrine\Deprecations\Deprecation;
  11. use Doctrine\ORM\Cache\Persister\CachedPersister;
  12. use Doctrine\ORM\Event\LifecycleEventArgs;
  13. use Doctrine\ORM\Event\ListenersInvoker;
  14. use Doctrine\ORM\Event\OnFlushEventArgs;
  15. use Doctrine\ORM\Event\PostFlushEventArgs;
  16. use Doctrine\ORM\Event\PreFlushEventArgs;
  17. use Doctrine\ORM\Event\PreUpdateEventArgs;
  18. use Doctrine\ORM\Exception\UnexpectedAssociationValue;
  19. use Doctrine\ORM\Id\AssignedGenerator;
  20. use Doctrine\ORM\Internal\CommitOrderCalculator;
  21. use Doctrine\ORM\Internal\HydrationCompleteHandler;
  22. use Doctrine\ORM\Mapping\ClassMetadata;
  23. use Doctrine\ORM\Mapping\MappingException;
  24. use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter;
  25. use Doctrine\ORM\Persisters\Collection\CollectionPersister;
  26. use Doctrine\ORM\Persisters\Collection\ManyToManyPersister;
  27. use Doctrine\ORM\Persisters\Collection\OneToManyPersister;
  28. use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
  29. use Doctrine\ORM\Persisters\Entity\EntityPersister;
  30. use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister;
  31. use Doctrine\ORM\Persisters\Entity\SingleTablePersister;
  32. use Doctrine\ORM\Utility\IdentifierFlattener;
  33. use Doctrine\Persistence\Mapping\RuntimeReflectionService;
  34. use Doctrine\Persistence\NotifyPropertyChanged;
  35. use Doctrine\Persistence\ObjectManagerAware;
  36. use Doctrine\Persistence\PropertyChangedListener;
  37. use Exception;
  38. use InvalidArgumentException;
  39. use RuntimeException;
  40. use Throwable;
  41. use UnexpectedValueException;
  42. use function array_combine;
  43. use function array_diff_key;
  44. use function array_filter;
  45. use function array_key_exists;
  46. use function array_map;
  47. use function array_merge;
  48. use function array_pop;
  49. use function array_sum;
  50. use function array_values;
  51. use function count;
  52. use function current;
  53. use function get_class;
  54. use function implode;
  55. use function in_array;
  56. use function is_array;
  57. use function is_object;
  58. use function method_exists;
  59. use function reset;
  60. use function spl_object_id;
  61. use function sprintf;
  62. /**
  63. * The UnitOfWork is responsible for tracking changes to objects during an
  64. * "object-level" transaction and for writing out changes to the database
  65. * in the correct order.
  66. *
  67. * Internal note: This class contains highly performance-sensitive code.
  68. */
  69. class UnitOfWork implements PropertyChangedListener
  70. {
  71. /**
  72. * An entity is in MANAGED state when its persistence is managed by an EntityManager.
  73. */
  74. public const STATE_MANAGED = 1;
  75. /**
  76. * An entity is new if it has just been instantiated (i.e. using the "new" operator)
  77. * and is not (yet) managed by an EntityManager.
  78. */
  79. public const STATE_NEW = 2;
  80. /**
  81. * A detached entity is an instance with persistent state and identity that is not
  82. * (or no longer) associated with an EntityManager (and a UnitOfWork).
  83. */
  84. public const STATE_DETACHED = 3;
  85. /**
  86. * A removed entity instance is an instance with a persistent identity,
  87. * associated with an EntityManager, whose persistent state will be deleted
  88. * on commit.
  89. */
  90. public const STATE_REMOVED = 4;
  91. /**
  92. * Hint used to collect all primary keys of associated entities during hydration
  93. * and execute it in a dedicated query afterwards
  94. *
  95. * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql
  96. */
  97. public const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
  98. /**
  99. * The identity map that holds references to all managed entities that have
  100. * an identity. The entities are grouped by their class name.
  101. * Since all classes in a hierarchy must share the same identifier set,
  102. * we always take the root class name of the hierarchy.
  103. *
  104. * @var mixed[]
  105. * @psalm-var array<class-string, array<string, object|null>>
  106. */
  107. private $identityMap = [];
  108. /**
  109. * Map of all identifiers of managed entities.
  110. * Keys are object ids (spl_object_id).
  111. *
  112. * @var mixed[]
  113. * @psalm-var array<int, array<string, mixed>>
  114. */
  115. private $entityIdentifiers = [];
  116. /**
  117. * Map of the original entity data of managed entities.
  118. * Keys are object ids (spl_object_id). This is used for calculating changesets
  119. * at commit time.
  120. *
  121. * Internal note: Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
  122. * A value will only really be copied if the value in the entity is modified
  123. * by the user.
  124. *
  125. * @psalm-var array<int, array<string, mixed>>
  126. */
  127. private $originalEntityData = [];
  128. /**
  129. * Map of entity changes. Keys are object ids (spl_object_id).
  130. * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
  131. *
  132. * @psalm-var array<int, array<string, array{mixed, mixed}>>
  133. */
  134. private $entityChangeSets = [];
  135. /**
  136. * The (cached) states of any known entities.
  137. * Keys are object ids (spl_object_id).
  138. *
  139. * @psalm-var array<int, self::STATE_*>
  140. */
  141. private $entityStates = [];
  142. /**
  143. * Map of entities that are scheduled for dirty checking at commit time.
  144. * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
  145. * Keys are object ids (spl_object_id).
  146. *
  147. * @psalm-var array<class-string, array<int, mixed>>
  148. */
  149. private $scheduledForSynchronization = [];
  150. /**
  151. * A list of all pending entity insertions.
  152. *
  153. * @psalm-var array<int, object>
  154. */
  155. private $entityInsertions = [];
  156. /**
  157. * A list of all pending entity updates.
  158. *
  159. * @psalm-var array<int, object>
  160. */
  161. private $entityUpdates = [];
  162. /**
  163. * Any pending extra updates that have been scheduled by persisters.
  164. *
  165. * @psalm-var array<int, array{object, array<string, array{mixed, mixed}>}>
  166. */
  167. private $extraUpdates = [];
  168. /**
  169. * A list of all pending entity deletions.
  170. *
  171. * @psalm-var array<int, object>
  172. */
  173. private $entityDeletions = [];
  174. /**
  175. * New entities that were discovered through relationships that were not
  176. * marked as cascade-persist. During flush, this array is populated and
  177. * then pruned of any entities that were discovered through a valid
  178. * cascade-persist path. (Leftovers cause an error.)
  179. *
  180. * Keys are OIDs, payload is a two-item array describing the association
  181. * and the entity.
  182. *
  183. * @var object[][]|array[][] indexed by respective object spl_object_id()
  184. */
  185. private $nonCascadedNewDetectedEntities = [];
  186. /**
  187. * All pending collection deletions.
  188. *
  189. * @psalm-var array<int, Collection<array-key, object>>
  190. */
  191. private $collectionDeletions = [];
  192. /**
  193. * All pending collection updates.
  194. *
  195. * @psalm-var array<int, Collection<array-key, object>>
  196. */
  197. private $collectionUpdates = [];
  198. /**
  199. * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
  200. * At the end of the UnitOfWork all these collections will make new snapshots
  201. * of their data.
  202. *
  203. * @psalm-var array<int, Collection<array-key, object>>
  204. */
  205. private $visitedCollections = [];
  206. /**
  207. * The EntityManager that "owns" this UnitOfWork instance.
  208. *
  209. * @var EntityManagerInterface
  210. */
  211. private $em;
  212. /**
  213. * The entity persister instances used to persist entity instances.
  214. *
  215. * @psalm-var array<string, EntityPersister>
  216. */
  217. private $persisters = [];
  218. /**
  219. * The collection persister instances used to persist collections.
  220. *
  221. * @psalm-var array<string, CollectionPersister>
  222. */
  223. private $collectionPersisters = [];
  224. /**
  225. * The EventManager used for dispatching events.
  226. *
  227. * @var EventManager
  228. */
  229. private $evm;
  230. /**
  231. * The ListenersInvoker used for dispatching events.
  232. *
  233. * @var ListenersInvoker
  234. */
  235. private $listenersInvoker;
  236. /**
  237. * The IdentifierFlattener used for manipulating identifiers
  238. *
  239. * @var IdentifierFlattener
  240. */
  241. private $identifierFlattener;
  242. /**
  243. * Orphaned entities that are scheduled for removal.
  244. *
  245. * @psalm-var array<int, object>
  246. */
  247. private $orphanRemovals = [];
  248. /**
  249. * Read-Only objects are never evaluated
  250. *
  251. * @var array<int, true>
  252. */
  253. private $readOnlyObjects = [];
  254. /**
  255. * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
  256. *
  257. * @psalm-var array<class-string, array<string, mixed>>
  258. */
  259. private $eagerLoadingEntities = [];
  260. /** @var bool */
  261. protected $hasCache = false;
  262. /**
  263. * Helper for handling completion of hydration
  264. *
  265. * @var HydrationCompleteHandler
  266. */
  267. private $hydrationCompleteHandler;
  268. /** @var ReflectionPropertiesGetter */
  269. private $reflectionPropertiesGetter;
  270. /**
  271. * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  272. */
  273. public function __construct(EntityManagerInterface $em)
  274. {
  275. $this->em = $em;
  276. $this->evm = $em->getEventManager();
  277. $this->listenersInvoker = new ListenersInvoker($em);
  278. $this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
  279. $this->identifierFlattener = new IdentifierFlattener($this, $em->getMetadataFactory());
  280. $this->hydrationCompleteHandler = new HydrationCompleteHandler($this->listenersInvoker, $em);
  281. $this->reflectionPropertiesGetter = new ReflectionPropertiesGetter(new RuntimeReflectionService());
  282. }
  283. /**
  284. * Commits the UnitOfWork, executing all operations that have been postponed
  285. * up to this point. The state of all managed entities will be synchronized with
  286. * the database.
  287. *
  288. * The operations are executed in the following order:
  289. *
  290. * 1) All entity insertions
  291. * 2) All entity updates
  292. * 3) All collection deletions
  293. * 4) All collection updates
  294. * 5) All entity deletions
  295. *
  296. * @param object|mixed[]|null $entity
  297. *
  298. * @return void
  299. *
  300. * @throws Exception
  301. */
  302. public function commit($entity = null)
  303. {
  304. // Raise preFlush
  305. if ($this->evm->hasListeners(Events::preFlush)) {
  306. $this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
  307. }
  308. // Compute changes done since last commit.
  309. if ($entity === null) {
  310. $this->computeChangeSets();
  311. } elseif (is_object($entity)) {
  312. $this->computeSingleEntityChangeSet($entity);
  313. } elseif (is_array($entity)) {
  314. foreach ($entity as $object) {
  315. $this->computeSingleEntityChangeSet($object);
  316. }
  317. }
  318. if (
  319. ! ($this->entityInsertions ||
  320. $this->entityDeletions ||
  321. $this->entityUpdates ||
  322. $this->collectionUpdates ||
  323. $this->collectionDeletions ||
  324. $this->orphanRemovals)
  325. ) {
  326. $this->dispatchOnFlushEvent();
  327. $this->dispatchPostFlushEvent();
  328. $this->postCommitCleanup($entity);
  329. return; // Nothing to do.
  330. }
  331. $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations();
  332. if ($this->orphanRemovals) {
  333. foreach ($this->orphanRemovals as $orphan) {
  334. $this->remove($orphan);
  335. }
  336. }
  337. $this->dispatchOnFlushEvent();
  338. // Now we need a commit order to maintain referential integrity
  339. $commitOrder = $this->getCommitOrder();
  340. $conn = $this->em->getConnection();
  341. $conn->beginTransaction();
  342. try {
  343. // Collection deletions (deletions of complete collections)
  344. foreach ($this->collectionDeletions as $collectionToDelete) {
  345. if (! $collectionToDelete instanceof PersistentCollection) {
  346. $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
  347. continue;
  348. }
  349. // Deferred explicit tracked collections can be removed only when owning relation was persisted
  350. $owner = $collectionToDelete->getOwner();
  351. if ($this->em->getClassMetadata(get_class($owner))->isChangeTrackingDeferredImplicit() || $this->isScheduledForDirtyCheck($owner)) {
  352. $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
  353. }
  354. }
  355. if ($this->entityInsertions) {
  356. foreach ($commitOrder as $class) {
  357. $this->executeInserts($class);
  358. }
  359. }
  360. if ($this->entityUpdates) {
  361. foreach ($commitOrder as $class) {
  362. $this->executeUpdates($class);
  363. }
  364. }
  365. // Extra updates that were requested by persisters.
  366. if ($this->extraUpdates) {
  367. $this->executeExtraUpdates();
  368. }
  369. // Collection updates (deleteRows, updateRows, insertRows)
  370. foreach ($this->collectionUpdates as $collectionToUpdate) {
  371. $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
  372. }
  373. // Entity deletions come last and need to be in reverse commit order
  374. if ($this->entityDeletions) {
  375. for ($count = count($commitOrder), $i = $count - 1; $i >= 0 && $this->entityDeletions; --$i) {
  376. $this->executeDeletions($commitOrder[$i]);
  377. }
  378. }
  379. // Commit failed silently
  380. if ($conn->commit() === false) {
  381. $object = is_object($entity) ? $entity : null;
  382. throw new OptimisticLockException('Commit failed', $object);
  383. }
  384. } catch (Throwable $e) {
  385. $this->em->close();
  386. if ($conn->isTransactionActive()) {
  387. $conn->rollBack();
  388. }
  389. $this->afterTransactionRolledBack();
  390. throw $e;
  391. }
  392. $this->afterTransactionComplete();
  393. // Take new snapshots from visited collections
  394. foreach ($this->visitedCollections as $coll) {
  395. $coll->takeSnapshot();
  396. }
  397. $this->dispatchPostFlushEvent();
  398. $this->postCommitCleanup($entity);
  399. }
  400. /**
  401. * @param object|object[]|null $entity
  402. */
  403. private function postCommitCleanup($entity): void
  404. {
  405. $this->entityInsertions =
  406. $this->entityUpdates =
  407. $this->entityDeletions =
  408. $this->extraUpdates =
  409. $this->collectionUpdates =
  410. $this->nonCascadedNewDetectedEntities =
  411. $this->collectionDeletions =
  412. $this->visitedCollections =
  413. $this->orphanRemovals = [];
  414. if ($entity === null) {
  415. $this->entityChangeSets = $this->scheduledForSynchronization = [];
  416. return;
  417. }
  418. $entities = is_object($entity)
  419. ? [$entity]
  420. : $entity;
  421. foreach ($entities as $object) {
  422. $oid = spl_object_id($object);
  423. $this->clearEntityChangeSet($oid);
  424. unset($this->scheduledForSynchronization[$this->em->getClassMetadata(get_class($object))->rootEntityName][$oid]);
  425. }
  426. }
  427. /**
  428. * Computes the changesets of all entities scheduled for insertion.
  429. */
  430. private function computeScheduleInsertsChangeSets(): void
  431. {
  432. foreach ($this->entityInsertions as $entity) {
  433. $class = $this->em->getClassMetadata(get_class($entity));
  434. $this->computeChangeSet($class, $entity);
  435. }
  436. }
  437. /**
  438. * Only flushes the given entity according to a ruleset that keeps the UoW consistent.
  439. *
  440. * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
  441. * 2. Read Only entities are skipped.
  442. * 3. Proxies are skipped.
  443. * 4. Only if entity is properly managed.
  444. *
  445. * @param object $entity
  446. *
  447. * @throws InvalidArgumentException
  448. */
  449. private function computeSingleEntityChangeSet($entity): void
  450. {
  451. $state = $this->getEntityState($entity);
  452. if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
  453. throw new InvalidArgumentException('Entity has to be managed or scheduled for removal for single computation ' . self::objToStr($entity));
  454. }
  455. $class = $this->em->getClassMetadata(get_class($entity));
  456. if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
  457. $this->persist($entity);
  458. }
  459. // Compute changes for INSERTed entities first. This must always happen even in this case.
  460. $this->computeScheduleInsertsChangeSets();
  461. if ($class->isReadOnly) {
  462. return;
  463. }
  464. // Ignore uninitialized proxy objects
  465. if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  466. return;
  467. }
  468. // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
  469. $oid = spl_object_id($entity);
  470. if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
  471. $this->computeChangeSet($class, $entity);
  472. }
  473. }
  474. /**
  475. * Executes any extra updates that have been scheduled.
  476. */
  477. private function executeExtraUpdates(): void
  478. {
  479. foreach ($this->extraUpdates as $oid => $update) {
  480. [$entity, $changeset] = $update;
  481. $this->entityChangeSets[$oid] = $changeset;
  482. $this->getEntityPersister(get_class($entity))->update($entity);
  483. }
  484. $this->extraUpdates = [];
  485. }
  486. /**
  487. * Gets the changeset for an entity.
  488. *
  489. * @param object $entity
  490. *
  491. * @return mixed[][]
  492. * @psalm-return array<string, array{mixed, mixed}|PersistentCollection>
  493. */
  494. public function & getEntityChangeSet($entity)
  495. {
  496. $oid = spl_object_id($entity);
  497. $data = [];
  498. if (! isset($this->entityChangeSets[$oid])) {
  499. return $data;
  500. }
  501. return $this->entityChangeSets[$oid];
  502. }
  503. /**
  504. * Computes the changes that happened to a single entity.
  505. *
  506. * Modifies/populates the following properties:
  507. *
  508. * {@link _originalEntityData}
  509. * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
  510. * then it was not fetched from the database and therefore we have no original
  511. * entity data yet. All of the current entity data is stored as the original entity data.
  512. *
  513. * {@link _entityChangeSets}
  514. * The changes detected on all properties of the entity are stored there.
  515. * A change is a tuple array where the first entry is the old value and the second
  516. * entry is the new value of the property. Changesets are used by persisters
  517. * to INSERT/UPDATE the persistent entity state.
  518. *
  519. * {@link _entityUpdates}
  520. * If the entity is already fully MANAGED (has been fetched from the database before)
  521. * and any changes to its properties are detected, then a reference to the entity is stored
  522. * there to mark it for an update.
  523. *
  524. * {@link _collectionDeletions}
  525. * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
  526. * then this collection is marked for deletion.
  527. *
  528. * @param ClassMetadata $class The class descriptor of the entity.
  529. * @param object $entity The entity for which to compute the changes.
  530. * @psalm-param ClassMetadata<T> $class
  531. * @psalm-param T $entity
  532. *
  533. * @return void
  534. *
  535. * @template T of object
  536. *
  537. * @ignore
  538. */
  539. public function computeChangeSet(ClassMetadata $class, $entity)
  540. {
  541. $oid = spl_object_id($entity);
  542. if (isset($this->readOnlyObjects[$oid])) {
  543. return;
  544. }
  545. if (! $class->isInheritanceTypeNone()) {
  546. $class = $this->em->getClassMetadata(get_class($entity));
  547. }
  548. $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush) & ~ListenersInvoker::INVOKE_MANAGER;
  549. if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  550. $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
  551. }
  552. $actualData = [];
  553. foreach ($class->reflFields as $name => $refProp) {
  554. $value = $refProp->getValue($entity);
  555. if ($class->isCollectionValuedAssociation($name) && $value !== null) {
  556. if ($value instanceof PersistentCollection) {
  557. if ($value->getOwner() === $entity) {
  558. continue;
  559. }
  560. $value = new ArrayCollection($value->getValues());
  561. }
  562. // If $value is not a Collection then use an ArrayCollection.
  563. if (! $value instanceof Collection) {
  564. $value = new ArrayCollection($value);
  565. }
  566. $assoc = $class->associationMappings[$name];
  567. // Inject PersistentCollection
  568. $value = new PersistentCollection(
  569. $this->em,
  570. $this->em->getClassMetadata($assoc['targetEntity']),
  571. $value
  572. );
  573. $value->setOwner($entity, $assoc);
  574. $value->setDirty(! $value->isEmpty());
  575. $class->reflFields[$name]->setValue($entity, $value);
  576. $actualData[$name] = $value;
  577. continue;
  578. }
  579. if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
  580. $actualData[$name] = $value;
  581. }
  582. }
  583. if (! isset($this->originalEntityData[$oid])) {
  584. // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
  585. // These result in an INSERT.
  586. $this->originalEntityData[$oid] = $actualData;
  587. $changeSet = [];
  588. foreach ($actualData as $propName => $actualValue) {
  589. if (! isset($class->associationMappings[$propName])) {
  590. $changeSet[$propName] = [null, $actualValue];
  591. continue;
  592. }
  593. $assoc = $class->associationMappings[$propName];
  594. if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  595. $changeSet[$propName] = [null, $actualValue];
  596. }
  597. }
  598. $this->entityChangeSets[$oid] = $changeSet;
  599. } else {
  600. // Entity is "fully" MANAGED: it was already fully persisted before
  601. // and we have a copy of the original data
  602. $originalData = $this->originalEntityData[$oid];
  603. $isChangeTrackingNotify = $class->isChangeTrackingNotify();
  604. $changeSet = $isChangeTrackingNotify && isset($this->entityChangeSets[$oid])
  605. ? $this->entityChangeSets[$oid]
  606. : [];
  607. foreach ($actualData as $propName => $actualValue) {
  608. // skip field, its a partially omitted one!
  609. if (! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
  610. continue;
  611. }
  612. $orgValue = $originalData[$propName];
  613. // skip if value haven't changed
  614. if ($orgValue === $actualValue) {
  615. continue;
  616. }
  617. // if regular field
  618. if (! isset($class->associationMappings[$propName])) {
  619. if ($isChangeTrackingNotify) {
  620. continue;
  621. }
  622. $changeSet[$propName] = [$orgValue, $actualValue];
  623. continue;
  624. }
  625. $assoc = $class->associationMappings[$propName];
  626. // Persistent collection was exchanged with the "originally"
  627. // created one. This can only mean it was cloned and replaced
  628. // on another entity.
  629. if ($actualValue instanceof PersistentCollection) {
  630. $owner = $actualValue->getOwner();
  631. if ($owner === null) { // cloned
  632. $actualValue->setOwner($entity, $assoc);
  633. } elseif ($owner !== $entity) { // no clone, we have to fix
  634. if (! $actualValue->isInitialized()) {
  635. $actualValue->initialize(); // we have to do this otherwise the cols share state
  636. }
  637. $newValue = clone $actualValue;
  638. $newValue->setOwner($entity, $assoc);
  639. $class->reflFields[$propName]->setValue($entity, $newValue);
  640. }
  641. }
  642. if ($orgValue instanceof PersistentCollection) {
  643. // A PersistentCollection was de-referenced, so delete it.
  644. $coid = spl_object_id($orgValue);
  645. if (isset($this->collectionDeletions[$coid])) {
  646. continue;
  647. }
  648. $this->collectionDeletions[$coid] = $orgValue;
  649. $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
  650. continue;
  651. }
  652. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  653. if ($assoc['isOwningSide']) {
  654. $changeSet[$propName] = [$orgValue, $actualValue];
  655. }
  656. if ($orgValue !== null && $assoc['orphanRemoval']) {
  657. $this->scheduleOrphanRemoval($orgValue);
  658. }
  659. }
  660. }
  661. if ($changeSet) {
  662. $this->entityChangeSets[$oid] = $changeSet;
  663. $this->originalEntityData[$oid] = $actualData;
  664. $this->entityUpdates[$oid] = $entity;
  665. }
  666. }
  667. // Look for changes in associations of the entity
  668. foreach ($class->associationMappings as $field => $assoc) {
  669. $val = $class->reflFields[$field]->getValue($entity);
  670. if ($val === null) {
  671. continue;
  672. }
  673. $this->computeAssociationChanges($assoc, $val);
  674. if (
  675. ! isset($this->entityChangeSets[$oid]) &&
  676. $assoc['isOwningSide'] &&
  677. $assoc['type'] === ClassMetadata::MANY_TO_MANY &&
  678. $val instanceof PersistentCollection &&
  679. $val->isDirty()
  680. ) {
  681. $this->entityChangeSets[$oid] = [];
  682. $this->originalEntityData[$oid] = $actualData;
  683. $this->entityUpdates[$oid] = $entity;
  684. }
  685. }
  686. }
  687. /**
  688. * Computes all the changes that have been done to entities and collections
  689. * since the last commit and stores these changes in the _entityChangeSet map
  690. * temporarily for access by the persisters, until the UoW commit is finished.
  691. *
  692. * @return void
  693. */
  694. public function computeChangeSets()
  695. {
  696. // Compute changes for INSERTed entities first. This must always happen.
  697. $this->computeScheduleInsertsChangeSets();
  698. // Compute changes for other MANAGED entities. Change tracking policies take effect here.
  699. foreach ($this->identityMap as $className => $entities) {
  700. $class = $this->em->getClassMetadata($className);
  701. // Skip class if instances are read-only
  702. if ($class->isReadOnly) {
  703. continue;
  704. }
  705. // If change tracking is explicit or happens through notification, then only compute
  706. // changes on entities of that type that are explicitly marked for synchronization.
  707. switch (true) {
  708. case $class->isChangeTrackingDeferredImplicit():
  709. $entitiesToProcess = $entities;
  710. break;
  711. case isset($this->scheduledForSynchronization[$className]):
  712. $entitiesToProcess = $this->scheduledForSynchronization[$className];
  713. break;
  714. default:
  715. $entitiesToProcess = [];
  716. }
  717. foreach ($entitiesToProcess as $entity) {
  718. // Ignore uninitialized proxy objects
  719. if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
  720. continue;
  721. }
  722. // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION OR DELETION are processed here.
  723. $oid = spl_object_id($entity);
  724. if (! isset($this->entityInsertions[$oid]) && ! isset($this->entityDeletions[$oid]) && isset($this->entityStates[$oid])) {
  725. $this->computeChangeSet($class, $entity);
  726. }
  727. }
  728. }
  729. }
  730. /**
  731. * Computes the changes of an association.
  732. *
  733. * @param mixed $value The value of the association.
  734. * @psalm-param array<string, mixed> $assoc The association mapping.
  735. *
  736. * @throws ORMInvalidArgumentException
  737. * @throws ORMException
  738. */
  739. private function computeAssociationChanges(array $assoc, $value): void
  740. {
  741. if ($value instanceof Proxy && ! $value->__isInitialized()) {
  742. return;
  743. }
  744. if ($value instanceof PersistentCollection && $value->isDirty()) {
  745. $coid = spl_object_id($value);
  746. $this->collectionUpdates[$coid] = $value;
  747. $this->visitedCollections[$coid] = $value;
  748. }
  749. // Look through the entities, and in any of their associations,
  750. // for transient (new) entities, recursively. ("Persistence by reachability")
  751. // Unwrap. Uninitialized collections will simply be empty.
  752. $unwrappedValue = $assoc['type'] & ClassMetadata::TO_ONE ? [$value] : $value->unwrap();
  753. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  754. foreach ($unwrappedValue as $key => $entry) {
  755. if (! ($entry instanceof $targetClass->name)) {
  756. throw ORMInvalidArgumentException::invalidAssociation($targetClass, $assoc, $entry);
  757. }
  758. $state = $this->getEntityState($entry, self::STATE_NEW);
  759. if (! ($entry instanceof $assoc['targetEntity'])) {
  760. throw UnexpectedAssociationValue::create(
  761. $assoc['sourceEntity'],
  762. $assoc['fieldName'],
  763. get_class($entry),
  764. $assoc['targetEntity']
  765. );
  766. }
  767. switch ($state) {
  768. case self::STATE_NEW:
  769. if (! $assoc['isCascadePersist']) {
  770. /*
  771. * For now just record the details, because this may
  772. * not be an issue if we later discover another pathway
  773. * through the object-graph where cascade-persistence
  774. * is enabled for this object.
  775. */
  776. $this->nonCascadedNewDetectedEntities[spl_object_id($entry)] = [$assoc, $entry];
  777. break;
  778. }
  779. $this->persistNew($targetClass, $entry);
  780. $this->computeChangeSet($targetClass, $entry);
  781. break;
  782. case self::STATE_REMOVED:
  783. // Consume the $value as array (it's either an array or an ArrayAccess)
  784. // and remove the element from Collection.
  785. if ($assoc['type'] & ClassMetadata::TO_MANY) {
  786. unset($value[$key]);
  787. }
  788. break;
  789. case self::STATE_DETACHED:
  790. // Can actually not happen right now as we assume STATE_NEW,
  791. // so the exception will be raised from the DBAL layer (constraint violation).
  792. throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
  793. break;
  794. default:
  795. // MANAGED associated entities are already taken into account
  796. // during changeset calculation anyway, since they are in the identity map.
  797. }
  798. }
  799. }
  800. /**
  801. * @param object $entity
  802. * @psalm-param ClassMetadata<T> $class
  803. * @psalm-param T $entity
  804. *
  805. * @template T of object
  806. */
  807. private function persistNew(ClassMetadata $class, $entity): void
  808. {
  809. $oid = spl_object_id($entity);
  810. $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
  811. if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  812. $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
  813. }
  814. $idGen = $class->idGenerator;
  815. if (! $idGen->isPostInsertGenerator()) {
  816. $idValue = $idGen->generate($this->em, $entity);
  817. if (! $idGen instanceof AssignedGenerator) {
  818. $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)];
  819. $class->setIdentifierValues($entity, $idValue);
  820. }
  821. // Some identifiers may be foreign keys to new entities.
  822. // In this case, we don't have the value yet and should treat it as if we have a post-insert generator
  823. if (! $this->hasMissingIdsWhichAreForeignKeys($class, $idValue)) {
  824. $this->entityIdentifiers[$oid] = $idValue;
  825. }
  826. }
  827. $this->entityStates[$oid] = self::STATE_MANAGED;
  828. $this->scheduleForInsert($entity);
  829. }
  830. /**
  831. * @param mixed[] $idValue
  832. */
  833. private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue): bool
  834. {
  835. foreach ($idValue as $idField => $idFieldValue) {
  836. if ($idFieldValue === null && isset($class->associationMappings[$idField])) {
  837. return true;
  838. }
  839. }
  840. return false;
  841. }
  842. /**
  843. * INTERNAL:
  844. * Computes the changeset of an individual entity, independently of the
  845. * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
  846. *
  847. * The passed entity must be a managed entity. If the entity already has a change set
  848. * because this method is invoked during a commit cycle then the change sets are added.
  849. * whereby changes detected in this method prevail.
  850. *
  851. * @param ClassMetadata $class The class descriptor of the entity.
  852. * @param object $entity The entity for which to (re)calculate the change set.
  853. * @psalm-param ClassMetadata<T> $class
  854. * @psalm-param T $entity
  855. *
  856. * @return void
  857. *
  858. * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
  859. *
  860. * @template T of object
  861. * @ignore
  862. */
  863. public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
  864. {
  865. $oid = spl_object_id($entity);
  866. if (! isset($this->entityStates[$oid]) || $this->entityStates[$oid] !== self::STATE_MANAGED) {
  867. throw ORMInvalidArgumentException::entityNotManaged($entity);
  868. }
  869. // skip if change tracking is "NOTIFY"
  870. if ($class->isChangeTrackingNotify()) {
  871. return;
  872. }
  873. if (! $class->isInheritanceTypeNone()) {
  874. $class = $this->em->getClassMetadata(get_class($entity));
  875. }
  876. $actualData = [];
  877. foreach ($class->reflFields as $name => $refProp) {
  878. if (
  879. ( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity())
  880. && ($name !== $class->versionField)
  881. && ! $class->isCollectionValuedAssociation($name)
  882. ) {
  883. $actualData[$name] = $refProp->getValue($entity);
  884. }
  885. }
  886. if (! isset($this->originalEntityData[$oid])) {
  887. throw new RuntimeException('Cannot call recomputeSingleEntityChangeSet before computeChangeSet on an entity.');
  888. }
  889. $originalData = $this->originalEntityData[$oid];
  890. $changeSet = [];
  891. foreach ($actualData as $propName => $actualValue) {
  892. $orgValue = $originalData[$propName] ?? null;
  893. if ($orgValue !== $actualValue) {
  894. $changeSet[$propName] = [$orgValue, $actualValue];
  895. }
  896. }
  897. if ($changeSet) {
  898. if (isset($this->entityChangeSets[$oid])) {
  899. $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
  900. } elseif (! isset($this->entityInsertions[$oid])) {
  901. $this->entityChangeSets[$oid] = $changeSet;
  902. $this->entityUpdates[$oid] = $entity;
  903. }
  904. $this->originalEntityData[$oid] = $actualData;
  905. }
  906. }
  907. /**
  908. * Executes all entity insertions for entities of the specified type.
  909. */
  910. private function executeInserts(ClassMetadata $class): void
  911. {
  912. $entities = [];
  913. $className = $class->name;
  914. $persister = $this->getEntityPersister($className);
  915. $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
  916. $insertionsForClass = [];
  917. foreach ($this->entityInsertions as $oid => $entity) {
  918. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  919. continue;
  920. }
  921. $insertionsForClass[$oid] = $entity;
  922. $persister->addInsert($entity);
  923. unset($this->entityInsertions[$oid]);
  924. if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  925. $entities[] = $entity;
  926. }
  927. }
  928. $postInsertIds = $persister->executeInserts();
  929. if ($postInsertIds) {
  930. // Persister returned post-insert IDs
  931. foreach ($postInsertIds as $postInsertId) {
  932. $idField = $class->getSingleIdentifierFieldName();
  933. $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']);
  934. $entity = $postInsertId['entity'];
  935. $oid = spl_object_id($entity);
  936. $class->reflFields[$idField]->setValue($entity, $idValue);
  937. $this->entityIdentifiers[$oid] = [$idField => $idValue];
  938. $this->entityStates[$oid] = self::STATE_MANAGED;
  939. $this->originalEntityData[$oid][$idField] = $idValue;
  940. $this->addToIdentityMap($entity);
  941. }
  942. } else {
  943. foreach ($insertionsForClass as $oid => $entity) {
  944. if (! isset($this->entityIdentifiers[$oid])) {
  945. //entity was not added to identity map because some identifiers are foreign keys to new entities.
  946. //add it now
  947. $this->addToEntityIdentifiersAndEntityMap($class, $oid, $entity);
  948. }
  949. }
  950. }
  951. foreach ($entities as $entity) {
  952. $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
  953. }
  954. }
  955. /**
  956. * @param object $entity
  957. * @psalm-param ClassMetadata<T> $class
  958. * @psalm-param T $entity
  959. *
  960. * @template T of object
  961. */
  962. private function addToEntityIdentifiersAndEntityMap(
  963. ClassMetadata $class,
  964. int $oid,
  965. $entity
  966. ): void {
  967. $identifier = [];
  968. foreach ($class->getIdentifierFieldNames() as $idField) {
  969. $value = $class->getFieldValue($entity, $idField);
  970. if (isset($class->associationMappings[$idField])) {
  971. // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced.
  972. $value = $this->getSingleIdentifierValue($value);
  973. }
  974. $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value;
  975. }
  976. $this->entityStates[$oid] = self::STATE_MANAGED;
  977. $this->entityIdentifiers[$oid] = $identifier;
  978. $this->addToIdentityMap($entity);
  979. }
  980. /**
  981. * Executes all entity updates for entities of the specified type.
  982. */
  983. private function executeUpdates(ClassMetadata $class): void
  984. {
  985. $className = $class->name;
  986. $persister = $this->getEntityPersister($className);
  987. $preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
  988. $postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
  989. foreach ($this->entityUpdates as $oid => $entity) {
  990. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  991. continue;
  992. }
  993. if ($preUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
  994. $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->getEntityChangeSet($entity)), $preUpdateInvoke);
  995. $this->recomputeSingleEntityChangeSet($class, $entity);
  996. }
  997. if (! empty($this->entityChangeSets[$oid])) {
  998. $persister->update($entity);
  999. }
  1000. unset($this->entityUpdates[$oid]);
  1001. if ($postUpdateInvoke !== ListenersInvoker::INVOKE_NONE) {
  1002. $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
  1003. }
  1004. }
  1005. }
  1006. /**
  1007. * Executes all entity deletions for entities of the specified type.
  1008. */
  1009. private function executeDeletions(ClassMetadata $class): void
  1010. {
  1011. $className = $class->name;
  1012. $persister = $this->getEntityPersister($className);
  1013. $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
  1014. foreach ($this->entityDeletions as $oid => $entity) {
  1015. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  1016. continue;
  1017. }
  1018. $persister->delete($entity);
  1019. unset(
  1020. $this->entityDeletions[$oid],
  1021. $this->entityIdentifiers[$oid],
  1022. $this->originalEntityData[$oid],
  1023. $this->entityStates[$oid]
  1024. );
  1025. // Entity with this $oid after deletion treated as NEW, even if the $oid
  1026. // is obtained by a new entity because the old one went out of scope.
  1027. //$this->entityStates[$oid] = self::STATE_NEW;
  1028. if (! $class->isIdentifierNatural()) {
  1029. $class->reflFields[$class->identifier[0]]->setValue($entity, null);
  1030. }
  1031. if ($invoke !== ListenersInvoker::INVOKE_NONE) {
  1032. $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
  1033. }
  1034. }
  1035. }
  1036. /**
  1037. * Gets the commit order.
  1038. *
  1039. * @return list<object>
  1040. */
  1041. private function getCommitOrder(): array
  1042. {
  1043. $calc = $this->getCommitOrderCalculator();
  1044. // See if there are any new classes in the changeset, that are not in the
  1045. // commit order graph yet (don't have a node).
  1046. // We have to inspect changeSet to be able to correctly build dependencies.
  1047. // It is not possible to use IdentityMap here because post inserted ids
  1048. // are not yet available.
  1049. $newNodes = [];
  1050. foreach (array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions) as $entity) {
  1051. $class = $this->em->getClassMetadata(get_class($entity));
  1052. if ($calc->hasNode($class->name)) {
  1053. continue;
  1054. }
  1055. $calc->addNode($class->name, $class);
  1056. $newNodes[] = $class;
  1057. }
  1058. // Calculate dependencies for new nodes
  1059. while ($class = array_pop($newNodes)) {
  1060. foreach ($class->associationMappings as $assoc) {
  1061. if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1062. continue;
  1063. }
  1064. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1065. if (! $calc->hasNode($targetClass->name)) {
  1066. $calc->addNode($targetClass->name, $targetClass);
  1067. $newNodes[] = $targetClass;
  1068. }
  1069. $joinColumns = reset($assoc['joinColumns']);
  1070. $calc->addDependency($targetClass->name, $class->name, (int) empty($joinColumns['nullable']));
  1071. // If the target class has mapped subclasses, these share the same dependency.
  1072. if (! $targetClass->subClasses) {
  1073. continue;
  1074. }
  1075. foreach ($targetClass->subClasses as $subClassName) {
  1076. $targetSubClass = $this->em->getClassMetadata($subClassName);
  1077. if (! $calc->hasNode($subClassName)) {
  1078. $calc->addNode($targetSubClass->name, $targetSubClass);
  1079. $newNodes[] = $targetSubClass;
  1080. }
  1081. $calc->addDependency($targetSubClass->name, $class->name, 1);
  1082. }
  1083. }
  1084. }
  1085. return $calc->sort();
  1086. }
  1087. /**
  1088. * Schedules an entity for insertion into the database.
  1089. * If the entity already has an identifier, it will be added to the identity map.
  1090. *
  1091. * @param object $entity The entity to schedule for insertion.
  1092. *
  1093. * @return void
  1094. *
  1095. * @throws ORMInvalidArgumentException
  1096. * @throws InvalidArgumentException
  1097. */
  1098. public function scheduleForInsert($entity)
  1099. {
  1100. $oid = spl_object_id($entity);
  1101. if (isset($this->entityUpdates[$oid])) {
  1102. throw new InvalidArgumentException('Dirty entity can not be scheduled for insertion.');
  1103. }
  1104. if (isset($this->entityDeletions[$oid])) {
  1105. throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
  1106. }
  1107. if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1108. throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
  1109. }
  1110. if (isset($this->entityInsertions[$oid])) {
  1111. throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
  1112. }
  1113. $this->entityInsertions[$oid] = $entity;
  1114. if (isset($this->entityIdentifiers[$oid])) {
  1115. $this->addToIdentityMap($entity);
  1116. }
  1117. if ($entity instanceof NotifyPropertyChanged) {
  1118. $entity->addPropertyChangedListener($this);
  1119. }
  1120. }
  1121. /**
  1122. * Checks whether an entity is scheduled for insertion.
  1123. *
  1124. * @param object $entity
  1125. *
  1126. * @return bool
  1127. */
  1128. public function isScheduledForInsert($entity)
  1129. {
  1130. return isset($this->entityInsertions[spl_object_id($entity)]);
  1131. }
  1132. /**
  1133. * Schedules an entity for being updated.
  1134. *
  1135. * @param object $entity The entity to schedule for being updated.
  1136. *
  1137. * @return void
  1138. *
  1139. * @throws ORMInvalidArgumentException
  1140. */
  1141. public function scheduleForUpdate($entity)
  1142. {
  1143. $oid = spl_object_id($entity);
  1144. if (! isset($this->entityIdentifiers[$oid])) {
  1145. throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
  1146. }
  1147. if (isset($this->entityDeletions[$oid])) {
  1148. throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
  1149. }
  1150. if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
  1151. $this->entityUpdates[$oid] = $entity;
  1152. }
  1153. }
  1154. /**
  1155. * INTERNAL:
  1156. * Schedules an extra update that will be executed immediately after the
  1157. * regular entity updates within the currently running commit cycle.
  1158. *
  1159. * Extra updates for entities are stored as (entity, changeset) tuples.
  1160. *
  1161. * @param object $entity The entity for which to schedule an extra update.
  1162. * @psalm-param array<string, array{mixed, mixed}> $changeset The changeset of the entity (what to update).
  1163. *
  1164. * @return void
  1165. *
  1166. * @ignore
  1167. */
  1168. public function scheduleExtraUpdate($entity, array $changeset)
  1169. {
  1170. $oid = spl_object_id($entity);
  1171. $extraUpdate = [$entity, $changeset];
  1172. if (isset($this->extraUpdates[$oid])) {
  1173. [, $changeset2] = $this->extraUpdates[$oid];
  1174. $extraUpdate = [$entity, $changeset + $changeset2];
  1175. }
  1176. $this->extraUpdates[$oid] = $extraUpdate;
  1177. }
  1178. /**
  1179. * Checks whether an entity is registered as dirty in the unit of work.
  1180. * Note: Is not very useful currently as dirty entities are only r…

Large files files are truncated, but you can click here to view the full file