UnitOfWork.php 124 KB

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