UnitOfWork.php 92KB

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