UnitOfWork.php 102 KB

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