UnitOfWork.php 95KB

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