UnitOfWork.php 105 KB

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