UnitOfWork.php 95KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  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. }
  1310. }
  1311. if ($class->isVersioned) {
  1312. $managedCopyVersion = $class->reflFields[$class->versionField]->getValue($managedCopy);
  1313. $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
  1314. // Throw exception if versions dont match.
  1315. if ($managedCopyVersion != $entityVersion) {
  1316. throw OptimisticLockException::lockFailedVersionMissmatch($entity, $entityVersion, $managedCopyVersion);
  1317. }
  1318. }
  1319. // Merge state of $entity into existing (managed) entity
  1320. foreach ($class->reflFields as $name => $prop) {
  1321. if ( ! isset($class->associationMappings[$name])) {
  1322. if ( ! $class->isIdentifier($name)) {
  1323. $prop->setValue($managedCopy, $prop->getValue($entity));
  1324. }
  1325. } else {
  1326. $assoc2 = $class->associationMappings[$name];
  1327. if ($assoc2['type'] & ClassMetadata::TO_ONE) {
  1328. $other = $prop->getValue($entity);
  1329. if ($other === null) {
  1330. $prop->setValue($managedCopy, null);
  1331. } else if ($other instanceof Proxy && !$other->__isInitialized__) {
  1332. // do not merge fields marked lazy that have not been fetched.
  1333. continue;
  1334. } else if ( ! $assoc2['isCascadeMerge']) {
  1335. if ($this->getEntityState($other, self::STATE_DETACHED) !== self::STATE_MANAGED) {
  1336. $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
  1337. $relatedId = $targetClass->getIdentifierValues($other);
  1338. if ($targetClass->subClasses) {
  1339. $other = $this->em->find($targetClass->name, $relatedId);
  1340. } else {
  1341. $other = $this->em->getProxyFactory()->getProxy($assoc2['targetEntity'], $relatedId);
  1342. $this->registerManaged($other, $relatedId, array());
  1343. }
  1344. }
  1345. $prop->setValue($managedCopy, $other);
  1346. }
  1347. } else {
  1348. $mergeCol = $prop->getValue($entity);
  1349. if ($mergeCol instanceof PersistentCollection && !$mergeCol->isInitialized()) {
  1350. // do not merge fields marked lazy that have not been fetched.
  1351. // keep the lazy persistent collection of the managed copy.
  1352. continue;
  1353. }
  1354. $managedCol = $prop->getValue($managedCopy);
  1355. if (!$managedCol) {
  1356. $managedCol = new PersistentCollection($this->em,
  1357. $this->em->getClassMetadata($assoc2['targetEntity']),
  1358. new ArrayCollection
  1359. );
  1360. $managedCol->setOwner($managedCopy, $assoc2);
  1361. $prop->setValue($managedCopy, $managedCol);
  1362. $this->originalEntityData[$oid][$name] = $managedCol;
  1363. }
  1364. if ($assoc2['isCascadeMerge']) {
  1365. $managedCol->initialize();
  1366. // clear and set dirty a managed collection if its not also the same collection to merge from.
  1367. if (!$managedCol->isEmpty() && $managedCol != $mergeCol) {
  1368. $managedCol->unwrap()->clear();
  1369. $managedCol->setDirty(true);
  1370. if ($assoc2['isOwningSide'] && $assoc2['type'] == ClassMetadata::MANY_TO_MANY && $class->isChangeTrackingNotify()) {
  1371. $this->scheduleForDirtyCheck($managedCopy);
  1372. }
  1373. }
  1374. }
  1375. }
  1376. }
  1377. if ($class->isChangeTrackingNotify()) {
  1378. // Just treat all properties as changed, there is no other choice.
  1379. $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
  1380. }
  1381. }
  1382. if ($class->isChangeTrackingDeferredExplicit()) {
  1383. $this->scheduleForDirtyCheck($entity);
  1384. }
  1385. }
  1386. if ($prevManagedCopy !== null) {
  1387. $assocField = $assoc['fieldName'];
  1388. $prevClass = $this->em->getClassMetadata(get_class($prevManagedCopy));
  1389. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  1390. $prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
  1391. } else {
  1392. $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);
  1393. if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
  1394. $class->reflFields[$assoc['mappedBy']]->setValue($managedCopy, $prevManagedCopy);
  1395. }
  1396. }
  1397. }
  1398. // Mark the managed copy visited as well
  1399. $visited[spl_object_hash($managedCopy)] = true;
  1400. $this->cascadeMerge($entity, $managedCopy, $visited);
  1401. return $managedCopy;
  1402. }
  1403. /**
  1404. * Detaches an entity from the persistence management. It's persistence will
  1405. * no longer be managed by Doctrine.
  1406. *
  1407. * @param object $entity The entity to detach.
  1408. */
  1409. public function detach($entity)
  1410. {
  1411. $visited = array();
  1412. $this->doDetach($entity, $visited);
  1413. }
  1414. /**
  1415. * Executes a detach operation on the given entity.
  1416. *
  1417. * @param object $entity
  1418. * @param array $visited
  1419. */
  1420. private function doDetach($entity, array &$visited)
  1421. {
  1422. $oid = spl_object_hash($entity);
  1423. if (isset($visited[$oid])) {
  1424. return; // Prevent infinite recursion
  1425. }
  1426. $visited[$oid] = $entity; // mark visited
  1427. switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
  1428. case self::STATE_MANAGED:
  1429. if ($this->isInIdentityMap($entity)) {
  1430. $this->removeFromIdentityMap($entity);
  1431. }
  1432. unset($this->entityInsertions[$oid], $this->entityUpdates[$oid],
  1433. $this->entityDeletions[$oid], $this->entityIdentifiers[$oid],
  1434. $this->entityStates[$oid], $this->originalEntityData[$oid]);
  1435. break;
  1436. case self::STATE_NEW:
  1437. case self::STATE_DETACHED:
  1438. return;
  1439. }
  1440. $this->cascadeDetach($entity, $visited);
  1441. }
  1442. /**
  1443. * Refreshes the state of the given entity from the database, overwriting
  1444. * any local, unpersisted changes.
  1445. *
  1446. * @param object $entity The entity to refresh.
  1447. * @throws InvalidArgumentException If the entity is not MANAGED.
  1448. */
  1449. public function refresh($entity)
  1450. {
  1451. $visited = array();
  1452. $this->doRefresh($entity, $visited);
  1453. }
  1454. /**
  1455. * Executes a refresh operation on an entity.
  1456. *
  1457. * @param object $entity The entity to refresh.
  1458. * @param array $visited The already visited entities during cascades.
  1459. * @throws InvalidArgumentException If the entity is not MANAGED.
  1460. */
  1461. private function doRefresh($entity, array &$visited)
  1462. {
  1463. $oid = spl_object_hash($entity);
  1464. if (isset($visited[$oid])) {
  1465. return; // Prevent infinite recursion
  1466. }
  1467. $visited[$oid] = $entity; // mark visited
  1468. $class = $this->em->getClassMetadata(get_class($entity));
  1469. if ($this->getEntityState($entity) == self::STATE_MANAGED) {
  1470. $this->getEntityPersister($class->name)->refresh(
  1471. array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1472. $entity
  1473. );
  1474. } else {
  1475. throw new InvalidArgumentException("Entity is not MANAGED.");
  1476. }
  1477. $this->cascadeRefresh($entity, $visited);
  1478. }
  1479. /**
  1480. * Cascades a refresh operation to associated entities.
  1481. *
  1482. * @param object $entity
  1483. * @param array $visited
  1484. */
  1485. private function cascadeRefresh($entity, array &$visited)
  1486. {
  1487. $class = $this->em->getClassMetadata(get_class($entity));
  1488. foreach ($class->associationMappings as $assoc) {
  1489. if ( ! $assoc['isCascadeRefresh']) {
  1490. continue;
  1491. }
  1492. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1493. if ($relatedEntities instanceof Collection) {
  1494. if ($relatedEntities instanceof PersistentCollection) {
  1495. // Unwrap so that foreach() does not initialize
  1496. $relatedEntities = $relatedEntities->unwrap();
  1497. }
  1498. foreach ($relatedEntities as $relatedEntity) {
  1499. $this->doRefresh($relatedEntity, $visited);
  1500. }
  1501. } else if ($relatedEntities !== null) {
  1502. $this->doRefresh($relatedEntities, $visited);
  1503. }
  1504. }
  1505. }
  1506. /**
  1507. * Cascades a detach operation to associated entities.
  1508. *
  1509. * @param object $entity
  1510. * @param array $visited
  1511. */
  1512. private function cascadeDetach($entity, array &$visited)
  1513. {
  1514. $class = $this->em->getClassMetadata(get_class($entity));
  1515. foreach ($class->associationMappings as $assoc) {
  1516. if ( ! $assoc['isCascadeDetach']) {
  1517. continue;
  1518. }
  1519. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1520. if ($relatedEntities instanceof Collection) {
  1521. if ($relatedEntities instanceof PersistentCollection) {
  1522. // Unwrap so that foreach() does not initialize
  1523. $relatedEntities = $relatedEntities->unwrap();
  1524. }
  1525. foreach ($relatedEntities as $relatedEntity) {
  1526. $this->doDetach($relatedEntity, $visited);
  1527. }
  1528. } else if ($relatedEntities !== null) {
  1529. $this->doDetach($relatedEntities, $visited);
  1530. }
  1531. }
  1532. }
  1533. /**
  1534. * Cascades a merge operation to associated entities.
  1535. *
  1536. * @param object $entity
  1537. * @param object $managedCopy
  1538. * @param array $visited
  1539. */
  1540. private function cascadeMerge($entity, $managedCopy, array &$visited)
  1541. {
  1542. $class = $this->em->getClassMetadata(get_class($entity));
  1543. foreach ($class->associationMappings as $assoc) {
  1544. if ( ! $assoc['isCascadeMerge']) {
  1545. continue;
  1546. }
  1547. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1548. if ($relatedEntities instanceof Collection) {
  1549. if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
  1550. continue;
  1551. }
  1552. if ($relatedEntities instanceof PersistentCollection) {
  1553. // Unwrap so that foreach() does not initialize
  1554. $relatedEntities = $relatedEntities->unwrap();
  1555. }
  1556. foreach ($relatedEntities as $relatedEntity) {
  1557. $this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
  1558. }
  1559. } else if ($relatedEntities !== null) {
  1560. $this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
  1561. }
  1562. }
  1563. }
  1564. /**
  1565. * Cascades the save operation to associated entities.
  1566. *
  1567. * @param object $entity
  1568. * @param array $visited
  1569. * @param array $insertNow
  1570. */
  1571. private function cascadePersist($entity, array &$visited)
  1572. {
  1573. $class = $this->em->getClassMetadata(get_class($entity));
  1574. foreach ($class->associationMappings as $assoc) {
  1575. if ( ! $assoc['isCascadePersist']) {
  1576. continue;
  1577. }
  1578. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1579. if (($relatedEntities instanceof Collection || is_array($relatedEntities))) {
  1580. if ($relatedEntities instanceof PersistentCollection) {
  1581. // Unwrap so that foreach() does not initialize
  1582. $relatedEntities = $relatedEntities->unwrap();
  1583. }
  1584. foreach ($relatedEntities as $relatedEntity) {
  1585. $this->doPersist($relatedEntity, $visited);
  1586. }
  1587. } else if ($relatedEntities !== null) {
  1588. $this->doPersist($relatedEntities, $visited);
  1589. }
  1590. }
  1591. }
  1592. /**
  1593. * Cascades the delete operation to associated entities.
  1594. *
  1595. * @param object $entity
  1596. * @param array $visited
  1597. */
  1598. private function cascadeRemove($entity, array &$visited)
  1599. {
  1600. $class = $this->em->getClassMetadata(get_class($entity));
  1601. foreach ($class->associationMappings as $assoc) {
  1602. if ( ! $assoc['isCascadeRemove']) {
  1603. continue;
  1604. }
  1605. if ($entity instanceof Proxy && !$entity->__isInitialized__) {
  1606. $entity->__load();
  1607. }
  1608. $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
  1609. if ($relatedEntities instanceof Collection || is_array($relatedEntities)) {
  1610. // If its a PersistentCollection initialization is intended! No unwrap!
  1611. foreach ($relatedEntities as $relatedEntity) {
  1612. $this->doRemove($relatedEntity, $visited);
  1613. }
  1614. } else if ($relatedEntities !== null) {
  1615. $this->doRemove($relatedEntities, $visited);
  1616. }
  1617. }
  1618. }
  1619. /**
  1620. * Acquire a lock on the given entity.
  1621. *
  1622. * @param object $entity
  1623. * @param int $lockMode
  1624. * @param int $lockVersion
  1625. */
  1626. public function lock($entity, $lockMode, $lockVersion = null)
  1627. {
  1628. if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
  1629. throw new InvalidArgumentException("Entity is not MANAGED.");
  1630. }
  1631. $entityName = get_class($entity);
  1632. $class = $this->em->getClassMetadata($entityName);
  1633. if ($lockMode == \Doctrine\DBAL\LockMode::OPTIMISTIC) {
  1634. if (!$class->isVersioned) {
  1635. throw OptimisticLockException::notVersioned($entityName);
  1636. }
  1637. if ($lockVersion != null) {
  1638. $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
  1639. if ($entityVersion != $lockVersion) {
  1640. throw OptimisticLockException::lockFailedVersionMissmatch($entity, $lockVersion, $entityVersion);
  1641. }
  1642. }
  1643. } else if (in_array($lockMode, array(\Doctrine\DBAL\LockMode::PESSIMISTIC_READ, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE))) {
  1644. if (!$this->em->getConnection()->isTransactionActive()) {
  1645. throw TransactionRequiredException::transactionRequired();
  1646. }
  1647. $oid = spl_object_hash($entity);
  1648. $this->getEntityPersister($class->name)->lock(
  1649. array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
  1650. $lockMode
  1651. );
  1652. }
  1653. }
  1654. /**
  1655. * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
  1656. *
  1657. * @return \Doctrine\ORM\Internal\CommitOrderCalculator
  1658. */
  1659. public function getCommitOrderCalculator()
  1660. {
  1661. if ($this->commitOrderCalculator === null) {
  1662. $this->commitOrderCalculator = new Internal\CommitOrderCalculator;
  1663. }
  1664. return $this->commitOrderCalculator;
  1665. }
  1666. /**
  1667. * Clears the UnitOfWork.
  1668. */
  1669. public function clear()
  1670. {
  1671. $this->identityMap =
  1672. $this->entityIdentifiers =
  1673. $this->originalEntityData =
  1674. $this->entityChangeSets =
  1675. $this->entityStates =
  1676. $this->scheduledForDirtyCheck =
  1677. $this->entityInsertions =
  1678. $this->entityUpdates =
  1679. $this->entityDeletions =
  1680. $this->collectionDeletions =
  1681. $this->collectionUpdates =
  1682. $this->extraUpdates =
  1683. $this->orphanRemovals = array();
  1684. if ($this->commitOrderCalculator !== null) {
  1685. $this->commitOrderCalculator->clear();
  1686. }
  1687. if ($this->evm->hasListeners(Events::onClear)) {
  1688. $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em));
  1689. }
  1690. }
  1691. /**
  1692. * INTERNAL:
  1693. * Schedules an orphaned entity for removal. The remove() operation will be
  1694. * invoked on that entity at the beginning of the next commit of this
  1695. * UnitOfWork.
  1696. *
  1697. * @ignore
  1698. * @param object $entity
  1699. */
  1700. public function scheduleOrphanRemoval($entity)
  1701. {
  1702. $this->orphanRemovals[spl_object_hash($entity)] = $entity;
  1703. }
  1704. /**
  1705. * INTERNAL:
  1706. * Schedules a complete collection for removal when this UnitOfWork commits.
  1707. *
  1708. * @param PersistentCollection $coll
  1709. */
  1710. public function scheduleCollectionDeletion(PersistentCollection $coll)
  1711. {
  1712. //TODO: if $coll is already scheduled for recreation ... what to do?
  1713. // Just remove $coll from the scheduled recreations?
  1714. $this->collectionDeletions[] = $coll;
  1715. }
  1716. public function isCollectionScheduledForDeletion(PersistentCollection $coll)
  1717. {
  1718. return in_array($coll, $this->collectionsDeletions, true);
  1719. }
  1720. /**
  1721. * INTERNAL:
  1722. * Creates an entity. Used for reconstitution of persistent entities.
  1723. *
  1724. * @ignore
  1725. * @param string $className The name of the entity class.
  1726. * @param array $data The data for the entity.
  1727. * @param array $hints Any hints to account for during reconstitution/lookup of the entity.
  1728. * @return object The managed entity instance.
  1729. * @internal Highly performance-sensitive method.
  1730. *
  1731. * @todo Rename: getOrCreateEntity
  1732. */
  1733. public function createEntity($className, array $data, &$hints = array())
  1734. {
  1735. $class = $this->em->getClassMetadata($className);
  1736. //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]);
  1737. if ($class->isIdentifierComposite) {
  1738. $id = array();
  1739. foreach ($class->identifier as $fieldName) {
  1740. if (isset($class->associationMappings[$fieldName])) {
  1741. $id[$fieldName] = $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']];
  1742. } else {
  1743. $id[$fieldName] = $data[$fieldName];
  1744. }
  1745. }
  1746. $idHash = implode(' ', $id);
  1747. } else {
  1748. if (isset($class->associationMappings[$class->identifier[0]])) {
  1749. $idHash = $data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']];
  1750. } else {
  1751. $idHash = $data[$class->identifier[0]];
  1752. }
  1753. $id = array($class->identifier[0] => $idHash);
  1754. }
  1755. if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
  1756. $entity = $this->identityMap[$class->rootEntityName][$idHash];
  1757. $oid = spl_object_hash($entity);
  1758. if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
  1759. $entity->__isInitialized__ = true;
  1760. $overrideLocalValues = true;
  1761. if ($entity instanceof NotifyPropertyChanged) {
  1762. $entity->addPropertyChangedListener($this);
  1763. }
  1764. } else {
  1765. $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
  1766. // If only a specific entity is set to refresh, check that it's the one
  1767. if(isset($hints[Query::HINT_REFRESH_ENTITY])) {
  1768. $overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity;
  1769. }
  1770. }
  1771. if ($overrideLocalValues) {
  1772. $this->originalEntityData[$oid] = $data;
  1773. }
  1774. } else {
  1775. $entity = $class->newInstance();
  1776. $oid = spl_object_hash($entity);
  1777. $this->entityIdentifiers[$oid] = $id;
  1778. $this->entityStates[$oid] = self::STATE_MANAGED;
  1779. $this->originalEntityData[$oid] = $data;
  1780. $this->identityMap[$class->rootEntityName][$idHash] = $entity;
  1781. if ($entity instanceof NotifyPropertyChanged) {
  1782. $entity->addPropertyChangedListener($this);
  1783. }
  1784. $overrideLocalValues = true;
  1785. }
  1786. if ($overrideLocalValues) {
  1787. foreach ($data as $field => $value) {
  1788. if (isset($class->fieldMappings[$field])) {
  1789. $class->reflFields[$field]->setValue($entity, $value);
  1790. }
  1791. }
  1792. // Loading the entity right here, if its in the eager loading map get rid of it there.
  1793. unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
  1794. // Properly initialize any unfetched associations, if partial objects are not allowed.
  1795. if ( ! isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
  1796. foreach ($class->associationMappings as $field => $assoc) {
  1797. // Check if the association is not among the fetch-joined associations already.
  1798. if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
  1799. continue;
  1800. }
  1801. $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
  1802. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  1803. if ($assoc['isOwningSide']) {
  1804. $associatedId = array();
  1805. // TODO: Is this even computed right in all cases of composite keys?
  1806. foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
  1807. $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;
  1808. if ($joinColumnValue !== null) {
  1809. if ($targetClass->containsForeignIdentifier) {
  1810. $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
  1811. } else {
  1812. $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
  1813. }
  1814. }
  1815. }
  1816. if ( ! $associatedId) {
  1817. // Foreign key is NULL
  1818. $class->reflFields[$field]->setValue($entity, null);
  1819. $this->originalEntityData[$oid][$field] = null;
  1820. } else {
  1821. if (!isset($hints['fetchMode'][$class->name][$field])) {
  1822. $hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
  1823. }
  1824. // Foreign key is set
  1825. // Check identity map first
  1826. // FIXME: Can break easily with composite keys if join column values are in
  1827. // wrong order. The correct order is the one in ClassMetadata#identifier.
  1828. $relatedIdHash = implode(' ', $associatedId);
  1829. if (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])) {
  1830. $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
  1831. // if this is an uninitialized proxy, we are deferring eager loads,
  1832. // this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
  1833. // then we cann append this entity for eager loading!
  1834. if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
  1835. isset($hints['deferEagerLoad']) &&
  1836. !$targetClass->isIdentifierComposite &&
  1837. $newValue instanceof Proxy &&
  1838. $newValue->__isInitialized__ === false) {
  1839. $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  1840. }
  1841. } else {
  1842. if ($targetClass->subClasses) {
  1843. // If it might be a subtype, it can not be lazy. There isn't even
  1844. // a way to solve this with deferred eager loading, which means putting
  1845. // an entity with subclasses at a *-to-one location is really bad! (performance-wise)
  1846. $newValue = $this->getEntityPersister($assoc['targetEntity'])
  1847. ->loadOneToOneEntity($assoc, $entity, $associatedId);
  1848. } else {
  1849. // Deferred eager load only works for single identifier classes
  1850. if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER) {
  1851. if (isset($hints['deferEagerLoad']) && !$targetClass->isIdentifierComposite) {
  1852. // TODO: Is there a faster approach?
  1853. $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
  1854. $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  1855. } else {
  1856. // TODO: This is very imperformant, ignore it?
  1857. $newValue = $this->em->find($assoc['targetEntity'], $associatedId);
  1858. }
  1859. } else {
  1860. $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
  1861. }
  1862. // PERF: Inlined & optimized code from UnitOfWork#registerManaged()
  1863. $newValueOid = spl_object_hash($newValue);
  1864. $this->entityIdentifiers[$newValueOid] = $associatedId;
  1865. $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
  1866. $this->entityStates[$newValueOid] = self::STATE_MANAGED;
  1867. // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
  1868. }
  1869. }
  1870. $this->originalEntityData[$oid][$field] = $newValue;
  1871. $class->reflFields[$field]->setValue($entity, $newValue);
  1872. if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
  1873. $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
  1874. $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
  1875. }
  1876. }
  1877. } else {
  1878. // Inverse side of x-to-one can never be lazy
  1879. $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])
  1880. ->loadOneToOneEntity($assoc, $entity));
  1881. }
  1882. } else {
  1883. // Inject collection
  1884. $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
  1885. $pColl->setOwner($entity, $assoc);
  1886. $reflField = $class->reflFields[$field];
  1887. $reflField->setValue($entity, $pColl);
  1888. if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
  1889. $this->loadCollection($pColl);
  1890. $pColl->takeSnapshot();
  1891. } else {
  1892. $pColl->setInitialized(false);
  1893. }
  1894. $this->originalEntityData[$oid][$field] = $pColl;
  1895. }
  1896. }
  1897. }
  1898. }
  1899. //TODO: These should be invoked later, after hydration, because associations may not yet be loaded here.
  1900. if (isset($class->lifecycleCallbacks[Events::postLoad])) {
  1901. $class->invokeLifecycleCallbacks(Events::postLoad, $entity);
  1902. }
  1903. if ($this->evm->hasListeners(Events::postLoad)) {
  1904. $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity, $this->em));
  1905. }
  1906. return $entity;
  1907. }
  1908. /**
  1909. * @return void
  1910. */
  1911. public function triggerEagerLoads()
  1912. {
  1913. if (!$this->eagerLoadingEntities) {
  1914. return;
  1915. }
  1916. // avoid infinite recursion
  1917. $eagerLoadingEntities = $this->eagerLoadingEntities;
  1918. $this->eagerLoadingEntities = array();
  1919. foreach ($eagerLoadingEntities AS $entityName => $ids) {
  1920. $class = $this->em->getClassMetadata($entityName);
  1921. if ($ids) {
  1922. $this->getEntityPersister($entityName)->loadAll(
  1923. array_combine($class->identifier, array(array_values($ids)))
  1924. );
  1925. }
  1926. }
  1927. }
  1928. /**
  1929. * Initializes (loads) an uninitialized persistent collection of an entity.
  1930. *
  1931. * @param PeristentCollection $collection The collection to initialize.
  1932. * @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
  1933. */
  1934. public function loadCollection(PersistentCollection $collection)
  1935. {
  1936. $assoc = $collection->getMapping();
  1937. switch ($assoc['type']) {
  1938. case ClassMetadata::ONE_TO_MANY:
  1939. $this->getEntityPersister($assoc['targetEntity'])->loadOneToManyCollection(
  1940. $assoc, $collection->getOwner(), $collection);
  1941. break;
  1942. case ClassMetadata::MANY_TO_MANY:
  1943. $this->getEntityPersister($assoc['targetEntity'])->loadManyToManyCollection(
  1944. $assoc, $collection->getOwner(), $collection);
  1945. break;
  1946. }
  1947. }
  1948. /**
  1949. * Gets the identity map of the UnitOfWork.
  1950. *
  1951. * @return array
  1952. */
  1953. public function getIdentityMap()
  1954. {
  1955. return $this->identityMap;
  1956. }
  1957. /**
  1958. * Gets the original data of an entity. The original data is the data that was
  1959. * present at the time the entity was reconstituted from the database.
  1960. *
  1961. * @param object $entity
  1962. * @return array
  1963. */
  1964. public function getOriginalEntityData($entity)
  1965. {
  1966. $oid = spl_object_hash($entity);
  1967. if (isset($this->originalEntityData[$oid])) {
  1968. return $this->originalEntityData[$oid];
  1969. }
  1970. return array();
  1971. }
  1972. /**
  1973. * @ignore
  1974. */
  1975. public function setOriginalEntityData($entity, array $data)
  1976. {
  1977. $this->originalEntityData[spl_object_hash($entity)] = $data;
  1978. }
  1979. /**
  1980. * INTERNAL:
  1981. * Sets a property value of the original data array of an entity.
  1982. *
  1983. * @ignore
  1984. * @param string $oid
  1985. * @param string $property
  1986. * @param mixed $value
  1987. */
  1988. public function setOriginalEntityProperty($oid, $property, $value)
  1989. {
  1990. $this->originalEntityData[$oid][$property] = $value;
  1991. }
  1992. /**
  1993. * Gets the identifier of an entity.
  1994. * The returned value is always an array of identifier values. If the entity
  1995. * has a composite identifier then the identifier values are in the same
  1996. * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
  1997. *
  1998. * @param object $entity
  1999. * @return array The identifier values.
  2000. */
  2001. public function getEntityIdentifier($entity)
  2002. {
  2003. return $this->entityIdentifiers[spl_object_hash($entity)];
  2004. }
  2005. /**
  2006. * Tries to find an entity with the given identifier in the identity map of
  2007. * this UnitOfWork.
  2008. *
  2009. * @param mixed $id The entity identifier to look for.
  2010. * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
  2011. * @return mixed Returns the entity with the specified identifier if it exists in
  2012. * this UnitOfWork, FALSE otherwise.
  2013. */
  2014. public function tryGetById($id, $rootClassName)
  2015. {
  2016. $idHash = implode(' ', (array) $id);
  2017. if (isset($this->identityMap[$rootClassName][$idHash])) {
  2018. return $this->identityMap[$rootClassName][$idHash];
  2019. }
  2020. return false;
  2021. }
  2022. /**
  2023. * Schedules an entity for dirty-checking at commit-time.
  2024. *
  2025. * @param object $entity The entity to schedule for dirty-checking.
  2026. * @todo Rename: scheduleForSynchronization
  2027. */
  2028. public function scheduleForDirtyCheck($entity)
  2029. {
  2030. $rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
  2031. $this->scheduledForDirtyCheck[$rootClassName][spl_object_hash($entity)] = $entity;
  2032. }
  2033. /**
  2034. * Checks whether the UnitOfWork has any pending insertions.
  2035. *
  2036. * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
  2037. */
  2038. public function hasPendingInsertions()
  2039. {
  2040. return ! empty($this->entityInsertions);
  2041. }
  2042. /**
  2043. * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
  2044. * number of entities in the identity map.
  2045. *
  2046. * @return integer
  2047. */
  2048. public function size()
  2049. {
  2050. $count = 0;
  2051. foreach ($this->identityMap as $entitySet) {
  2052. $count += count($entitySet);
  2053. }
  2054. return $count;
  2055. }
  2056. /**
  2057. * Gets the EntityPersister for an Entity.
  2058. *
  2059. * @param string $entityName The name of the Entity.
  2060. * @return \Doctrine\ORM\Persisters\AbstractEntityPersister
  2061. */
  2062. public function getEntityPersister($entityName)
  2063. {
  2064. if ( ! isset($this->persisters[$entityName])) {
  2065. $class = $this->em->getClassMetadata($entityName);
  2066. if ($class->isInheritanceTypeNone()) {
  2067. $persister = new Persisters\BasicEntityPersister($this->em, $class);
  2068. } else if ($class->isInheritanceTypeSingleTable()) {
  2069. $persister = new Persisters\SingleTablePersister($this->em, $class);
  2070. } else if ($class->isInheritanceTypeJoined()) {
  2071. $persister = new Persisters\JoinedSubclassPersister($this->em, $class);
  2072. } else {
  2073. $persister = new Persisters\UnionSubclassPersister($this->em, $class);
  2074. }
  2075. $this->persisters[$entityName] = $persister;
  2076. }
  2077. return $this->persisters[$entityName];
  2078. }
  2079. /**
  2080. * Gets a collection persister for a collection-valued association.
  2081. *
  2082. * @param AssociationMapping $association
  2083. * @return AbstractCollectionPersister
  2084. */
  2085. public function getCollectionPersister(array $association)
  2086. {
  2087. $type = $association['type'];
  2088. if ( ! isset($this->collectionPersisters[$type])) {
  2089. if ($type == ClassMetadata::ONE_TO_MANY) {
  2090. $persister = new Persisters\OneToManyPersister($this->em);
  2091. } else if ($type == ClassMetadata::MANY_TO_MANY) {
  2092. $persister = new Persisters\ManyToManyPersister($this->em);
  2093. }
  2094. $this->collectionPersisters[$type] = $persister;
  2095. }
  2096. return $this->collectionPersisters[$type];
  2097. }
  2098. /**
  2099. * INTERNAL:
  2100. * Registers an entity as managed.
  2101. *
  2102. * @param object $entity The entity.
  2103. * @param array $id The identifier values.
  2104. * @param array $data The original entity data.
  2105. */
  2106. public function registerManaged($entity, array $id, array $data)
  2107. {
  2108. $oid = spl_object_hash($entity);
  2109. $this->entityIdentifiers[$oid] = $id;
  2110. $this->entityStates[$oid] = self::STATE_MANAGED;
  2111. $this->originalEntityData[$oid] = $data;
  2112. $this->addToIdentityMap($entity);
  2113. }
  2114. /**
  2115. * INTERNAL:
  2116. * Clears the property changeset of the entity with the given OID.
  2117. *
  2118. * @param string $oid The entity's OID.
  2119. */
  2120. public function clearEntityChangeSet($oid)
  2121. {
  2122. $this->entityChangeSets[$oid] = array();
  2123. }
  2124. /* PropertyChangedListener implementation */
  2125. /**
  2126. * Notifies this UnitOfWork of a property change in an entity.
  2127. *
  2128. * @param object $entity The entity that owns the property.
  2129. * @param string $propertyName The name of the property that changed.
  2130. * @param mixed $oldValue The old value of the property.
  2131. * @param mixed $newValue The new value of the property.
  2132. */
  2133. public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
  2134. {
  2135. $oid = spl_object_hash($entity);
  2136. $class = $this->em->getClassMetadata(get_class($entity));
  2137. $isAssocField = isset($class->associationMappings[$propertyName]);
  2138. if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
  2139. return; // ignore non-persistent fields
  2140. }
  2141. // Update changeset and mark entity for synchronization
  2142. $this->entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue);
  2143. if ( ! isset($this->scheduledForDirtyCheck[$class->rootEntityName][$oid])) {
  2144. $this->scheduleForDirtyCheck($entity);
  2145. }
  2146. }
  2147. /**
  2148. * Gets the currently scheduled entity insertions in this UnitOfWork.
  2149. *
  2150. * @return array
  2151. */
  2152. public function getScheduledEntityInsertions()
  2153. {
  2154. return $this->entityInsertions;
  2155. }
  2156. /**
  2157. * Gets the currently scheduled entity updates in this UnitOfWork.
  2158. *
  2159. * @return array
  2160. */
  2161. public function getScheduledEntityUpdates()
  2162. {
  2163. return $this->entityUpdates;
  2164. }
  2165. /**
  2166. * Gets the currently scheduled entity deletions in this UnitOfWork.
  2167. *
  2168. * @return array
  2169. */
  2170. public function getScheduledEntityDeletions()
  2171. {
  2172. return $this->entityDeletions;
  2173. }
  2174. /**
  2175. * Get the currently scheduled complete collection deletions
  2176. *
  2177. * @return array
  2178. */
  2179. public function getScheduledCollectionDeletions()
  2180. {
  2181. return $this->collectionDeletions;
  2182. }
  2183. /**
  2184. * Gets the currently scheduled collection inserts, updates and deletes.
  2185. *
  2186. * @return array
  2187. */
  2188. public function getScheduledCollectionUpdates()
  2189. {
  2190. return $this->collectionUpdates;
  2191. }
  2192. /**
  2193. * Helper method to initialize a lazy loading proxy or persistent collection.
  2194. *
  2195. * @param object
  2196. * @return void
  2197. */
  2198. public function initializeObject($obj)
  2199. {
  2200. if ($obj instanceof Proxy) {
  2201. $obj->__load();
  2202. } else if ($obj instanceof PersistentCollection) {
  2203. $obj->initialize();
  2204. }
  2205. }
  2206. /**
  2207. * Helper method to show an object as string.
  2208. *
  2209. * @param object $obj
  2210. * @return string
  2211. */
  2212. private static function objToStr($obj)
  2213. {
  2214. return method_exists($obj, '__toString') ? (string)$obj : get_class($obj).'@'.spl_object_hash($obj);
  2215. }
  2216. /**
  2217. * Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
  2218. *
  2219. * This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
  2220. * on this object that might be necessary to perform a correct udpate.
  2221. *
  2222. * @throws \InvalidArgumentException
  2223. * @param $object
  2224. * @return void
  2225. */
  2226. public function markReadOnly($object)
  2227. {
  2228. if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
  2229. throw new InvalidArgumentException("Managed entity required");
  2230. }
  2231. $this->readOnlyObjects[spl_object_hash($object)] = true;
  2232. }
  2233. /**
  2234. * Is this entity read only?
  2235. *
  2236. * @throws \InvalidArgumentException
  2237. * @param $object
  2238. * @return void
  2239. */
  2240. public function isReadOnly($object)
  2241. {
  2242. if ( ! is_object($object) ) {
  2243. throw new InvalidArgumentException("Managed entity required");
  2244. }
  2245. return isset($this->readOnlyObjects[spl_object_hash($object)]);
  2246. }
  2247. }