UnitOfWork.php 110 KB

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