UnitOfWork.php 97KB

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