PageRenderTime 55ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Doctrine/ORM/UnitOfWork.php

https://github.com/stephaneerard/doctrine2
PHP | 3048 lines | 1594 code | 502 blank | 952 comment | 300 complexity | d3331c8db0c0134261ccb6562e783398 MD5 | raw file
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Exception;
  21. use InvalidArgumentException;
  22. use UnexpectedValueException;
  23. use Doctrine\Common\Collections\ArrayCollection;
  24. use Doctrine\Common\Collections\Collection;
  25. use Doctrine\Common\NotifyPropertyChanged;
  26. use Doctrine\Common\PropertyChangedListener;
  27. use Doctrine\Common\Persistence\ObjectManagerAware;
  28. use Doctrine\ORM\Event\LifecycleEventArgs;
  29. use Doctrine\ORM\Mapping\ClassMetadata;
  30. use Doctrine\ORM\Proxy\Proxy;
  31. /**
  32. * The UnitOfWork is responsible for tracking changes to objects during an
  33. * "object-level" transaction and for writing out changes to the database
  34. * in the correct order.
  35. *
  36. * @since 2.0
  37. * @author Benjamin Eberlei <kontakt@beberlei.de>
  38. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  39. * @author Jonathan Wage <jonwage@gmail.com>
  40. * @author Roman Borschel <roman@code-factory.org>
  41. * @internal This class contains highly performance-sensitive code.
  42. */
  43. class UnitOfWork implements PropertyChangedListener
  44. {
  45. /**
  46. * An entity is in MANAGED state when its persistence is managed by an EntityManager.
  47. */
  48. const STATE_MANAGED = 1;
  49. /**
  50. * An entity is new if it has just been instantiated (i.e. using the "new" operator)
  51. * and is not (yet) managed by an EntityManager.
  52. */
  53. const STATE_NEW = 2;
  54. /**
  55. * A detached entity is an instance with persistent state and identity that is not
  56. * (or no longer) associated with an EntityManager (and a UnitOfWork).
  57. */
  58. const STATE_DETACHED = 3;
  59. /**
  60. * A removed entity instance is an instance with a persistent identity,
  61. * associated with an EntityManager, whose persistent state will be deleted
  62. * on commit.
  63. */
  64. const STATE_REMOVED = 4;
  65. /**
  66. * The identity map that holds references to all managed entities that have
  67. * an identity. The entities are grouped by their class name.
  68. * Since all classes in a hierarchy must share the same identifier set,
  69. * we always take the root class name of the hierarchy.
  70. *
  71. * @var array
  72. */
  73. private $identityMap = array();
  74. /**
  75. * Map of all identifiers of managed entities.
  76. * Keys are object ids (spl_object_hash).
  77. *
  78. * @var array
  79. */
  80. private $entityIdentifiers = array();
  81. /**
  82. * Map of the original entity data of managed entities.
  83. * Keys are object ids (spl_object_hash). This is used for calculating changesets
  84. * at commit time.
  85. *
  86. * @var array
  87. * @internal Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
  88. * A value will only really be copied if the value in the entity is modified
  89. * by the user.
  90. */
  91. private $originalEntityData = array();
  92. /**
  93. * Map of entity changes. Keys are object ids (spl_object_hash).
  94. * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
  95. *
  96. * @var array
  97. */
  98. private $entityChangeSets = array();
  99. /**
  100. * The (cached) states of any known entities.
  101. * Keys are object ids (spl_object_hash).
  102. *
  103. * @var array
  104. */
  105. private $entityStates = array();
  106. /**
  107. * Map of entities that are scheduled for dirty checking at commit time.
  108. * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
  109. * Keys are object ids (spl_object_hash).
  110. *
  111. * @var array
  112. * @todo rename: scheduledForSynchronization
  113. */
  114. private $scheduledForDirtyCheck = array();
  115. /**
  116. * A list of all pending entity insertions.
  117. *
  118. * @var array
  119. */
  120. private $entityInsertions = array();
  121. /**
  122. * A list of all pending entity updates.
  123. *
  124. * @var array
  125. */
  126. private $entityUpdates = array();
  127. /**
  128. * Any pending extra updates that have been scheduled by persisters.
  129. *
  130. * @var array
  131. */
  132. private $extraUpdates = array();
  133. /**
  134. * A list of all pending entity deletions.
  135. *
  136. * @var array
  137. */
  138. private $entityDeletions = array();
  139. /**
  140. * All pending collection deletions.
  141. *
  142. * @var array
  143. */
  144. private $collectionDeletions = array();
  145. /**
  146. * All pending collection updates.
  147. *
  148. * @var array
  149. */
  150. private $collectionUpdates = array();
  151. /**
  152. * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
  153. * At the end of the UnitOfWork all these collections will make new snapshots
  154. * of their data.
  155. *
  156. * @var array
  157. */
  158. private $visitedCollections = array();
  159. /**
  160. * The EntityManager that "owns" this UnitOfWork instance.
  161. *
  162. * @var \Doctrine\ORM\EntityManager
  163. */
  164. private $em;
  165. /**
  166. * The calculator used to calculate the order in which changes to
  167. * entities need to be written to the database.
  168. *
  169. * @var \Doctrine\ORM\Internal\CommitOrderCalculator
  170. */
  171. private $commitOrderCalculator;
  172. /**
  173. * The entity persister instances used to persist entity instances.
  174. *
  175. * @var array
  176. */
  177. private $persisters = array();
  178. /**
  179. * The collection persister instances used to persist collections.
  180. *
  181. * @var array
  182. */
  183. private $collectionPersisters = array();
  184. /**
  185. * The EventManager used for dispatching events.
  186. *
  187. * @var \Doctrine\Common\EventManager
  188. */
  189. private $evm;
  190. /**
  191. * Orphaned entities that are scheduled for removal.
  192. *
  193. * @var array
  194. */
  195. private $orphanRemovals = array();
  196. /**
  197. * Read-Only objects are never evaluated
  198. *
  199. * @var array
  200. */
  201. private $readOnlyObjects = array();
  202. /**
  203. * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
  204. *
  205. * @var array
  206. */
  207. private $eagerLoadingEntities = array();
  208. /**
  209. * Initializes a new UnitOfWork instance, bound to the given EntityManager.
  210. *
  211. * @param \Doctrine\ORM\EntityManager $em
  212. */
  213. public function __construct(EntityManager $em)
  214. {
  215. $this->em = $em;
  216. $this->evm = $em->getEventManager();
  217. }
  218. /**
  219. * Commits the UnitOfWork, executing all operations that have been postponed
  220. * up to this point. The state of all managed entities will be synchronized with
  221. * the database.
  222. *
  223. * The operations are executed in the following order:
  224. *
  225. * 1) All entity insertions
  226. * 2) All entity updates
  227. * 3) All collection deletions
  228. * 4) All collection updates
  229. * 5) All entity deletions
  230. *
  231. * @param null|object|array $entity
  232. *
  233. * @throws \Exception
  234. *
  235. * @return void
  236. */
  237. public function commit($entity = null)
  238. {
  239. // Raise preFlush
  240. if ($this->evm->hasListeners(Events::preFlush)) {
  241. $this->evm->dispatchEvent(Events::preFlush, new Event\PreFlushEventArgs($this->em));
  242. }
  243. // Compute changes done since last commit.
  244. if ($entity === null) {
  245. $this->computeChangeSets();
  246. } elseif (is_object($entity)) {
  247. $this->computeSingleEntityChangeSet($entity);
  248. } elseif (is_array($entity)) {
  249. foreach ($entity as $object) {
  250. $this->computeSingleEntityChangeSet($object);
  251. }
  252. }
  253. if ( ! ($this->entityInsertions ||
  254. $this->entityDeletions ||
  255. $this->entityUpdates ||
  256. $this->collectionUpdates ||
  257. $this->collectionDeletions ||
  258. $this->orphanRemovals)) {
  259. return; // Nothing to do.
  260. }
  261. if ($this->orphanRemovals) {
  262. foreach ($this->orphanRemovals as $orphan) {
  263. $this->remove($orphan);
  264. }
  265. }
  266. // Raise onFlush
  267. if ($this->evm->hasListeners(Events::onFlush)) {
  268. $this->evm->dispatchEvent(Events::onFlush, new Event\OnFlushEventArgs($this->em));
  269. }
  270. // Now we need a commit order to maintain referential integrity
  271. $commitOrder = $this->getCommitOrder();
  272. $conn = $this->em->getConnection();
  273. $conn->beginTransaction();
  274. try {
  275. if ($this->entityInsertions) {
  276. foreach ($commitOrder as $class) {
  277. $this->executeInserts($class);
  278. }
  279. }
  280. if ($this->entityUpdates) {
  281. foreach ($commitOrder as $class) {
  282. $this->executeUpdates($class);
  283. }
  284. }
  285. // Extra updates that were requested by persisters.
  286. if ($this->extraUpdates) {
  287. $this->executeExtraUpdates();
  288. }
  289. // Collection deletions (deletions of complete collections)
  290. foreach ($this->collectionDeletions as $collectionToDelete) {
  291. $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
  292. }
  293. // Collection updates (deleteRows, updateRows, insertRows)
  294. foreach ($this->collectionUpdates as $collectionToUpdate) {
  295. $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
  296. }
  297. // Entity deletions come last and need to be in reverse commit order
  298. if ($this->entityDeletions) {
  299. for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
  300. $this->executeDeletions($commitOrder[$i]);
  301. }
  302. }
  303. $conn->commit();
  304. } catch (Exception $e) {
  305. $this->em->close();
  306. $conn->rollback();
  307. throw $e;
  308. }
  309. // Take new snapshots from visited collections
  310. foreach ($this->visitedCollections as $coll) {
  311. $coll->takeSnapshot();
  312. }
  313. // Raise postFlush
  314. if ($this->evm->hasListeners(Events::postFlush)) {
  315. $this->evm->dispatchEvent(Events::postFlush, new Event\PostFlushEventArgs($this->em));
  316. }
  317. // Clear up
  318. $this->entityInsertions =
  319. $this->entityUpdates =
  320. $this->entityDeletions =
  321. $this->extraUpdates =
  322. $this->entityChangeSets =
  323. $this->collectionUpdates =
  324. $this->collectionDeletions =
  325. $this->visitedCollections =
  326. $this->scheduledForDirtyCheck =
  327. $this->orphanRemovals = array();
  328. }
  329. /**
  330. * Compute the changesets of all entities scheduled for insertion
  331. *
  332. * @return void
  333. */
  334. private function computeScheduleInsertsChangeSets()
  335. {
  336. foreach ($this->entityInsertions as $entity) {
  337. $class = $this->em->getClassMetadata(get_class($entity));
  338. $this->computeChangeSet($class, $entity);
  339. }
  340. }
  341. /**
  342. * Only flush the given entity according to a ruleset that keeps the UoW consistent.
  343. *
  344. * 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
  345. * 2. Read Only entities are skipped.
  346. * 3. Proxies are skipped.
  347. * 4. Only if entity is properly managed.
  348. *
  349. * @param object $entity
  350. *
  351. * @throws \InvalidArgumentException
  352. *
  353. * @return void
  354. */
  355. private function computeSingleEntityChangeSet($entity)
  356. {
  357. if ( $this->getEntityState($entity) !== self::STATE_MANAGED) {
  358. throw new \InvalidArgumentException("Entity has to be managed for single computation " . self::objToStr($entity));
  359. }
  360. $class = $this->em->getClassMetadata(get_class($entity));
  361. if ($class->isChangeTrackingDeferredImplicit()) {
  362. $this->persist($entity);
  363. }
  364. // Compute changes for INSERTed entities first. This must always happen even in this case.
  365. $this->computeScheduleInsertsChangeSets();
  366. if ($class->isReadOnly) {
  367. return;
  368. }
  369. // Ignore uninitialized proxy objects
  370. if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  371. return;
  372. }
  373. // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
  374. $oid = spl_object_hash($entity);
  375. if ( ! isset($this->entityInsertions[$oid]) && isset($this->entityStates[$oid])) {
  376. $this->computeChangeSet($class, $entity);
  377. }
  378. }
  379. /**
  380. * Executes any extra updates that have been scheduled.
  381. */
  382. private function executeExtraUpdates()
  383. {
  384. foreach ($this->extraUpdates as $oid => $update) {
  385. list ($entity, $changeset) = $update;
  386. $this->entityChangeSets[$oid] = $changeset;
  387. $this->getEntityPersister(get_class($entity))->update($entity);
  388. }
  389. }
  390. /**
  391. * Gets the changeset for an entity.
  392. *
  393. * @param object $entity
  394. *
  395. * @return array
  396. */
  397. public function getEntityChangeSet($entity)
  398. {
  399. $oid = spl_object_hash($entity);
  400. if (isset($this->entityChangeSets[$oid])) {
  401. return $this->entityChangeSets[$oid];
  402. }
  403. return array();
  404. }
  405. /**
  406. * Computes the changes that happened to a single entity.
  407. *
  408. * Modifies/populates the following properties:
  409. *
  410. * {@link _originalEntityData}
  411. * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
  412. * then it was not fetched from the database and therefore we have no original
  413. * entity data yet. All of the current entity data is stored as the original entity data.
  414. *
  415. * {@link _entityChangeSets}
  416. * The changes detected on all properties of the entity are stored there.
  417. * A change is a tuple array where the first entry is the old value and the second
  418. * entry is the new value of the property. Changesets are used by persisters
  419. * to INSERT/UPDATE the persistent entity state.
  420. *
  421. * {@link _entityUpdates}
  422. * If the entity is already fully MANAGED (has been fetched from the database before)
  423. * and any changes to its properties are detected, then a reference to the entity is stored
  424. * there to mark it for an update.
  425. *
  426. * {@link _collectionDeletions}
  427. * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
  428. * then this collection is marked for deletion.
  429. *
  430. * @ignore
  431. * @internal Don't call from the outside.
  432. * @param ClassMetadata $class The class descriptor of the entity.
  433. * @param object $entity The entity for which to compute the changes.
  434. */
  435. public function computeChangeSet(ClassMetadata $class, $entity)
  436. {
  437. $oid = spl_object_hash($entity);
  438. if (isset($this->readOnlyObjects[$oid])) {
  439. return;
  440. }
  441. if ( ! $class->isInheritanceTypeNone()) {
  442. $class = $this->em->getClassMetadata(get_class($entity));
  443. }
  444. // Fire PreFlush lifecycle callbacks
  445. if (isset($class->lifecycleCallbacks[Events::preFlush])) {
  446. $class->invokeLifecycleCallbacks(Events::preFlush, $entity);
  447. }
  448. $actualData = array();
  449. foreach ($class->reflFields as $name => $refProp) {
  450. $value = $refProp->getValue($entity);
  451. if ($class->isCollectionValuedAssociation($name) && $value !== null && ! ($value instanceof PersistentCollection)) {
  452. // If $value is not a Collection then use an ArrayCollection.
  453. if ( ! $value instanceof Collection) {
  454. $value = new ArrayCollection($value);
  455. }
  456. $assoc = $class->associationMappings[$name];
  457. // Inject PersistentCollection
  458. $value = new PersistentCollection(
  459. $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
  460. );
  461. $value->setOwner($entity, $assoc);
  462. $value->setDirty( ! $value->isEmpty());
  463. $class->reflFields[$name]->setValue($entity, $value);
  464. $actualData[$name] = $value;
  465. continue;
  466. }
  467. if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
  468. $actualData[$name] = $value;
  469. }
  470. }
  471. if ( ! isset($this->originalEntityData[$oid])) {
  472. // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
  473. // These result in an INSERT.
  474. $this->originalEntityData[$oid] = $actualData;
  475. $changeSet = array();
  476. foreach ($actualData as $propName => $actualValue) {
  477. if ( ! isset($class->associationMappings[$propName])) {
  478. $changeSet[$propName] = array(null, $actualValue);
  479. continue;
  480. }
  481. $assoc = $class->associationMappings[$propName];
  482. if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  483. $changeSet[$propName] = array(null, $actualValue);
  484. }
  485. }
  486. $this->entityChangeSets[$oid] = $changeSet;
  487. } else {
  488. // Entity is "fully" MANAGED: it was already fully persisted before
  489. // and we have a copy of the original data
  490. $originalData = $this->originalEntityData[$oid];
  491. $isChangeTrackingNotify = $class->isChangeTrackingNotify();
  492. $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
  493. ? $this->entityChangeSets[$oid]
  494. : array();
  495. foreach ($actualData as $propName => $actualValue) {
  496. // skip field, its a partially omitted one!
  497. if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
  498. continue;
  499. }
  500. $orgValue = $originalData[$propName];
  501. // skip if value havent changed
  502. if ($orgValue === $actualValue) {
  503. continue;
  504. }
  505. // if regular field
  506. if ( ! isset($class->associationMappings[$propName])) {
  507. if ($isChangeTrackingNotify) {
  508. continue;
  509. }
  510. $changeSet[$propName] = array($orgValue, $actualValue);
  511. continue;
  512. }
  513. $assoc = $class->associationMappings[$propName];
  514. // Persistent collection was exchanged with the "originally"
  515. // created one. This can only mean it was cloned and replaced
  516. // on another entity.
  517. if ($actualValue instanceof PersistentCollection) {
  518. $owner = $actualValue->getOwner();
  519. if ($owner === null) { // cloned
  520. $actualValue->setOwner($entity, $assoc);
  521. } else if ($owner !== $entity) { // no clone, we have to fix
  522. if (!$actualValue->isInitialized()) {
  523. $actualValue->initialize(); // we have to do this otherwise the cols share state
  524. }
  525. $newValue = clone $actualValue;
  526. $newValue->setOwner($entity, $assoc);
  527. $class->reflFields[$propName]->setValue($entity, $newValue);
  528. }
  529. }
  530. if ($orgValue instanceof PersistentCollection) {
  531. // A PersistentCollection was de-referenced, so delete it.
  532. $coid = spl_object_hash($orgValue);
  533. if (isset($this->collectionDeletions[$coid])) {
  534. continue;
  535. }
  536. $this->collectionDeletions[$coid] = $orgValue;
  537. $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
  538. continue;
  539. }
  540. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  541. if ($assoc['isOwningSide']) {
  542. $changeSet[$propName] = array($orgValue, $actualValue);
  543. }
  544. if ($orgValue !== null && $assoc['orphanRemoval']) {
  545. $this->scheduleOrphanRemoval($orgValue);
  546. }
  547. }
  548. }
  549. if ($changeSet) {
  550. $this->entityChangeSets[$oid] = $changeSet;
  551. $this->originalEntityData[$oid] = $actualData;
  552. $this->entityUpdates[$oid] = $entity;
  553. }
  554. }
  555. // Look for changes in associations of the entity
  556. foreach ($class->associationMappings as $field => $assoc) {
  557. if (($val = $class->reflFields[$field]->getValue($entity)) !== null) {
  558. $this->computeAssociationChanges($assoc, $val);
  559. if (!isset($this->entityChangeSets[$oid]) &&
  560. $assoc['isOwningSide'] &&
  561. $assoc['type'] == ClassMetadata::MANY_TO_MANY &&
  562. $val instanceof PersistentCollection &&
  563. $val->isDirty()) {
  564. $this->entityChangeSets[$oid] = array();
  565. $this->originalEntityData[$oid] = $actualData;
  566. $this->entityUpdates[$oid] = $entity;
  567. }
  568. }
  569. }
  570. }
  571. /**
  572. * Computes all the changes that have been done to entities and collections
  573. * since the last commit and stores these changes in the _entityChangeSet map
  574. * temporarily for access by the persisters, until the UoW commit is finished.
  575. */
  576. public function computeChangeSets()
  577. {
  578. // Compute changes for INSERTed entities first. This must always happen.
  579. $this->computeScheduleInsertsChangeSets();
  580. // Compute changes for other MANAGED entities. Change tracking policies take effect here.
  581. foreach ($this->identityMap as $className => $entities) {
  582. $class = $this->em->getClassMetadata($className);
  583. // Skip class if instances are read-only
  584. if ($class->isReadOnly) {
  585. continue;
  586. }
  587. // If change tracking is explicit or happens through notification, then only compute
  588. // changes on entities of that type that are explicitly marked for synchronization.
  589. switch (true) {
  590. case ($class->isChangeTrackingDeferredImplicit()):
  591. $entitiesToProcess = $entities;
  592. break;
  593. case (isset($this->scheduledForDirtyCheck[$className])):
  594. $entitiesToProcess = $this->scheduledForDirtyCheck[$className];
  595. break;
  596. default:
  597. $entitiesToProcess = array();
  598. }
  599. foreach ($entitiesToProcess as $entity) {
  600. // Ignore uninitialized proxy objects
  601. if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  602. continue;
  603. }
  604. // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
  605. $oid = spl_object_hash($entity);
  606. if ( ! isset($this->entityInsertions[$oid]) && isset($this->entityStates[$oid])) {
  607. $this->computeChangeSet($class, $entity);
  608. }
  609. }
  610. }
  611. }
  612. /**
  613. * Computes the changes of an association.
  614. *
  615. * @param array $assoc
  616. * @param mixed $value The value of the association.
  617. *
  618. * @throws ORMInvalidArgumentException
  619. * @throws ORMException
  620. *
  621. * @return void
  622. */
  623. private function computeAssociationChanges($assoc, $value)
  624. {
  625. if ($value instanceof Proxy && ! $value->__isInitialized__) {
  626. return;
  627. }
  628. if ($value instanceof PersistentCollection && $value->isDirty()) {
  629. $coid = spl_object_hash($value);
  630. if ($assoc['isOwningSide']) {
  631. $this->collectionUpdates[$coid] = $value;
  632. }
  633. $this->visitedCollections[$coid] = $value;
  634. }
  635. // Look through the entities, and in any of their associations,
  636. // for transient (new) entities, recursively. ("Persistence by reachability")
  637. // Unwrap. Uninitialized collections will simply be empty.
  638. $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? array($value) : $value->unwrap();
  639. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  640. foreach ($unwrappedValue as $key => $entry) {
  641. $state = $this->getEntityState($entry, self::STATE_NEW);
  642. if ( ! ($entry instanceof $assoc['targetEntity'])) {
  643. throw new ORMException(
  644. sprintf(
  645. 'Found entity of type %s on association %s#%s, but expecting %s',
  646. get_class($entry),
  647. $assoc['sourceEntity'],
  648. $assoc['fieldName'],
  649. $targetClass->name
  650. )
  651. );
  652. }
  653. switch ($state) {
  654. case self::STATE_NEW:
  655. if ( ! $assoc['isCascadePersist']) {
  656. throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry);
  657. }
  658. $this->persistNew($targetClass, $entry);
  659. $this->computeChangeSet($targetClass, $entry);
  660. break;
  661. case self::STATE_REMOVED:
  662. // Consume the $value as array (it's either an array or an ArrayAccess)
  663. // and remove the element from Collection.
  664. if ($assoc['type'] & ClassMetadata::TO_MANY) {
  665. unset($value[$key]);
  666. }
  667. break;
  668. case self::STATE_DETACHED:
  669. // Can actually not happen right now as we assume STATE_NEW,
  670. // so the exception will be raised from the DBAL layer (constraint violation).
  671. throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
  672. break;
  673. default:
  674. // MANAGED associated entities are already taken into account
  675. // during changeset calculation anyway, since they are in the identity map.
  676. }
  677. }
  678. }
  679. /**
  680. * @param ClassMetadata $class
  681. * @param object $entity
  682. */
  683. private function persistNew($class, $entity)
  684. {
  685. $oid = spl_object_hash($entity);
  686. if (isset($class->lifecycleCallbacks[Events::prePersist])) {
  687. $class->invokeLifecycleCallbacks(Events::prePersist, $entity);
  688. }
  689. if ($this->evm->hasListeners(Events::prePersist)) {
  690. $this->evm->dispatchEvent(Events::prePersist, new LifecycleEventArgs($entity, $this->em));
  691. }
  692. $idGen = $class->idGenerator;
  693. if ( ! $idGen->isPostInsertGenerator()) {
  694. $idValue = $idGen->generate($this->em, $entity);
  695. if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
  696. $idValue = array($class->identifier[0] => $idValue);
  697. $class->setIdentifierValues($entity, $idValue);
  698. }
  699. $this->entityIdentifiers[$oid] = $idValue;
  700. }
  701. $this->entityStates[$oid] = self::STATE_MANAGED;
  702. $this->scheduleForInsert($entity);
  703. }
  704. /**
  705. * INTERNAL:
  706. * Computes the changeset of an individual entity, independently of the
  707. * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
  708. *
  709. * The passed entity must be a managed entity. If the entity already has a change set
  710. * because this method is invoked during a commit cycle then the change sets are added.
  711. * whereby changes detected in this method prevail.
  712. *
  713. * @ignore
  714. * @param ClassMetadata $class The class descriptor of the entity.
  715. * @param object $entity The entity for which to (re)calculate the change set.
  716. *
  717. * @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
  718. */
  719. public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
  720. {
  721. $oid = spl_object_hash($entity);
  722. if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
  723. throw ORMInvalidArgumentException::entityNotManaged($entity);
  724. }
  725. // skip if change tracking is "NOTIFY"
  726. if ($class->isChangeTrackingNotify()) {
  727. return;
  728. }
  729. if ( ! $class->isInheritanceTypeNone()) {
  730. $class = $this->em->getClassMetadata(get_class($entity));
  731. }
  732. $actualData = array();
  733. foreach ($class->reflFields as $name => $refProp) {
  734. if ( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) {
  735. $actualData[$name] = $refProp->getValue($entity);
  736. }
  737. }
  738. $originalData = $this->originalEntityData[$oid];
  739. $changeSet = array();
  740. foreach ($actualData as $propName => $actualValue) {
  741. $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
  742. if (is_object($orgValue) && $orgValue !== $actualValue) {
  743. $changeSet[$propName] = array($orgValue, $actualValue);
  744. } else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
  745. $changeSet[$propName] = array($orgValue, $actualValue);
  746. }
  747. }
  748. if ($changeSet) {
  749. if (isset($this->entityChangeSets[$oid])) {
  750. $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
  751. }
  752. $this->originalEntityData[$oid] = $actualData;
  753. }
  754. }
  755. /**
  756. * Executes all entity insertions for entities of the specified type.
  757. *
  758. * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  759. */
  760. private function executeInserts($class)
  761. {
  762. $className = $class->name;
  763. $persister = $this->getEntityPersister($className);
  764. $entities = array();
  765. $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postPersist]);
  766. $hasListeners = $this->evm->hasListeners(Events::postPersist);
  767. foreach ($this->entityInsertions as $oid => $entity) {
  768. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  769. continue;
  770. }
  771. $persister->addInsert($entity);
  772. unset($this->entityInsertions[$oid]);
  773. if ($hasLifecycleCallbacks || $hasListeners) {
  774. $entities[] = $entity;
  775. }
  776. }
  777. $postInsertIds = $persister->executeInserts();
  778. if ($postInsertIds) {
  779. // Persister returned post-insert IDs
  780. foreach ($postInsertIds as $id => $entity) {
  781. $oid = spl_object_hash($entity);
  782. $idField = $class->identifier[0];
  783. $class->reflFields[$idField]->setValue($entity, $id);
  784. $this->entityIdentifiers[$oid] = array($idField => $id);
  785. $this->entityStates[$oid] = self::STATE_MANAGED;
  786. $this->originalEntityData[$oid][$idField] = $id;
  787. $this->addToIdentityMap($entity);
  788. }
  789. }
  790. foreach ($entities as $entity) {
  791. if ($hasLifecycleCallbacks) {
  792. $class->invokeLifecycleCallbacks(Events::postPersist, $entity);
  793. }
  794. if ($hasListeners) {
  795. $this->evm->dispatchEvent(Events::postPersist, new LifecycleEventArgs($entity, $this->em));
  796. }
  797. }
  798. }
  799. /**
  800. * Executes all entity updates for entities of the specified type.
  801. *
  802. * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  803. */
  804. private function executeUpdates($class)
  805. {
  806. $className = $class->name;
  807. $persister = $this->getEntityPersister($className);
  808. $hasPreUpdateLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::preUpdate]);
  809. $hasPreUpdateListeners = $this->evm->hasListeners(Events::preUpdate);
  810. $hasPostUpdateLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postUpdate]);
  811. $hasPostUpdateListeners = $this->evm->hasListeners(Events::postUpdate);
  812. foreach ($this->entityUpdates as $oid => $entity) {
  813. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  814. continue;
  815. }
  816. if ($hasPreUpdateLifecycleCallbacks) {
  817. $class->invokeLifecycleCallbacks(Events::preUpdate, $entity);
  818. $this->recomputeSingleEntityChangeSet($class, $entity);
  819. }
  820. if ($hasPreUpdateListeners) {
  821. $this->evm->dispatchEvent(
  822. Events::preUpdate,
  823. new Event\PreUpdateEventArgs($entity, $this->em, $this->entityChangeSets[$oid])
  824. );
  825. }
  826. if (!empty($this->entityChangeSets[$oid])) {
  827. $persister->update($entity);
  828. }
  829. unset($this->entityUpdates[$oid]);
  830. if ($hasPostUpdateLifecycleCallbacks) {
  831. $class->invokeLifecycleCallbacks(Events::postUpdate, $entity);
  832. }
  833. if ($hasPostUpdateListeners) {
  834. $this->evm->dispatchEvent(Events::postUpdate, new LifecycleEventArgs($entity, $this->em));
  835. }
  836. }
  837. }
  838. /**
  839. * Executes all entity deletions for entities of the specified type.
  840. *
  841. * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  842. */
  843. private function executeDeletions($class)
  844. {
  845. $className = $class->name;
  846. $persister = $this->getEntityPersister($className);
  847. $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postRemove]);
  848. $hasListeners = $this->evm->hasListeners(Events::postRemove);
  849. foreach ($this->entityDeletions as $oid => $entity) {
  850. if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
  851. continue;
  852. }
  853. $persister->delete($entity);
  854. unset(
  855. $this->entityDeletions[$oid],
  856. $this->entityIdentifiers[$oid],
  857. $this->originalEntityData[$oid],
  858. $this->entityStates[$oid]
  859. );
  860. // Entity with this $oid after deletion treated as NEW, even if the $oid
  861. // is obtained by a new entity because the old one went out of scope.
  862. //$this->entityStates[$oid] = self::STATE_NEW;
  863. if ( ! $class->isIdentifierNatural()) {
  864. $class->reflFields[$class->identifier[0]]->setValue($entity, null);
  865. }
  866. if ($hasLifecycleCallbacks) {
  867. $class->invokeLifecycleCallbacks(Events::postRemove, $entity);
  868. }
  869. if ($hasListeners) {
  870. $this->evm->dispatchEvent(Events::postRemove, new LifecycleEventArgs($entity, $this->em));
  871. }
  872. }
  873. }
  874. /**
  875. * Gets the commit order.
  876. *
  877. * @param array $entityChangeSet
  878. *
  879. * @return array
  880. */
  881. private function getCommitOrder(array $entityChangeSet = null)
  882. {
  883. if ($entityChangeSet === null) {
  884. $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
  885. }
  886. $calc = $this->getCommitOrderCalculator();
  887. // See if there are any new classes in the changeset, that are not in the
  888. // commit order graph yet (dont have a node).
  889. // We have to inspect changeSet to be able to correctly build dependencies.
  890. // It is not possible to use IdentityMap here because post inserted ids
  891. // are not yet available.
  892. $newNodes = array();
  893. foreach ($entityChangeSet as $entity) {
  894. $className = $this->em->getClassMetadata(get_class($entity))->name;
  895. if ($calc->hasClass($className)) {
  896. continue;
  897. }
  898. $class = $this->em->getClassMetadata($className);
  899. $calc->addClass($class);
  900. $newNodes[] = $class;
  901. }
  902. // Calculate dependencies for new nodes
  903. while ($class = array_pop($newNodes)) {
  904. foreach ($class->associationMappings as $assoc) {
  905. if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  906. continue;
  907. }
  908. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  909. if ( ! $calc->hasClass($targetClass->name)) {
  910. $calc->addClass($targetClass);
  911. $newNodes[] = $targetClass;
  912. }
  913. $calc->addDependency($targetClass, $class);
  914. // If the target class has mapped subclasses, these share the same dependency.
  915. if ( ! $targetClass->subClasses) {
  916. continue;
  917. }
  918. foreach ($targetClass->subClasses as $subClassName) {
  919. $targetSubClass = $this->em->getClassMetadata($subClassName);
  920. if ( ! $calc->hasClass($subClassName)) {
  921. $calc->addClass($targetSubClass);
  922. $newNodes[] = $targetSubClass;
  923. }
  924. $calc->addDependency($targetSubClass, $class);
  925. }
  926. }
  927. }
  928. return $calc->getCommitOrder();
  929. }
  930. /**
  931. * Schedules an entity for insertion into the database.
  932. * If the entity already has an identifier, it will be added to the identity map.
  933. *
  934. * @param object $entity The entity to schedule for insertion.
  935. *
  936. * @throws ORMInvalidArgumentException
  937. * @throws \InvalidArgumentException
  938. */
  939. public function scheduleForInsert($entity)
  940. {
  941. $oid = spl_object_hash($entity);
  942. if (isset($this->entityUpdates[$oid])) {
  943. throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
  944. }
  945. if (isset($this->entityDeletions[$oid])) {
  946. throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
  947. }
  948. if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
  949. throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
  950. }
  951. if (isset($this->entityInsertions[$oid])) {
  952. throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
  953. }
  954. $this->entityInsertions[$oid] = $entity;
  955. if (isset($this->entityIdentifiers[$oid])) {
  956. $this->addToIdentityMap($entity);
  957. }
  958. if ($entity instanceof NotifyPropertyChanged) {
  959. $entity->addPropertyChangedListener($this);
  960. }
  961. }
  962. /**
  963. * Checks whether an entity is scheduled for insertion.
  964. *
  965. * @param object $entity
  966. *
  967. * @return boolean
  968. */
  969. public function isScheduledForInsert($entity)
  970. {
  971. return isset($this->entityInsertions[spl_object_hash($entity)]);
  972. }
  973. /**
  974. * Schedules an entity for being updated.
  975. *
  976. * @param object $entity The entity to schedule for being updated.
  977. *
  978. * @throws ORMInvalidArgumentException
  979. */
  980. public function scheduleForUpdate($entity)
  981. {
  982. $oid = spl_object_hash($entity);
  983. if ( ! isset($this->entityIdentifiers[$oid])) {
  984. throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update");
  985. }
  986. if (isset($this->entityDeletions[$oid])) {
  987. throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update");
  988. }
  989. if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
  990. $this->entityUpdates[$oid] = $entity;
  991. }
  992. }
  993. /**
  994. * INTERNAL:
  995. * Schedules an extra update that will be executed immediately after the
  996. * regular entity updates within the currently running commit cycle.
  997. *
  998. * Extra updates for entities are stored as (entity, changeset) tuples.
  999. *
  1000. * @ignore
  1001. * @param object $entity The entity for which to schedule an extra update.
  1002. * @param array $changeset The changeset of the entity (what to update).
  1003. */
  1004. public function scheduleExtraUpdate($entity, array $changeset)
  1005. {
  1006. $oid = spl_object_hash($entity);
  1007. $extraUpdate = array($entity, $changeset);
  1008. if (isset($this->extraUpdates[$oid])) {
  1009. list($ignored, $changeset2) = $this->extraUpdates[$oid];
  1010. $extraUpdate = array($entity, $changeset + $changeset2);
  1011. }
  1012. $this->extraUpdates[$oid] = $extraUpdate;
  1013. }
  1014. /**
  1015. * Checks whether an entity is registered as dirty in the unit of work.
  1016. * Note: Is not very useful currently as dirty entities are only registered
  1017. * at commit time.
  1018. *
  1019. * @param object $entity
  1020. *
  1021. * @return boolean
  1022. */
  1023. public function isScheduledForUpdate($entity)
  1024. {
  1025. return isset($this->entityUpdates[spl_object_hash($entity)]);
  1026. }
  1027. /**
  1028. * Checks whether an entity is registered to be checked in the unit of work.
  1029. *
  1030. * @param object $entity
  1031. *
  1032. * @return boolean
  1033. */
  1034. public function isScheduledForDirtyCheck($entity)
  1035. {
  1036. $rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  1037. return isset($this->scheduledForDirtyCheck[$rootEntityName][spl_object_hash($entity)]);
  1038. }
  1039. /**
  1040. * INTERNAL:
  1041. * Schedules an entity for deletion.
  1042. *
  1043. * @param object $entity
  1044. */
  1045. public function scheduleForDelete($entity)
  1046. {
  1047. $oid = spl_object_hash($entity);
  1048. if (isset($this->entityInsertions[$oid])) {
  1049. if ($this->isInIdentityMap($entity)) {
  1050. $this->removeFromIdentityMap($entity);
  1051. }
  1052. unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
  1053. return; // entity has not been persisted yet, so nothing more to do.
  1054. }
  1055. if ( ! $this->isInIdentityMap($entity)) {
  1056. return;
  1057. }
  1058. $this->removeFromIdentityMap($entity);
  1059. if (isset($this->entityUpdates[$oid])) {
  1060. unset($this->entityUpdates[$oid]);
  1061. }
  1062. if ( ! isset($this->entityDeletions[$oid])) {
  1063. $this->entityDeletions[$oid] = $entity;
  1064. $this->entityStates[$oid] = self::STATE_REMOVED;
  1065. }
  1066. }
  1067. /**
  1068. * Checks whether an entity is registered as removed/deleted with the unit
  1069. * of work.
  1070. *
  1071. * @param object $entity
  1072. *
  1073. * @return boolean
  1074. */
  1075. public function isScheduledForDelete($entity)
  1076. {
  1077. return isset($this->entityDeletions[spl_object_hash($entity)]);
  1078. }
  1079. /**
  1080. * Checks whether an entity is scheduled for insertion, update or deletion.
  1081. *
  1082. * @param $entity
  1083. *
  1084. * @return boolean
  1085. */
  1086. public function isEntityScheduled($entity)
  1087. {
  1088. $oid = spl_object_hash($entity);
  1089. return isset($this->entityInsertions[$oid])
  1090. || isset($this->entityUpdates[$oid])
  1091. || isset($this->entityDeletions[$oid]);
  1092. }
  1093. /**
  1094. * INTERNAL:
  1095. * Registers an entity in the identity map.
  1096. * Note that entities in a hierarchy are registered with the class name of
  1097. * the root entity.
  1098. *
  1099. * @ignore
  1100. * @param object $entity The entity to register.
  1101. *
  1102. * @throws ORMInvalidArgumentException
  1103. *
  1104. * @return boolean TRUE if the registration was successful, FALSE if the identity of
  1105. * the entity in question is already managed.
  1106. */
  1107. public function addToIdentityMap($entity)
  1108. {
  1109. $classMetadata = $this->em->getClassMetadata(get_class($entity));
  1110. $idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
  1111. if ($idHash === '') {
  1112. throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity);
  1113. }
  1114. $className = $classMetadata->rootEntityName;
  1115. if (isset($this->identityMap[$className][$idHash])) {
  1116. return false;
  1117. }
  1118. $this->identityMap[$className][$idHash] = $entity;
  1119. return true;
  1120. }
  1121. /**
  1122. * Gets the state of an entity with regard to the current unit of work.
  1123. *
  1124. * @param object $entity
  1125. * @param integer $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
  1126. * This parameter can be set to improve performance of entity state detection
  1127. * by potentially avoiding a database lookup if the distinction between NEW and DETACHED
  1128. * is either known or does not matter for the caller of the method.
  1129. *
  1130. * @return int The entity state.
  1131. */
  1132. public function getEntityState($entity, $assume = null)
  1133. {
  1134. $oid = spl_object_hash($entity);
  1135. if (isset($this->entityStates[$oid])) {
  1136. return $this->entityStates[$oid];
  1137. }
  1138. if ($assume !== null) {
  1139. return $assume;
  1140. }
  1141. // State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
  1142. // Note that you can not remember the NEW or DETACHED state in _entityStates since
  1143. // the UoW does not hold references to such objects and the object hash can be reused.
  1144. // More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
  1145. $class = $this->em->getClassMetadata(get_class($entity));
  1146. $id = $class->getIdentifierValues($entity);
  1147. if ( ! $id) {
  1148. return self::STATE_NEW;
  1149. }
  1150. switch (true) {
  1151. case ($class->isIdentifierNatural());
  1152. // Check for a version field, if available, to avoid a db lookup.
  1153. if ($class->isVersioned) {
  1154. return ($class->getFieldValue($entity, $class->versionField))
  1155. ? self::STATE_DETACHED
  1156. : self::STATE_NEW;
  1157. }
  1158. // Last try before db lookup: check the identity map.
  1159. if ($this->tryGetById($id, $class->rootEntityName)) {
  1160. return self::STATE_DETACHED;
  1161. }
  1162. // db lookup
  1163. if ($this->getEntityPersister($class->name)->exists($entity)) {
  1164. return self::STATE_DETACHED;
  1165. }
  1166. return self::STATE_NEW;
  1167. case ( ! $class->idGenerator->isPostInsertGenerator()):
  1168. // if we have a pre insert generator we can't be sure that having an id
  1169. // really means that the entity exists. We have to verify this through
  1170. // the last resort: a db lookup
  1171. // Last try before db lookup: check the identity map.
  1172. if ($this->tryGetById($id, $class->rootEntityName)) {
  1173. return self::STATE_DETACHED;
  1174. }
  1175. // db lookup
  1176. if ($this->getEntityPersister($class->name)->exists($entity)) {
  1177. return self::STATE_DETACHED;
  1178. }
  1179. return self::STATE_NEW;
  1180. default:
  1181. return self::STATE_DETACHED;
  1182. }
  1183. }
  1184. /**
  1185. * INTERNAL:
  1186. * Removes an entity from the identity map. This effectively detaches the
  1187. * entity from the persistence management of Doctrine.
  1188. *
  1189. * @ignore
  1190. * @param object $entity
  1191. *
  1192. * @throws ORMInvalidArgumentException
  1193. *
  1194. * @return boolean
  1195. */
  1196. public function removeFromIdentityMap($entity)
  1197. {
  1198. $oid = spl_object_hash($entity);
  1199. $classMetadata = $this->em->getClassMetadata(get_class($entity));
  1200. $idHash = implode(' ', $this->entityIdentifiers[$oid]);
  1201. if ($idHash === '') {
  1202. throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map");
  1203. }
  1204. $className = $classMetadata->rootEntityName;
  1205. if (isset($this->identityMap[$className][$idHash])) {
  1206. unset($this->identityMap[$className][$idHash]);
  1207. unset($this->readOnlyObjects[$oid]);
  1208. //$this->entityStates[$oid] = self::STATE_DETACHED;
  1209. return true;
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * INTERNAL:
  1215. * Gets an entity in the identity map by its identifier hash.
  1216. *
  1217. * @ignore
  1218. * @param string $idHash
  1219. * @param string $rootClassName
  1220. *
  1221. * @return object
  1222. */
  1223. public function getByIdHash($idHash, $rootClassName)
  1224. {
  1225. return $this->identityMap[$rootClassName][$idHash];
  1226. }
  1227. /**
  1228. * INTERNAL:
  1229. * Tries to get an entity by its identifier hash. If no entity is found for
  1230. * the given hash, FALSE is returned.
  1231. *
  1232. * @ignore
  1233. * @param string $idHash
  1234. * @param string $rootClassName
  1235. *
  1236. * @return mixed The found entity or FALSE.
  1237. */
  1238. public function tryGetByIdHash($idHash, $rootClassName)
  1239. {
  1240. if (isset($this->identityMap[$rootClassName][$idHash])) {
  1241. return $this->identityMap[$rootClassName][$idHash];
  1242. }
  1243. return false;
  1244. }
  1245. /**
  1246. * Checks whether an entity is registered in the identity map of this UnitOfWork.
  1247. *
  1248. * @param object $entity
  1249. *
  1250. * @return boolean
  1251. */
  1252. public function isInIdentityMap($entity)
  1253. {
  1254. $oid = spl_object_hash($entity);
  1255. if ( ! isset($this->entityIdentifiers[$oid])) {
  1256. return false;
  1257. }
  1258. $classMetadata = $this->em->getClassMetadata(get_class($entity));
  1259. $idHash = implode(' ', $this->entityIdentifiers[$oid]);
  1260. if ($idHash === '') {
  1261. return false;
  1262. }
  1263. return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
  1264. }
  1265. /**
  1266. * INTERNAL:
  1267. * Checks whether an identifier hash exists in the identity map.
  1268. *
  1269. * @ignore
  1270. * @param string $idHash
  1271. * @param string $rootClassName
  1272. *
  1273. * @return boolean
  1274. */
  1275. public function containsIdHash($idHash, $rootClassName)
  1276. {
  1277. return isset($this->identityMap[$rootClassName][$idHash]);
  1278. }
  1279. /**
  1280. * Persists an entity as part of the current unit of work.
  1281. *
  1282. * @param object $entity The entity to persist.
  1283. */
  1284. public function persist($entity)
  1285. {
  1286. $visited = array();
  1287. $this->doPersist($entity, $visited);
  1288. }
  1289. /**
  1290. * Persists an entity as part of the current unit of work.
  1291. *
  1292. * This method is internally called during persist() cascades as it tracks
  1293. * the already visited entities to prevent infinite recursions.
  1294. *
  1295. * @param object $entity The entity to persist.
  1296. * @param array $visited The already visited entities.
  1297. *
  1298. * @throws ORMInvalidArgumentException
  1299. * @throws UnexpectedValueException
  1300. */
  1301. private function doPersist($entity, array &$visited)
  1302. {
  1303. $oid = spl_object_hash($entity);
  1304. if (isset($visited[$oid])) {
  1305. return; // Prevent infinite recursion
  1306. }
  1307. $visited[$oid] = $entity; // Mark visited
  1308. $class = $this->em->getClassMetadata(get_class($entity));
  1309. // We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
  1310. // If we would detect DETACHED here we would throw an exception anyway with the same
  1311. // consequences (not recoverable/programming error), so just assuming NEW here
  1312. // lets us avoid some database lookups for entities with natural identifiers.
  1313. $entityState = $this->getEntityState($entity, self::STATE_NEW);
  1314. switch ($entityState) {
  1315. case self::STATE_MANAGED:
  1316. // Nothing to do, except if policy is "deferred explicit"
  1317. if ($class->isChangeTrackingDeferredExplicit()) {
  1318. $this->scheduleForDirtyCheck($entity);
  1319. }
  1320. break;
  1321. case self::STATE_NEW:
  1322. $this->persistNew($class, $entity);
  1323. break;
  1324. case self::STATE_REMOVED:
  1325. // Entity becomes managed again
  1326. unset($this->entityDeletions[$oid]);
  1327. $this->entityStates[$oid] = self::STATE_MANAGED;
  1328. break;
  1329. case self::STATE_DETACHED:
  1330. // Can actually not happen right now since we assume STATE_NEW.
  1331. throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted");
  1332. default:
  1333. throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
  1334. }
  1335. $this->cascadePersist($entity, $visited);
  1336. }
  1337. /**
  1338. * Deletes an entity as part of the current unit of work.
  1339. *
  1340. * @param object $entity The entity to remove.
  1341. */
  1342. public function remove($entity)
  1343. {
  1344. $visited = array();
  1345. $this->doRemove($entity, $visited);
  1346. }
  1347. /**
  1348. * Deletes an entity as part of the current unit of work.
  1349. *
  1350. * This method is internally called during delete() cascades as it tracks
  1351. * the already visited entities to prevent infinite recursions.
  1352. *
  1353. * @param object $entity The entity to delete.
  1354. * @param array $visited The map of the already visited entities.
  1355. *
  1356. * @throws ORMInvalidArgumentException If the instance is a detached entity.
  1357. * @throws UnexpectedValueException
  1358. */
  1359. private function doRemove($entity, array &$visited)
  1360. {
  1361. $oid = spl_object_hash($entity);
  1362. if (isset($visited[$oid])) {
  1363. return; // Prevent infinite recursion
  1364. }
  1365. $visited[$oid] = $entity; // mark visited
  1366. // Cascade first, because scheduleForDelete() removes the entity from the identity map, which
  1367. // can cause problems when a lazy proxy has to be initialized for the cascade operation.
  1368. $this->cascadeRemove($entity, $visited);
  1369. $class = $this->em->getClassMetadata(get_class($entity));
  1370. $entityState = $this->getEntityState($entity);
  1371. switch ($entityState) {
  1372. case self::STATE_NEW:
  1373. case self::STATE_REMOVED:
  1374. // nothing to do
  1375. break;
  1376. case self::STATE_MANAGED:
  1377. if (isset($class->lifecycleCallbacks[Events::preRemove])) {
  1378. $class->invokeLifecycleCallbacks(Events::preRemove, $entity);
  1379. }
  1380. if ($this->evm->hasListeners(Events::preRemove)) {
  1381. $this->evm->dispatchEvent(Events::preRemove, new LifecycleEventArgs($entity, $this->em));
  1382. }
  1383. $this->scheduleForDelete($entity);
  1384. break;
  1385. case self::STATE_DETACHED:
  1386. throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed");
  1387. default:
  1388. throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
  1389. }
  1390. }
  1391. /**
  1392. * Merges the state of the given detached entity into this UnitOfWork.
  1393. *
  1394. * @param object $entity
  1395. *
  1396. * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1397. * attribute and the version check against the managed copy fails.
  1398. *
  1399. * @return object The managed copy of the entity.
  1400. *
  1401. * @todo Require active transaction!? OptimisticLockException may result in undefined state!?
  1402. */
  1403. public function merge($entity)
  1404. {
  1405. $visited = array();
  1406. return $this->doMerge($entity, $visited);
  1407. }
  1408. /**
  1409. * Executes a merge operation on an entity.
  1410. *
  1411. * @param object $entity
  1412. * @param array $visited
  1413. * @param object $prevManagedCopy
  1414. * @param array $assoc
  1415. *
  1416. * @throws OptimisticLockException If the entity uses optimistic locking through a version
  1417. * attribute and the version check against the managed copy fails.
  1418. * @throws ORMInvalidArgumentException If the entity instance is NEW.
  1419. * @throws EntityNotFoundException
  1420. *
  1421. * @return object The managed copy of the entity.
  1422. */
  1423. private function doMerge($entity, array &$visited, $prevManagedCopy = null, $assoc = null)
  1424. {
  1425. $oid = spl_object_hash($entity);
  1426. if (isset($visited[$oid])) {
  1427. return $visited[$oid]; // Prevent infinite recursion
  1428. }
  1429. $visited[$oid] = $entity; // mark visited
  1430. $class = $this->em->getClassMetadata(get_class($entity));
  1431. // First we assume DETACHED, although it can still be NEW but we can avoid
  1432. // an extra db-roundtrip this way. If it is not MANAGED but has an identity,
  1433. // we need to fetch it from the db anyway in order to merge.
  1434. // MANAGED entities are ignored by the merge operation.
  1435. $managedCopy = $entity;
  1436. if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
  1437. if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  1438. $entity->__load();
  1439. }
  1440. // Try to look the entity up in the identity map.
  1441. $id = $class->getIdentifierValues($entity);
  1442. // If there is no ID, it is actually NEW.
  1443. if ( ! $id) {
  1444. $managedCopy = $this->newInstance($class);
  1445. $this->persistNew($class, $managedCopy);
  1446. } else {
  1447. $flatId = $id;
  1448. if ($class->containsForeignIdentifier) {
  1449. // convert foreign identifiers into scalar foreign key
  1450. // values to avoid object to string conversion failures.
  1451. foreach ($id as $idField => $idValue) {
  1452. if (isset($class->associationMappings[$idField])) {
  1453. $targetClassMetadata = $this->em->getClassMetadata($class->associationMappings[$idField]['targetEntity']);
  1454. $associatedId = $this->getEntityIdentifier($idValue);
  1455. $flatId[$idField] = $associatedId[$targetClassMetadata->identifier[0]];
  1456. }
  1457. }
  1458. }
  1459. $managedCopy = $this->tryGetById($flatId, $class->rootEntityName);
  1460. if ($managedCopy) {
  1461. // We have the entity in-memory already, just make sure its not removed.
  1462. if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
  1463. throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge");
  1464. }
  1465. } else {
  1466. // We need to fetch the managed copy in order to merge.
  1467. $managedCopy = $this->em->find($class->name, $flatId);
  1468. }
  1469. if ($managedCopy === null) {
  1470. // If the identifier is ASSIGNED, it is NEW, otherwise an error
  1471. // since the managed entity was not found.
  1472. if ( ! $class->isIdentifierNatural()) {
  1473. throw new EntityNotFoundException;
  1474. }
  1475. $managedCopy = $this->newInstance($class);
  1476. $class->setIdentifierValues($managedCopy, $id);
  1477. $this->persistNew($class, $managedCopy);
  1478. } else {
  1479. if ($managedCopy instanceof Proxy && ! $managedCopy->__isInitialized__) {
  1480. $managedCopy->__load();
  1481. }
  1482. }
  1483. }
  1484. if ($class->isVersioned) {
  1485. $managedCopyVersion = $class->reflFields[$class->versionField]->getValue($managedCopy);
  1486. $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
  1487. // Throw exception if versions dont match.
  1488. if ($managedCopyVersion != $entityVersion) {
  1489. throw OptimisticLockException::lockFailedVersionMissmatch($entity, $entityVersion, $managedCopyVersion);
  1490. }
  1491. }
  1492. // Merge state of $entity into existing (managed) entity
  1493. foreach ($class->reflClass->getProperties() as $prop) {
  1494. $name = $prop->name;
  1495. $prop->setAccessible(true);
  1496. if ( ! isset($class->associationMappings[$name])) {
  1497. if ( ! $class->isIdentifier($name)) {
  1498. $prop->setValue($managedCopy, $prop->getValue($entity));
  1499. }
  1500. } else {
  1501. $assoc2 = $class->associationMappings[$name];
  1502. if ($assoc2['type'] & ClassMetadata::TO_ONE) {
  1503. $other = $prop->getValue($entity);
  1504. if ($other === null) {
  1505. $prop->setValue($managedCopy, null);
  1506. } else if ($other instanceof Proxy && !$other->__isInitialized__) {
  1507. // do not merge fields marked lazy that have not been fetched.
  1508. continue;
  1509. } else if ( ! $assoc2['isCascadeMerge']) {
  1510. if ($this->getEntityState($other, self::STATE_DETACHED) !== self::STATE_MANAGED) {
  1511. $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
  1512. $relatedId = $targetClass->getIdentifierValues($other);
  1513. if ($targetClass->subClasses) {
  1514. $other = $this->em->find($targetClass->name, $relatedId);
  1515. } else {
  1516. $other = $this->em->getProxyFactory()->getProxy($assoc2['targetEntity'], $relatedId);
  1517. $this->registerManaged($other, $relatedId, array());
  1518. }
  1519. }
  1520. $prop->setValue($managedCopy, $other);
  1521. }
  1522. } else {
  1523. $mergeCol = $prop->getValue($entity);
  1524. if ($mergeCol instanceof PersistentCollection && !$mergeCol->isInitialized()) {
  1525. // do not merge fields marked lazy that have not been fetched.
  1526. // keep the lazy persistent collection of the managed copy.
  1527. continue;
  1528. }
  1529. $managedCol = $prop->getValue($managedCopy);
  1530. if (!$managedCol) {
  1531. $managedCol = new PersistentCollection($this->em,
  1532. $this->em->getClassMetadata($assoc2['targetEntity']),
  1533. new ArrayCollection
  1534. );
  1535. $managedCol->setOwner($managedCopy, $assoc2);
  1536. $prop->setValue($managedCopy, $managedCol);
  1537. $this->originalEntityData[$oid][$name] = $managedCol;
  1538. }
  1539. if ($assoc2['isCascadeMerge']) {
  1540. $managedCol->initialize();
  1541. // clear and set dirty a managed collection if its not also the same collection to merge from.
  1542. if (!$managedCol->isEmpty() && $managedCol !== $mergeCol) {
  1543. $managedCol->unwrap()->clear();
  1544. $managedCol->setDirty(true);
  1545. if ($assoc2['isOwningSide'] && $assoc2['type'] == ClassMetadata::MANY_TO_MANY && $class->isChangeTrackingNotify()) {
  1546. $this->scheduleForDirtyCheck($managedCopy);
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. if ($class->isChangeTrackingNotify()) {
  1553. // Just treat all properties as changed, there is no other choice.
  1554. $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
  1555. }
  1556. }
  1557. if ($class->isChangeTrackingDeferredExplicit()) {
  1558. $this->scheduleForDirtyCheck($entity);
  1559. }
  1560. }
  1561. if ($prevManagedCopy !== null) {
  1562. $assocField = $assoc['fieldName'];
  1563. $prevClass = $this->em->getClassMetadata(get_class($prevManagedCopy));
  1564. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  1565. $prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
  1566. } else {
  1567. $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);
  1568. if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
  1569. $class->reflFields[$assoc['mappedBy']]->setValue($managedCopy, $prevManagedCopy);
  1570. }
  1571. }
  1572. }
  1573. // Mark the managed copy visited as well
  1574. $visited[spl_object_hash($managedCopy)] = true;
  1575. $this->cascadeMerge($entity, $managedCopy, $visited);
  1576. return $managedCopy;
  1577. }
  1578. /**
  1579. * Detaches an entity from the persistence management. It's persistence will
  1580. * no longer be managed by Doctrine.
  1581. *
  1582. * @param object $entity The entity to detach.
  1583. */
  1584. public function detach($entity)
  1585. {
  1586. $visited = array();
  1587. $this->doDetach($entity, $visited);
  1588. }
  1589. /**
  1590. * Executes a detach operation on the given entity.
  1591. *
  1592. * @param object $entity
  1593. * @param array $visited
  1594. * @param boolean $noCascade if true, don't cascade detach operation
  1595. */
  1596. private function doDetach($entity, array &$visited, $noCascade = false)
  1597. {
  1598. $oid = spl_object_hash($entity);
  1599. if (isset($visited[$oid])) {
  1600. return; // Prevent infinite recursion
  1601. }
  1602. $visited[$oid] = $entity; // mark visited
  1603. switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
  1604. case self::STATE_MANAGED:
  1605. if ($this->isInIdentityMap($entity)) {
  1606. $this->removeFromIdentityMap($entity);
  1607. }
  1608. unset(
  1609. $this->entityInsertions[$oid],
  1610. $this->entityUpdates[$oid],
  1611. $this->entityDeletions[$oid],
  1612. $this->entityIdentifiers[$oid],
  1613. $this->entityStates[$oid],
  1614. $this->originalEntityData[$oid]
  1615. );
  1616. break;
  1617. case self::STATE_NEW:
  1618. case self::STATE_DETACHED:
  1619. return;
  1620. }
  1621. if ( ! $noCascade) {
  1622. $this->cascadeDetach($entity, $visited);
  1623. }
  1624. }
  1625. /**
  1626. * Refreshes the state of the given entity from the database, overwriting
  1627. * any local, unpersisted changes.
  1628. *
  1629. * @param object $entity The entity to refresh.
  1630. *
  1631. * @throws InvalidArgumentException If the entity is not MANAGED.
  1632. */
  1633. public function refresh($entity)
  1634. {
  1635. $visited = array();
  1636. $this->doRefresh($entity, $visited);
  1637. }
  1638. /**
  1639. * Executes a refresh operation on an entity.
  1640. *
  1641. * @param object $entity The entity to refresh.
  1642. * @param array $visited The already visited entities during cascades.
  1643. *
  1644. * @throws ORMInvalidArgumentException If the entity is not MANAGED.
  1645. */
  1646. private function doRefresh($entity, array &$visited)
  1647. {
  1648. $oid = spl_object_hash($entity);
  1649. if (isset($visited[$oid])) {
  1650. return; // Prevent infinite recursion
  1651. }
  1652. $visited[$oid] = $entity; // mark visited
  1653. $class = $this->em->getClassMetadata(get_class($entity));
  1654. if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
  1655. throw ORMInvalidArgumentException::entityNotManaged($entity);
  1656. }
  1657. $this->getEntityPersister($class->name)->refresh(
  1658. array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1659. $entity
  1660. );
  1661. $this->cascadeRefresh($entity, $visited);
  1662. }
  1663. /**
  1664. * Cascades a refresh operation to associated entities.
  1665. *
  1666. * @param object $entity
  1667. * @param array $visited
  1668. */
  1669. private function cascadeRefresh($entity, array &$visited)
  1670. {
  1671. $class = $this->em->getClassMetadata(get_class($entity));
  1672. $associationMappings = array_filter(
  1673. $class->associationMappings,
  1674. function ($assoc) { return $assoc['isCascadeRefresh']; }
  1675. );
  1676. foreach ($associationMappings as $assoc) {
  1677. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1678. switch (true) {
  1679. case ($relatedEntities instanceof PersistentCollection):
  1680. // Unwrap so that foreach() does not initialize
  1681. $relatedEntities = $relatedEntities->unwrap();
  1682. // break; is commented intentionally!
  1683. case ($relatedEntities instanceof Collection):
  1684. case (is_array($relatedEntities)):
  1685. foreach ($relatedEntities as $relatedEntity) {
  1686. $this->doRefresh($relatedEntity, $visited);
  1687. }
  1688. break;
  1689. case ($relatedEntities !== null):
  1690. $this->doRefresh($relatedEntities, $visited);
  1691. break;
  1692. default:
  1693. // Do nothing
  1694. }
  1695. }
  1696. }
  1697. /**
  1698. * Cascades a detach operation to associated entities.
  1699. *
  1700. * @param object $entity
  1701. * @param array $visited
  1702. */
  1703. private function cascadeDetach($entity, array &$visited)
  1704. {
  1705. $class = $this->em->getClassMetadata(get_class($entity));
  1706. $associationMappings = array_filter(
  1707. $class->associationMappings,
  1708. function ($assoc) { return $assoc['isCascadeDetach']; }
  1709. );
  1710. foreach ($associationMappings as $assoc) {
  1711. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1712. switch (true) {
  1713. case ($relatedEntities instanceof PersistentCollection):
  1714. // Unwrap so that foreach() does not initialize
  1715. $relatedEntities = $relatedEntities->unwrap();
  1716. // break; is commented intentionally!
  1717. case ($relatedEntities instanceof Collection):
  1718. case (is_array($relatedEntities)):
  1719. foreach ($relatedEntities as $relatedEntity) {
  1720. $this->doDetach($relatedEntity, $visited);
  1721. }
  1722. break;
  1723. case ($relatedEntities !== null):
  1724. $this->doDetach($relatedEntities, $visited);
  1725. break;
  1726. default:
  1727. // Do nothing
  1728. }
  1729. }
  1730. }
  1731. /**
  1732. * Cascades a merge operation to associated entities.
  1733. *
  1734. * @param object $entity
  1735. * @param object $managedCopy
  1736. * @param array $visited
  1737. */
  1738. private function cascadeMerge($entity, $managedCopy, array &$visited)
  1739. {
  1740. $class = $this->em->getClassMetadata(get_class($entity));
  1741. $associationMappings = array_filter(
  1742. $class->associationMappings,
  1743. function ($assoc) { return $assoc['isCascadeMerge']; }
  1744. );
  1745. foreach ($associationMappings as $assoc) {
  1746. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1747. if ($relatedEntities instanceof Collection) {
  1748. if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
  1749. continue;
  1750. }
  1751. if ($relatedEntities instanceof PersistentCollection) {
  1752. // Unwrap so that foreach() does not initialize
  1753. $relatedEntities = $relatedEntities->unwrap();
  1754. }
  1755. foreach ($relatedEntities as $relatedEntity) {
  1756. $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
  1757. }
  1758. } else if ($relatedEntities !== null) {
  1759. $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
  1760. }
  1761. }
  1762. }
  1763. /**
  1764. * Cascades the save operation to associated entities.
  1765. *
  1766. * @param object $entity
  1767. * @param array $visited
  1768. *
  1769. * @return void
  1770. */
  1771. private function cascadePersist($entity, array &$visited)
  1772. {
  1773. $class = $this->em->getClassMetadata(get_class($entity));
  1774. $associationMappings = array_filter(
  1775. $class->associationMappings,
  1776. function ($assoc) { return $assoc['isCascadePersist']; }
  1777. );
  1778. foreach ($associationMappings as $assoc) {
  1779. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1780. switch (true) {
  1781. case ($relatedEntities instanceof PersistentCollection):
  1782. // Unwrap so that foreach() does not initialize
  1783. $relatedEntities = $relatedEntities->unwrap();
  1784. // break; is commented intentionally!
  1785. case ($relatedEntities instanceof Collection):
  1786. case (is_array($relatedEntities)):
  1787. foreach ($relatedEntities as $relatedEntity) {
  1788. $this->doPersist($relatedEntity, $visited);
  1789. }
  1790. break;
  1791. case ($relatedEntities !== null):
  1792. $this->doPersist($relatedEntities, $visited);
  1793. break;
  1794. default:
  1795. // Do nothing
  1796. }
  1797. }
  1798. }
  1799. /**
  1800. * Cascades the delete operation to associated entities.
  1801. *
  1802. * @param object $entity
  1803. * @param array $visited
  1804. */
  1805. private function cascadeRemove($entity, array &$visited)
  1806. {
  1807. $class = $this->em->getClassMetadata(get_class($entity));
  1808. $associationMappings = array_filter(
  1809. $class->associationMappings,
  1810. function ($assoc) { return $assoc['isCascadeRemove']; }
  1811. );
  1812. foreach ($associationMappings as $assoc) {
  1813. if ($entity instanceof Proxy && !$entity->__isInitialized__) {
  1814. $entity->__load();
  1815. }
  1816. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1817. switch (true) {
  1818. case ($relatedEntities instanceof Collection):
  1819. case (is_array($relatedEntities)):
  1820. // If its a PersistentCollection initialization is intended! No unwrap!
  1821. foreach ($relatedEntities as $relatedEntity) {
  1822. $this->doRemove($relatedEntity, $visited);
  1823. }
  1824. break;
  1825. case ($relatedEntities !== null):
  1826. $this->doRemove($relatedEntities, $visited);
  1827. break;
  1828. default:
  1829. // Do nothing
  1830. }
  1831. }
  1832. }
  1833. /**
  1834. * Acquire a lock on the given entity.
  1835. *
  1836. * @param object $entity
  1837. * @param int $lockMode
  1838. * @param int $lockVersion
  1839. *
  1840. * @throws ORMInvalidArgumentException
  1841. * @throws TransactionRequiredException
  1842. * @throws OptimisticLockException
  1843. *
  1844. * @return void
  1845. */
  1846. public function lock($entity, $lockMode, $lockVersion = null)
  1847. {
  1848. if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
  1849. throw ORMInvalidArgumentException::entityNotManaged($entity);
  1850. }
  1851. $class = $this->em->getClassMetadata(get_class($entity));
  1852. switch ($lockMode) {
  1853. case \Doctrine\DBAL\LockMode::OPTIMISTIC;
  1854. if ( ! $class->isVersioned) {
  1855. throw OptimisticLockException::notVersioned($class->name);
  1856. }
  1857. if ($lockVersion === null) {
  1858. return;
  1859. }
  1860. $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
  1861. if ($entityVersion != $lockVersion) {
  1862. throw OptimisticLockException::lockFailedVersionMissmatch($entity, $lockVersion, $entityVersion);
  1863. }
  1864. break;
  1865. case \Doctrine\DBAL\LockMode::PESSIMISTIC_READ:
  1866. case \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE:
  1867. if (!$this->em->getConnection()->isTransactionActive()) {
  1868. throw TransactionRequiredException::transactionRequired();
  1869. }
  1870. $oid = spl_object_hash($entity);
  1871. $this->getEntityPersister($class->name)->lock(
  1872. array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1873. $lockMode
  1874. );
  1875. break;
  1876. default:
  1877. // Do nothing
  1878. }
  1879. }
  1880. /**
  1881. * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
  1882. *
  1883. * @return \Doctrine\ORM\Internal\CommitOrderCalculator
  1884. */
  1885. public function getCommitOrderCalculator()
  1886. {
  1887. if ($this->commitOrderCalculator === null) {
  1888. $this->commitOrderCalculator = new Internal\CommitOrderCalculator;
  1889. }
  1890. return $this->commitOrderCalculator;
  1891. }
  1892. /**
  1893. * Clears the UnitOfWork.
  1894. *
  1895. * @param string $entityName if given, only entities of this type will get detached
  1896. */
  1897. public function clear($entityName = null)
  1898. {
  1899. if ($entityName === null) {
  1900. $this->identityMap =
  1901. $this->entityIdentifiers =
  1902. $this->originalEntityData =
  1903. $this->entityChangeSets =
  1904. $this->entityStates =
  1905. $this->scheduledForDirtyCheck =
  1906. $this->entityInsertions =
  1907. $this->entityUpdates =
  1908. $this->entityDeletions =
  1909. $this->collectionDeletions =
  1910. $this->collectionUpdates =
  1911. $this->extraUpdates =
  1912. $this->readOnlyObjects =
  1913. $this->orphanRemovals = array();
  1914. if ($this->commitOrderCalculator !== null) {
  1915. $this->commitOrderCalculator->clear();
  1916. }
  1917. } else {
  1918. $visited = array();
  1919. foreach ($this->identityMap as $className => $entities) {
  1920. if ($className === $entityName) {
  1921. foreach ($entities as $entity) {
  1922. $this->doDetach($entity, $visited, true);
  1923. }
  1924. }
  1925. }
  1926. }
  1927. if ($this->evm->hasListeners(Events::onClear)) {
  1928. $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName));
  1929. }
  1930. }
  1931. /**
  1932. * INTERNAL:
  1933. * Schedules an orphaned entity for removal. The remove() operation will be
  1934. * invoked on that entity at the beginning of the next commit of this
  1935. * UnitOfWork.
  1936. *
  1937. * @ignore
  1938. * @param object $entity
  1939. */
  1940. public function scheduleOrphanRemoval($entity)
  1941. {
  1942. $this->orphanRemovals[spl_object_hash($entity)] = $entity;
  1943. }
  1944. /**
  1945. * INTERNAL:
  1946. * Schedules a complete collection for removal when this UnitOfWork commits.
  1947. *
  1948. * @param PersistentCollection $coll
  1949. */
  1950. public function scheduleCollectionDeletion(PersistentCollection $coll)
  1951. {
  1952. $coid = spl_object_hash($coll);
  1953. //TODO: if $coll is already scheduled for recreation ... what to do?
  1954. // Just remove $coll from the scheduled recreations?
  1955. if (isset($this->collectionUpdates[$coid])) {
  1956. unset($this->collectionUpdates[$coid]);
  1957. }
  1958. $this->collectionDeletions[$coid] = $coll;
  1959. }
  1960. /**
  1961. * @param PersistentCollection $coll
  1962. *
  1963. * @return bool
  1964. */
  1965. public function isCollectionScheduledForDeletion(PersistentCollection $coll)
  1966. {
  1967. return isset($this->collectionDeletions[spl_object_hash($coll)]);
  1968. }
  1969. /**
  1970. * @param ClassMetadata $class
  1971. *
  1972. * @return \Doctrine\Common\Persistence\ObjectManagerAware|object
  1973. */
  1974. private function newInstance($class)
  1975. {
  1976. $entity = $class->newInstance();
  1977. if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) {
  1978. $entity->injectObjectManager($this->em, $class);
  1979. }
  1980. return $entity;
  1981. }
  1982. /**
  1983. * INTERNAL:
  1984. * Creates an entity. Used for reconstitution of persistent entities.
  1985. *
  1986. * @ignore
  1987. * @param string $className The name of the entity class.
  1988. * @param array $data The data for the entity.
  1989. * @param array $hints Any hints to account for during reconstitution/lookup of the entity.
  1990. *
  1991. * @return object The managed entity instance.
  1992. * @internal Highly performance-sensitive method.
  1993. *
  1994. * @todo Rename: getOrCreateEntity
  1995. */
  1996. public function createEntity($className, array $data, &$hints = array())
  1997. {
  1998. $class = $this->em->getClassMetadata($className);
  1999. //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]);
  2000. if ($class->isIdentifierComposite) {
  2001. $id = array();
  2002. foreach ($class->identifier as $fieldName) {
  2003. $id[$fieldName] = isset($class->associationMappings[$fieldName])
  2004. ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
  2005. : $data[$fieldName];
  2006. }
  2007. $idHash = implode(' ', $id);
  2008. } else {
  2009. $idHash = isset($class->associationMappings[$class->identifier[0]])
  2010. ? $data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']]
  2011. : $data[$class->identifier[0]];
  2012. $id = array($class->identifier[0] => $idHash);
  2013. }
  2014. if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
  2015. $entity = $this->identityMap[$class->rootEntityName][$idHash];
  2016. $oid = spl_object_hash($entity);
  2017. if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  2018. $entity->__isInitialized__ = true;
  2019. $overrideLocalValues = true;
  2020. if ($entity instanceof NotifyPropertyChanged) {
  2021. $entity->addPropertyChangedListener($this);
  2022. }
  2023. } else {
  2024. $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
  2025. // If only a specific entity is set to refresh, check that it's the one
  2026. if(isset($hints[Query::HINT_REFRESH_ENTITY])) {
  2027. $overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity;
  2028. // inject ObjectManager into just loaded proxies.
  2029. if ($overrideLocalValues && $entity instanceof ObjectManagerAware) {
  2030. $entity->injectObjectManager($this->em, $class);
  2031. }
  2032. }
  2033. }
  2034. if ($overrideLocalValues) {
  2035. $this->originalEntityData[$oid] = $data;
  2036. }
  2037. } else {
  2038. $entity = $this->newInstance($class);
  2039. $oid = spl_object_hash($entity);
  2040. $this->entityIdentifiers[$oid] = $id;
  2041. $this->entityStates[$oid] = self::STATE_MANAGED;
  2042. $this->originalEntityData[$oid] = $data;
  2043. $this->identityMap[$class->rootEntityName][$idHash] = $entity;
  2044. if ($entity instanceof NotifyPropertyChanged) {
  2045. $entity->addPropertyChangedListener($this);
  2046. }
  2047. $overrideLocalValues = true;
  2048. }
  2049. if ( ! $overrideLocalValues) {
  2050. return $entity;
  2051. }
  2052. foreach ($data as $field => $value) {
  2053. if (isset($class->fieldMappings[$field])) {
  2054. $class->reflFields[$field]->setValue($entity, $value);
  2055. }
  2056. }
  2057. // Loading the entity right here, if its in the eager loading map get rid of it there.
  2058. unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
  2059. if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
  2060. unset($this->eagerLoadingEntities[$class->rootEntityName]);
  2061. }
  2062. // Properly initialize any unfetched associations, if partial objects are not allowed.
  2063. if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
  2064. return $entity;
  2065. }
  2066. foreach ($class->associationMappings as $field => $assoc) {
  2067. // Check if the association is not among the fetch-joined associations already.
  2068. if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
  2069. continue;
  2070. }
  2071. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  2072. switch (true) {
  2073. case ($assoc['type'] & ClassMetadata::TO_ONE):
  2074. if ( ! $assoc['isOwningSide']) {
  2075. // Inverse side of x-to-one can never be lazy
  2076. $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
  2077. continue 2;
  2078. }
  2079. $associatedId = array();
  2080. // TODO: Is this even computed right in all cases of composite keys?
  2081. foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
  2082. $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;
  2083. if ($joinColumnValue !== null) {
  2084. if ($targetClass->containsForeignIdentifier) {
  2085. $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
  2086. } else {
  2087. $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
  2088. }
  2089. }
  2090. }
  2091. if ( ! $associatedId) {
  2092. // Foreign key is NULL
  2093. $class->reflFields[$field]->setValue($entity, null);
  2094. $this->originalEntityData[$oid][$field] = null;
  2095. continue;
  2096. }
  2097. if ( ! isset($hints['fetchMode'][$class->name][$field])) {
  2098. $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
  2099. }
  2100. // Foreign key is set
  2101. // Check identity map first
  2102. // FIXME: Can break easily with composite keys if join column values are in
  2103. // wrong order. The correct order is the one in ClassMetadata#identifier.
  2104. $relatedIdHash = implode(' ', $associatedId);
  2105. switch (true) {
  2106. case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
  2107. $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
  2108. // If this is an uninitialized proxy, we are deferring eager loads,
  2109. // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
  2110. // then we can append this entity for eager loading!
  2111. if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
  2112. isset($hints['deferEagerLoad']) &&
  2113. !$targetClass->isIdentifierComposite &&
  2114. $newValue instanceof Proxy &&
  2115. $newValue->__isInitialized__ === false) {
  2116. $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2117. }
  2118. break;
  2119. case ($targetClass->subClasses):
  2120. // If it might be a subtype, it can not be lazy. There isn't even
  2121. // a way to solve this with deferred eager loading, which means putting
  2122. // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
  2123. $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId);
  2124. break;
  2125. default:
  2126. switch (true) {
  2127. // We are negating the condition here. Other cases will assume it is valid!
  2128. case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
  2129. $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2130. break;
  2131. // Deferred eager load only works for single identifier classes
  2132. case (isset($hints['deferEagerLoad']) && ! $targetClass->isIdentifierComposite):
  2133. // TODO: Is there a faster approach?
  2134. $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  2135. $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  2136. break;
  2137. default:
  2138. // TODO: This is very imperformant, ignore it?
  2139. $newValue = $this->em->find($assoc['targetEntity'], $associatedId);
  2140. break;
  2141. }
  2142. // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
  2143. $newValueOid = spl_object_hash($newValue);
  2144. $this->entityIdentifiers[$newValueOid] = $associatedId;
  2145. $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
  2146. $this->entityStates[$newValueOid] = self::STATE_MANAGED;
  2147. // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
  2148. break;
  2149. }
  2150. $this->originalEntityData[$oid][$field] = $newValue;
  2151. $class->reflFields[$field]->setValue($entity, $newValue);
  2152. if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
  2153. $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
  2154. $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
  2155. }
  2156. break;
  2157. default:
  2158. // Inject collection
  2159. $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
  2160. $pColl->setOwner($entity, $assoc);
  2161. $pColl->setInitialized(false);
  2162. $reflField = $class->reflFields[$field];
  2163. $reflField->setValue($entity, $pColl);
  2164. if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
  2165. $this->loadCollection($pColl);
  2166. $pColl->takeSnapshot();
  2167. }
  2168. $this->originalEntityData[$oid][$field] = $pColl;
  2169. break;
  2170. }
  2171. }
  2172. if ($overrideLocalValues) {
  2173. if (isset($class->lifecycleCallbacks[Events::postLoad])) {
  2174. $class->invokeLifecycleCallbacks(Events::postLoad, $entity);
  2175. }
  2176. if ($this->evm->hasListeners(Events::postLoad)) {
  2177. $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity, $this->em));
  2178. }
  2179. }
  2180. return $entity;
  2181. }
  2182. /**
  2183. * @return void
  2184. */
  2185. public function triggerEagerLoads()
  2186. {
  2187. if ( ! $this->eagerLoadingEntities) {
  2188. return;
  2189. }
  2190. // avoid infinite recursion
  2191. $eagerLoadingEntities = $this->eagerLoadingEntities;
  2192. $this->eagerLoadingEntities = array();
  2193. foreach ($eagerLoadingEntities as $entityName => $ids) {
  2194. if ( ! $ids) {
  2195. continue;
  2196. }
  2197. $class = $this->em->getClassMetadata($entityName);
  2198. $this->getEntityPersister($entityName)->loadAll(
  2199. array_combine($class->identifier, array(array_values($ids)))
  2200. );
  2201. }
  2202. }
  2203. /**
  2204. * Initializes (loads) an uninitialized persistent collection of an entity.
  2205. *
  2206. * @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
  2207. *
  2208. * @return void
  2209. * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
  2210. */
  2211. public function loadCollection(PersistentCollection $collection)
  2212. {
  2213. $assoc = $collection->getMapping();
  2214. $persister = $this->getEntityPersister($assoc['targetEntity']);
  2215. switch ($assoc['type']) {
  2216. case ClassMetadata::ONE_TO_MANY:
  2217. $persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
  2218. break;
  2219. case ClassMetadata::MANY_TO_MANY:
  2220. $persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection);
  2221. break;
  2222. }
  2223. }
  2224. /**
  2225. * Gets the identity map of the UnitOfWork.
  2226. *
  2227. * @return array
  2228. */
  2229. public function getIdentityMap()
  2230. {
  2231. return $this->identityMap;
  2232. }
  2233. /**
  2234. * Gets the original data of an entity. The original data is the data that was
  2235. * present at the time the entity was reconstituted from the database.
  2236. *
  2237. * @param object $entity
  2238. *
  2239. * @return array
  2240. */
  2241. public function getOriginalEntityData($entity)
  2242. {
  2243. $oid = spl_object_hash($entity);
  2244. if (isset($this->originalEntityData[$oid])) {
  2245. return $this->originalEntityData[$oid];
  2246. }
  2247. return array();
  2248. }
  2249. /**
  2250. * @ignore
  2251. */
  2252. public function setOriginalEntityData($entity, array $data)
  2253. {
  2254. $this->originalEntityData[spl_object_hash($entity)] = $data;
  2255. }
  2256. /**
  2257. * INTERNAL:
  2258. * Sets a property value of the original data array of an entity.
  2259. *
  2260. * @ignore
  2261. * @param string $oid
  2262. * @param string $property
  2263. * @param mixed $value
  2264. */
  2265. public function setOriginalEntityProperty($oid, $property, $value)
  2266. {
  2267. $this->originalEntityData[$oid][$property] = $value;
  2268. }
  2269. /**
  2270. * Gets the identifier of an entity.
  2271. * The returned value is always an array of identifier values. If the entity
  2272. * has a composite identifier then the identifier values are in the same
  2273. * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
  2274. *
  2275. * @param object $entity
  2276. *
  2277. * @return array The identifier values.
  2278. */
  2279. public function getEntityIdentifier($entity)
  2280. {
  2281. return $this->entityIdentifiers[spl_object_hash($entity)];
  2282. }
  2283. /**
  2284. * Tries to find an entity with the given identifier in the identity map of
  2285. * this UnitOfWork.
  2286. *
  2287. * @param mixed $id The entity identifier to look for.
  2288. * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
  2289. *
  2290. * @return mixed Returns the entity with the specified identifier if it exists in
  2291. * this UnitOfWork, FALSE otherwise.
  2292. */
  2293. public function tryGetById($id, $rootClassName)
  2294. {
  2295. $idHash = implode(' ', (array) $id);
  2296. if (isset($this->identityMap[$rootClassName][$idHash])) {
  2297. return $this->identityMap[$rootClassName][$idHash];
  2298. }
  2299. return false;
  2300. }
  2301. /**
  2302. * Schedules an entity for dirty-checking at commit-time.
  2303. *
  2304. * @param object $entity The entity to schedule for dirty-checking.
  2305. * @todo Rename: scheduleForSynchronization
  2306. */
  2307. public function scheduleForDirtyCheck($entity)
  2308. {
  2309. $rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  2310. $this->scheduledForDirtyCheck[$rootClassName][spl_object_hash($entity)] = $entity;
  2311. }
  2312. /**
  2313. * Checks whether the UnitOfWork has any pending insertions.
  2314. *
  2315. * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
  2316. */
  2317. public function hasPendingInsertions()
  2318. {
  2319. return ! empty($this->entityInsertions);
  2320. }
  2321. /**
  2322. * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
  2323. * number of entities in the identity map.
  2324. *
  2325. * @return integer
  2326. */
  2327. public function size()
  2328. {
  2329. $countArray = array_map(function ($item) { return count($item); }, $this->identityMap);
  2330. return array_sum($countArray);
  2331. }
  2332. /**
  2333. * Gets the EntityPersister for an Entity.
  2334. *
  2335. * @param string $entityName The name of the Entity.
  2336. *
  2337. * @return \Doctrine\ORM\Persisters\BasicEntityPersister
  2338. */
  2339. public function getEntityPersister($entityName)
  2340. {
  2341. if (isset($this->persisters[$entityName])) {
  2342. return $this->persisters[$entityName];
  2343. }
  2344. $class = $this->em->getClassMetadata($entityName);
  2345. switch (true) {
  2346. case ($class->isInheritanceTypeNone()):
  2347. $persister = new Persisters\BasicEntityPersister($this->em, $class);
  2348. break;
  2349. case ($class->isInheritanceTypeSingleTable()):
  2350. $persister = new Persisters\SingleTablePersister($this->em, $class);
  2351. break;
  2352. case ($class->isInheritanceTypeJoined()):
  2353. $persister = new Persisters\JoinedSubclassPersister($this->em, $class);
  2354. break;
  2355. default:
  2356. $persister = new Persisters\UnionSubclassPersister($this->em, $class);
  2357. }
  2358. $this->persisters[$entityName] = $persister;
  2359. return $this->persisters[$entityName];
  2360. }
  2361. /**
  2362. * Gets a collection persister for a collection-valued association.
  2363. *
  2364. * @param array $association
  2365. *
  2366. * @return \Doctrine\ORM\Persisters\AbstractCollectionPersister
  2367. */
  2368. public function getCollectionPersister(array $association)
  2369. {
  2370. $type = $association['type'];
  2371. if (isset($this->collectionPersisters[$type])) {
  2372. return $this->collectionPersisters[$type];
  2373. }
  2374. switch ($type) {
  2375. case ClassMetadata::ONE_TO_MANY:
  2376. $persister = new Persisters\OneToManyPersister($this->em);
  2377. break;
  2378. case ClassMetadata::MANY_TO_MANY:
  2379. $persister = new Persisters\ManyToManyPersister($this->em);
  2380. break;
  2381. }
  2382. $this->collectionPersisters[$type] = $persister;
  2383. return $this->collectionPersisters[$type];
  2384. }
  2385. /**
  2386. * INTERNAL:
  2387. * Registers an entity as managed.
  2388. *
  2389. * @param object $entity The entity.
  2390. * @param array $id The identifier values.
  2391. * @param array $data The original entity data.
  2392. */
  2393. public function registerManaged($entity, array $id, array $data)
  2394. {
  2395. $oid = spl_object_hash($entity);
  2396. $this->entityIdentifiers[$oid] = $id;
  2397. $this->entityStates[$oid] = self::STATE_MANAGED;
  2398. $this->originalEntityData[$oid] = $data;
  2399. $this->addToIdentityMap($entity);
  2400. if ($entity instanceof NotifyPropertyChanged) {
  2401. $entity->addPropertyChangedListener($this);
  2402. }
  2403. }
  2404. /**
  2405. * INTERNAL:
  2406. * Clears the property changeset of the entity with the given OID.
  2407. *
  2408. * @param string $oid The entity's OID.
  2409. */
  2410. public function clearEntityChangeSet($oid)
  2411. {
  2412. $this->entityChangeSets[$oid] = array();
  2413. }
  2414. /* PropertyChangedListener implementation */
  2415. /**
  2416. * Notifies this UnitOfWork of a property change in an entity.
  2417. *
  2418. * @param object $entity The entity that owns the property.
  2419. * @param string $propertyName The name of the property that changed.
  2420. * @param mixed $oldValue The old value of the property.
  2421. * @param mixed $newValue The new value of the property.
  2422. */
  2423. public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
  2424. {
  2425. $oid = spl_object_hash($entity);
  2426. $class = $this->em->getClassMetadata(get_class($entity));
  2427. $isAssocField = isset($class->associationMappings[$propertyName]);
  2428. if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
  2429. return; // ignore non-persistent fields
  2430. }
  2431. // Update changeset and mark entity for synchronization
  2432. $this->entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue);
  2433. if ( ! isset($this->scheduledForDirtyCheck[$class->rootEntityName][$oid])) {
  2434. $this->scheduleForDirtyCheck($entity);
  2435. }
  2436. }
  2437. /**
  2438. * Gets the currently scheduled entity insertions in this UnitOfWork.
  2439. *
  2440. * @return array
  2441. */
  2442. public function getScheduledEntityInsertions()
  2443. {
  2444. return $this->entityInsertions;
  2445. }
  2446. /**
  2447. * Gets the currently scheduled entity updates in this UnitOfWork.
  2448. *
  2449. * @return array
  2450. */
  2451. public function getScheduledEntityUpdates()
  2452. {
  2453. return $this->entityUpdates;
  2454. }
  2455. /**
  2456. * Gets the currently scheduled entity deletions in this UnitOfWork.
  2457. *
  2458. * @return array
  2459. */
  2460. public function getScheduledEntityDeletions()
  2461. {
  2462. return $this->entityDeletions;
  2463. }
  2464. /**
  2465. * Get the currently scheduled complete collection deletions
  2466. *
  2467. * @return array
  2468. */
  2469. public function getScheduledCollectionDeletions()
  2470. {
  2471. return $this->collectionDeletions;
  2472. }
  2473. /**
  2474. * Gets the currently scheduled collection inserts, updates and deletes.
  2475. *
  2476. * @return array
  2477. */
  2478. public function getScheduledCollectionUpdates()
  2479. {
  2480. return $this->collectionUpdates;
  2481. }
  2482. /**
  2483. * Helper method to initialize a lazy loading proxy or persistent collection.
  2484. *
  2485. * @param object
  2486. *
  2487. * @return void
  2488. */
  2489. public function initializeObject($obj)
  2490. {
  2491. if ($obj instanceof Proxy) {
  2492. $obj->__load();
  2493. return;
  2494. }
  2495. if ($obj instanceof PersistentCollection) {
  2496. $obj->initialize();
  2497. }
  2498. }
  2499. /**
  2500. * Helper method to show an object as string.
  2501. *
  2502. * @param object $obj
  2503. *
  2504. * @return string
  2505. */
  2506. private static function objToStr($obj)
  2507. {
  2508. return method_exists($obj, '__toString') ? (string)$obj : get_class($obj).'@'.spl_object_hash($obj);
  2509. }
  2510. /**
  2511. * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
  2512. *
  2513. * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
  2514. * on this object that might be necessary to perform a correct update.
  2515. *
  2516. *
  2517. * @param object $object
  2518. *
  2519. * @throws ORMInvalidArgumentException
  2520. *
  2521. * @return void
  2522. */
  2523. public function markReadOnly($object)
  2524. {
  2525. if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
  2526. throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2527. }
  2528. $this->readOnlyObjects[spl_object_hash($object)] = true;
  2529. }
  2530. /**
  2531. * Is this entity read only?
  2532. *
  2533. * @param object $object
  2534. *
  2535. * @throws ORMInvalidArgumentException
  2536. *
  2537. * @return bool
  2538. */
  2539. public function isReadOnly($object)
  2540. {
  2541. if ( ! is_object($object)) {
  2542. throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
  2543. }
  2544. return isset($this->readOnlyObjects[spl_object_hash($object)]);
  2545. }
  2546. }