TableTest.php 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use ArrayObject;
  17. use Cake\Collection\Collection;
  18. use Cake\Database\Exception;
  19. use Cake\Database\Expression\QueryExpression;
  20. use Cake\Database\Schema\TableSchema;
  21. use Cake\Database\TypeMap;
  22. use Cake\Datasource\ConnectionManager;
  23. use Cake\Datasource\EntityInterface;
  24. use Cake\Event\Event;
  25. use Cake\Event\EventManager;
  26. use Cake\I18n\Time;
  27. use Cake\ORM\AssociationCollection;
  28. use Cake\ORM\Association\BelongsTo;
  29. use Cake\ORM\Association\BelongsToMany;
  30. use Cake\ORM\Association\HasMany;
  31. use Cake\ORM\Association\HasOne;
  32. use Cake\ORM\Entity;
  33. use Cake\ORM\Exception\PersistenceFailedException;
  34. use Cake\ORM\Query;
  35. use Cake\ORM\RulesChecker;
  36. use Cake\ORM\SaveOptionsBuilder;
  37. use Cake\ORM\Table;
  38. use Cake\TestSuite\TestCase;
  39. use Cake\Utility\Hash;
  40. use Cake\Validation\Validator;
  41. use InvalidArgumentException;
  42. /**
  43. * Used to test correct class is instantiated when using $this->getTableLocator()->get();
  44. */
  45. class UsersTable extends Table
  46. {
  47. }
  48. class ProtectedEntity extends Entity
  49. {
  50. protected $_accessible = [
  51. 'id' => false,
  52. 'title' => false,
  53. 'body' => true,
  54. ];
  55. }
  56. /**
  57. * Tests Table class
  58. */
  59. class TableTest extends TestCase
  60. {
  61. public $fixtures = [
  62. 'core.Articles',
  63. 'core.Tags',
  64. 'core.ArticlesTags',
  65. 'core.Authors',
  66. 'core.Categories',
  67. 'core.Comments',
  68. 'core.Groups',
  69. 'core.GroupsMembers',
  70. 'core.Members',
  71. 'core.PolymorphicTagged',
  72. 'core.SiteArticles',
  73. 'core.Users',
  74. ];
  75. /**
  76. * Handy variable containing the next primary key that will be inserted in the
  77. * users table
  78. *
  79. * @var int
  80. */
  81. public static $nextUserId = 5;
  82. public function setUp()
  83. {
  84. parent::setUp();
  85. $this->connection = ConnectionManager::get('test');
  86. static::setAppNamespace();
  87. $this->usersTypeMap = new TypeMap([
  88. 'Users.id' => 'integer',
  89. 'id' => 'integer',
  90. 'Users__id' => 'integer',
  91. 'Users.username' => 'string',
  92. 'Users__username' => 'string',
  93. 'username' => 'string',
  94. 'Users.password' => 'string',
  95. 'Users__password' => 'string',
  96. 'password' => 'string',
  97. 'Users.created' => 'timestamp',
  98. 'Users__created' => 'timestamp',
  99. 'created' => 'timestamp',
  100. 'Users.updated' => 'timestamp',
  101. 'Users__updated' => 'timestamp',
  102. 'updated' => 'timestamp',
  103. ]);
  104. $this->articlesTypeMap = new TypeMap([
  105. 'Articles.id' => 'integer',
  106. 'Articles__id' => 'integer',
  107. 'id' => 'integer',
  108. 'Articles.title' => 'string',
  109. 'Articles__title' => 'string',
  110. 'title' => 'string',
  111. 'Articles.author_id' => 'integer',
  112. 'Articles__author_id' => 'integer',
  113. 'author_id' => 'integer',
  114. 'Articles.body' => 'text',
  115. 'Articles__body' => 'text',
  116. 'body' => 'text',
  117. 'Articles.published' => 'string',
  118. 'Articles__published' => 'string',
  119. 'published' => 'string',
  120. ]);
  121. }
  122. /**
  123. * teardown method
  124. *
  125. * @return void
  126. */
  127. public function tearDown()
  128. {
  129. parent::tearDown();
  130. $this->clearPlugins();
  131. }
  132. /**
  133. * Tests the table method
  134. *
  135. * @return void
  136. */
  137. public function testTableMethod()
  138. {
  139. $table = new Table(['table' => 'users']);
  140. $this->assertEquals('users', $table->getTable());
  141. $table = new UsersTable();
  142. $this->assertEquals('users', $table->getTable());
  143. $table = $this->getMockBuilder('\Cake\ORM\Table')
  144. ->setMethods(['find'])
  145. ->setMockClassName('SpecialThingsTable')
  146. ->getMock();
  147. $this->assertEquals('special_things', $table->getTable());
  148. $table = new Table(['alias' => 'LoveBoats']);
  149. $this->assertEquals('love_boats', $table->getTable());
  150. $table->setTable('other');
  151. $this->assertEquals('other', $table->getTable());
  152. $table->setTable('database.other');
  153. $this->assertEquals('database.other', $table->getTable());
  154. }
  155. /**
  156. * Tests the alias method
  157. *
  158. * @group deprecated
  159. * @return void
  160. */
  161. public function testAliasMethod()
  162. {
  163. $this->deprecated(function () {
  164. $table = new Table(['alias' => 'users']);
  165. $this->assertEquals('users', $table->alias());
  166. $table = new Table(['table' => 'stuffs']);
  167. $this->assertEquals('stuffs', $table->alias());
  168. $table = new UsersTable();
  169. $this->assertEquals('Users', $table->alias());
  170. $table = $this->getMockBuilder('\Cake\ORM\Table')
  171. ->setMethods(['find'])
  172. ->setMockClassName('SpecialThingTable')
  173. ->getMock();
  174. $this->assertEquals('SpecialThing', $table->alias());
  175. $table->alias('AnotherOne');
  176. $this->assertEquals('AnotherOne', $table->alias());
  177. });
  178. }
  179. /**
  180. * Tests the setAlias method
  181. *
  182. * @return void
  183. */
  184. public function testSetAlias()
  185. {
  186. $table = new Table(['alias' => 'users']);
  187. $this->assertEquals('users', $table->getAlias());
  188. $table = new Table(['table' => 'stuffs']);
  189. $this->assertEquals('stuffs', $table->getAlias());
  190. $table = new UsersTable();
  191. $this->assertEquals('Users', $table->getAlias());
  192. $table = $this->getMockBuilder('\Cake\ORM\Table')
  193. ->setMethods(['find'])
  194. ->setMockClassName('SpecialThingTable')
  195. ->getMock();
  196. $this->assertEquals('SpecialThing', $table->getAlias());
  197. $table->setAlias('AnotherOne');
  198. $this->assertEquals('AnotherOne', $table->getAlias());
  199. }
  200. /**
  201. * Test that aliasField() works.
  202. *
  203. * @return void
  204. */
  205. public function testAliasField()
  206. {
  207. $table = new Table(['alias' => 'Users']);
  208. $this->assertEquals('Users.id', $table->aliasField('id'));
  209. $this->assertEquals('Users.id', $table->aliasField('Users.id'));
  210. }
  211. /**
  212. * Tests connection method
  213. *
  214. * @group deprecated
  215. * @return void
  216. */
  217. public function testConnection()
  218. {
  219. $this->deprecated(function () {
  220. $table = new Table(['table' => 'users']);
  221. $table->connection($this->connection);
  222. $this->assertSame($this->connection, $table->connection());
  223. });
  224. }
  225. /**
  226. * Tests setConnection method
  227. *
  228. * @return void
  229. */
  230. public function testSetConnection()
  231. {
  232. $table = new Table(['table' => 'users']);
  233. $this->assertSame($table, $table->setConnection($this->connection));
  234. $this->assertSame($this->connection, $table->getConnection());
  235. }
  236. /**
  237. * Tests primaryKey method
  238. *
  239. * @group deprecated
  240. * @return void
  241. */
  242. public function testPrimaryKey()
  243. {
  244. $this->deprecated(function () {
  245. $table = new Table([
  246. 'table' => 'users',
  247. 'schema' => [
  248. 'id' => ['type' => 'integer'],
  249. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]],
  250. ],
  251. ]);
  252. $this->assertEquals('id', $table->primaryKey());
  253. $table->primaryKey('thingID');
  254. $this->assertEquals('thingID', $table->primaryKey());
  255. $table->primaryKey(['thingID', 'user_id']);
  256. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  257. });
  258. }
  259. /**
  260. * Tests primaryKey method
  261. *
  262. * @return void
  263. */
  264. public function testSetPrimaryKey()
  265. {
  266. $table = new Table([
  267. 'table' => 'users',
  268. 'schema' => [
  269. 'id' => ['type' => 'integer'],
  270. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]],
  271. ],
  272. ]);
  273. $this->assertEquals('id', $table->getPrimaryKey());
  274. $this->assertSame($table, $table->setPrimaryKey('thingID'));
  275. $this->assertEquals('thingID', $table->getPrimaryKey());
  276. $table->setPrimaryKey(['thingID', 'user_id']);
  277. $this->assertEquals(['thingID', 'user_id'], $table->getPrimaryKey());
  278. }
  279. /**
  280. * Tests that name will be selected as a displayField
  281. *
  282. * @return void
  283. */
  284. public function testDisplayFieldName()
  285. {
  286. $table = new Table([
  287. 'table' => 'users',
  288. 'schema' => [
  289. 'foo' => ['type' => 'string'],
  290. 'name' => ['type' => 'string'],
  291. ],
  292. ]);
  293. $this->assertEquals('name', $table->getDisplayField());
  294. }
  295. /**
  296. * Tests that title will be selected as a displayField
  297. *
  298. * @return void
  299. */
  300. public function testDisplayFieldTitle()
  301. {
  302. $table = new Table([
  303. 'table' => 'users',
  304. 'schema' => [
  305. 'foo' => ['type' => 'string'],
  306. 'title' => ['type' => 'string'],
  307. ],
  308. ]);
  309. $this->assertEquals('title', $table->getDisplayField());
  310. }
  311. /**
  312. * Tests that no displayField will fallback to primary key
  313. *
  314. * @return void
  315. */
  316. public function testDisplayFallback()
  317. {
  318. $table = new Table([
  319. 'table' => 'users',
  320. 'schema' => [
  321. 'id' => ['type' => 'string'],
  322. 'foo' => ['type' => 'string'],
  323. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]],
  324. ],
  325. ]);
  326. $this->assertEquals('id', $table->getDisplayField());
  327. }
  328. /**
  329. * Tests that displayField can be changed
  330. *
  331. * @return void
  332. */
  333. public function testDisplaySet()
  334. {
  335. $table = new Table([
  336. 'table' => 'users',
  337. 'schema' => [
  338. 'id' => ['type' => 'string'],
  339. 'foo' => ['type' => 'string'],
  340. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]],
  341. ],
  342. ]);
  343. $this->assertEquals('id', $table->getDisplayField());
  344. $table->setDisplayField('foo');
  345. $this->assertEquals('foo', $table->getDisplayField());
  346. }
  347. /**
  348. * Tests schema method
  349. *
  350. * @group deprecated
  351. * @return void
  352. */
  353. public function testSchema()
  354. {
  355. $this->deprecated(function () {
  356. $schema = $this->connection->getSchemaCollection()->describe('users');
  357. $table = new Table([
  358. 'table' => 'users',
  359. 'connection' => $this->connection,
  360. ]);
  361. $this->assertEquals($schema, $table->schema());
  362. $table = new Table(['table' => 'stuff']);
  363. $table->schema($schema);
  364. $this->assertSame($schema, $table->schema());
  365. $table = new Table(['table' => 'another']);
  366. $schema = ['id' => ['type' => 'integer']];
  367. $table->schema($schema);
  368. $this->assertEquals(
  369. new TableSchema('another', $schema),
  370. $table->schema()
  371. );
  372. });
  373. }
  374. /**
  375. * Tests schema method
  376. *
  377. * @return void
  378. */
  379. public function testSetSchema()
  380. {
  381. $schema = $this->connection->getSchemaCollection()->describe('users');
  382. $table = new Table([
  383. 'table' => 'users',
  384. 'connection' => $this->connection,
  385. ]);
  386. $this->assertEquals($schema, $table->getSchema());
  387. $table = new Table(['table' => 'stuff']);
  388. $table->setSchema($schema);
  389. $this->assertSame($schema, $table->getSchema());
  390. $table = new Table(['table' => 'another']);
  391. $schema = ['id' => ['type' => 'integer']];
  392. $table->setSchema($schema);
  393. $this->assertEquals(
  394. new TableSchema('another', $schema),
  395. $table->getSchema()
  396. );
  397. }
  398. /**
  399. * Tests that _initializeSchema can be used to alter the database schema
  400. *
  401. * @return void
  402. */
  403. public function testSchemaInitialize()
  404. {
  405. $schema = $this->connection->getSchemaCollection()->describe('users');
  406. $table = $this->getMockBuilder('Cake\ORM\Table')
  407. ->setMethods(['_initializeSchema'])
  408. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  409. ->getMock();
  410. $table->expects($this->once())
  411. ->method('_initializeSchema')
  412. ->with($schema)
  413. ->will($this->returnCallback(function ($schema) {
  414. $schema->setColumnType('username', 'integer');
  415. return $schema;
  416. }));
  417. $result = $table->getSchema();
  418. $schema->setColumnType('username', 'integer');
  419. $this->assertEquals($schema, $result);
  420. $this->assertEquals($schema, $table->getSchema(), '_initializeSchema should be called once');
  421. }
  422. /**
  423. * Tests that all fields for a table are added by default in a find when no
  424. * other fields are specified
  425. *
  426. * @return void
  427. */
  428. public function testFindAllNoFieldsAndNoHydration()
  429. {
  430. $table = new Table([
  431. 'table' => 'users',
  432. 'connection' => $this->connection,
  433. ]);
  434. $results = $table
  435. ->find('all')
  436. ->where(['id IN' => [1, 2]])
  437. ->order('id')
  438. ->enableHydration(false)
  439. ->toArray();
  440. $expected = [
  441. [
  442. 'id' => 1,
  443. 'username' => 'mariano',
  444. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  445. 'created' => new Time('2007-03-17 01:16:23'),
  446. 'updated' => new Time('2007-03-17 01:18:31'),
  447. ],
  448. [
  449. 'id' => 2,
  450. 'username' => 'nate',
  451. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  452. 'created' => new Time('2008-03-17 01:18:23'),
  453. 'updated' => new Time('2008-03-17 01:20:31'),
  454. ],
  455. ];
  456. $this->assertEquals($expected, $results);
  457. }
  458. /**
  459. * Tests that it is possible to select only a few fields when finding over a table
  460. *
  461. * @return void
  462. */
  463. public function testFindAllSomeFieldsNoHydration()
  464. {
  465. $table = new Table([
  466. 'table' => 'users',
  467. 'connection' => $this->connection,
  468. ]);
  469. $results = $table->find('all')
  470. ->select(['username', 'password'])
  471. ->enableHydration(false)
  472. ->order('username')->toArray();
  473. $expected = [
  474. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  475. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  476. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  477. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  478. ];
  479. $this->assertSame($expected, $results);
  480. $results = $table->find('all')
  481. ->select(['foo' => 'username', 'password'])
  482. ->order('username')
  483. ->enableHydration(false)
  484. ->toArray();
  485. $expected = [
  486. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  487. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  488. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  489. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  490. ];
  491. $this->assertSame($expected, $results);
  492. }
  493. /**
  494. * Tests that the query will automatically casts complex conditions to the correct
  495. * types when the columns belong to the default table
  496. *
  497. * @return void
  498. */
  499. public function testFindAllConditionAutoTypes()
  500. {
  501. $table = new Table([
  502. 'table' => 'users',
  503. 'connection' => $this->connection,
  504. ]);
  505. $query = $table->find('all')
  506. ->select(['id', 'username'])
  507. ->where(['created >=' => new Time('2010-01-22 00:00')])
  508. ->enableHydration(false)
  509. ->order('id');
  510. $expected = [
  511. ['id' => 3, 'username' => 'larry'],
  512. ['id' => 4, 'username' => 'garrett'],
  513. ];
  514. $this->assertSame($expected, $query->toArray());
  515. $query = $table->find()
  516. ->enableHydration(false)
  517. ->select(['id', 'username'])
  518. ->where(['OR' => [
  519. 'created >=' => new Time('2010-01-22 00:00'),
  520. 'users.created' => new Time('2008-03-17 01:18:23'),
  521. ]])
  522. ->order('id');
  523. $expected = [
  524. ['id' => 2, 'username' => 'nate'],
  525. ['id' => 3, 'username' => 'larry'],
  526. ['id' => 4, 'username' => 'garrett'],
  527. ];
  528. $this->assertSame($expected, $query->toArray());
  529. }
  530. /**
  531. * Test that beforeFind events can mutate the query.
  532. *
  533. * @return void
  534. */
  535. public function testFindBeforeFindEventMutateQuery()
  536. {
  537. $table = new Table([
  538. 'table' => 'users',
  539. 'connection' => $this->connection,
  540. ]);
  541. $table->getEventManager()->on(
  542. 'Model.beforeFind',
  543. function (Event $event, $query, $options) {
  544. $query->limit(1);
  545. }
  546. );
  547. $result = $table->find('all')->all();
  548. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  549. }
  550. /**
  551. * Test that beforeFind events are fired and can stop the find and
  552. * return custom results.
  553. *
  554. * @return void
  555. */
  556. public function testFindBeforeFindEventOverrideReturn()
  557. {
  558. $table = new Table([
  559. 'table' => 'users',
  560. 'connection' => $this->connection,
  561. ]);
  562. $expected = ['One', 'Two', 'Three'];
  563. $table->getEventManager()->on(
  564. 'Model.beforeFind',
  565. function (Event $event, $query, $options) use ($expected) {
  566. $query->setResult($expected);
  567. $event->stopPropagation();
  568. }
  569. );
  570. $query = $table->find('all');
  571. $query->limit(1);
  572. $this->assertEquals($expected, $query->all()->toArray());
  573. }
  574. /**
  575. * Test that the getAssociation() method supports the dot syntax.
  576. *
  577. * @return void
  578. */
  579. public function testAssociationDotSyntax()
  580. {
  581. $groups = $this->getTableLocator()->get('Groups');
  582. $members = $this->getTableLocator()->get('Members');
  583. $groupsMembers = $this->getTableLocator()->get('GroupsMembers');
  584. $groups->belongsToMany('Members');
  585. $groups->hasMany('GroupsMembers');
  586. $groupsMembers->belongsTo('Members');
  587. $members->belongsToMany('Groups');
  588. $association = $groups->getAssociation('GroupsMembers.Members.Groups');
  589. $this->assertInstanceOf(BelongsToMany::class, $association);
  590. $this->assertSame(
  591. $groups->getAssociation('GroupsMembers')->getAssociation('Members')->getAssociation('Groups'),
  592. $association
  593. );
  594. }
  595. /**
  596. * Tests that the getAssociation() method throws an exception on non-existent ones.
  597. *
  598. * @return void
  599. */
  600. public function testGetAssociationNonExistent()
  601. {
  602. $this->expectException(InvalidArgumentException::class);
  603. $this->getTableLocator()->get('Groups')->getAssociation('FooBar');
  604. }
  605. /**
  606. * Tests that belongsTo() creates and configures correctly the association
  607. *
  608. * @return void
  609. */
  610. public function testBelongsTo()
  611. {
  612. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  613. $table = new Table(['table' => 'dates']);
  614. $belongsTo = $table->belongsTo('user', $options);
  615. $this->assertInstanceOf(BelongsTo::class, $belongsTo);
  616. $this->assertSame($belongsTo, $table->getAssociation('user'));
  617. $this->assertEquals('user', $belongsTo->getName());
  618. $this->assertEquals('fake_id', $belongsTo->getForeignKey());
  619. $this->assertEquals(['a' => 'b'], $belongsTo->getConditions());
  620. $this->assertSame($table, $belongsTo->getSource());
  621. }
  622. /**
  623. * Tests that hasOne() creates and configures correctly the association
  624. *
  625. * @return void
  626. */
  627. public function testHasOne()
  628. {
  629. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  630. $table = new Table(['table' => 'users']);
  631. $hasOne = $table->hasOne('profile', $options);
  632. $this->assertInstanceOf(HasOne::class, $hasOne);
  633. $this->assertSame($hasOne, $table->getAssociation('profile'));
  634. $this->assertEquals('profile', $hasOne->getName());
  635. $this->assertEquals('user_id', $hasOne->getForeignKey());
  636. $this->assertEquals(['b' => 'c'], $hasOne->getConditions());
  637. $this->assertSame($table, $hasOne->getSource());
  638. }
  639. /**
  640. * Test has one with a plugin model
  641. *
  642. * @return void
  643. */
  644. public function testHasOnePlugin()
  645. {
  646. $options = ['className' => 'TestPlugin.Comments'];
  647. $table = new Table(['table' => 'users']);
  648. $hasOne = $table->hasOne('Comments', $options);
  649. $this->assertInstanceOf(HasOne::class, $hasOne);
  650. $this->assertSame('Comments', $hasOne->getName());
  651. $hasOneTable = $hasOne->getTarget();
  652. $this->assertSame('Comments', $hasOne->getAlias());
  653. $this->assertSame('TestPlugin.Comments', $hasOne->getRegistryAlias());
  654. $options = ['className' => 'TestPlugin.Comments'];
  655. $table = new Table(['table' => 'users']);
  656. $hasOne = $table->hasOne('TestPlugin.Comments', $options);
  657. $this->assertInstanceOf(HasOne::class, $hasOne);
  658. $this->assertSame('Comments', $hasOne->getName());
  659. $hasOneTable = $hasOne->getTarget();
  660. $this->assertSame('Comments', $hasOne->getAlias());
  661. $this->assertSame('TestPlugin.Comments', $hasOne->getRegistryAlias());
  662. }
  663. /**
  664. * testNoneUniqueAssociationsSameClass
  665. *
  666. * @return void
  667. */
  668. public function testNoneUniqueAssociationsSameClass()
  669. {
  670. $Users = new Table(['table' => 'users']);
  671. $options = ['className' => 'Comments'];
  672. $Users->hasMany('Comments', $options);
  673. $Articles = new Table(['table' => 'articles']);
  674. $options = ['className' => 'Comments'];
  675. $Articles->hasMany('Comments', $options);
  676. $Categories = new Table(['table' => 'categories']);
  677. $options = ['className' => 'TestPlugin.Comments'];
  678. $Categories->hasMany('Comments', $options);
  679. $this->assertInstanceOf('Cake\ORM\Table', $Users->Comments->getTarget());
  680. $this->assertInstanceOf('Cake\ORM\Table', $Articles->Comments->getTarget());
  681. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $Categories->Comments->getTarget());
  682. }
  683. /**
  684. * Test associations which refer to the same table multiple times
  685. *
  686. * @return void
  687. */
  688. public function testSelfJoinAssociations()
  689. {
  690. $Categories = $this->getTableLocator()->get('Categories');
  691. $options = ['className' => 'Categories'];
  692. $Categories->hasMany('Children', ['foreignKey' => 'parent_id'] + $options);
  693. $Categories->belongsTo('Parent', $options);
  694. $this->assertSame('categories', $Categories->Children->getTarget()->getTable());
  695. $this->assertSame('categories', $Categories->Parent->getTarget()->getTable());
  696. $this->assertSame('Children', $Categories->Children->getAlias());
  697. $this->assertSame('Children', $Categories->Children->getTarget()->getAlias());
  698. $this->assertSame('Parent', $Categories->Parent->getAlias());
  699. $this->assertSame('Parent', $Categories->Parent->getTarget()->getAlias());
  700. $expected = [
  701. 'id' => 2,
  702. 'parent_id' => 1,
  703. 'name' => 'Category 1.1',
  704. 'parent' => [
  705. 'id' => 1,
  706. 'parent_id' => 0,
  707. 'name' => 'Category 1',
  708. ],
  709. 'children' => [
  710. [
  711. 'id' => 7,
  712. 'parent_id' => 2,
  713. 'name' => 'Category 1.1.1',
  714. ],
  715. [
  716. 'id' => 8,
  717. 'parent_id' => 2,
  718. 'name' => 'Category 1.1.2',
  719. ],
  720. ],
  721. ];
  722. $fields = ['id', 'parent_id', 'name'];
  723. $result = $Categories->find('all')
  724. ->select(['Categories.id', 'Categories.parent_id', 'Categories.name'])
  725. ->contain(['Children' => ['fields' => $fields], 'Parent' => ['fields' => $fields]])
  726. ->where(['Categories.id' => 2])
  727. ->first()
  728. ->toArray();
  729. $this->assertSame($expected, $result);
  730. }
  731. /**
  732. * Tests that hasMany() creates and configures correctly the association
  733. *
  734. * @return void
  735. */
  736. public function testHasMany()
  737. {
  738. $options = [
  739. 'foreignKey' => 'author_id',
  740. 'conditions' => ['b' => 'c'],
  741. 'sort' => ['foo' => 'asc'],
  742. ];
  743. $table = new Table(['table' => 'authors']);
  744. $hasMany = $table->hasMany('article', $options);
  745. $this->assertInstanceOf(HasMany::class, $hasMany);
  746. $this->assertSame($hasMany, $table->getAssociation('article'));
  747. $this->assertEquals('article', $hasMany->getName());
  748. $this->assertEquals('author_id', $hasMany->getForeignKey());
  749. $this->assertEquals(['b' => 'c'], $hasMany->getConditions());
  750. $this->assertEquals(['foo' => 'asc'], $hasMany->getSort());
  751. $this->assertSame($table, $hasMany->getSource());
  752. }
  753. /**
  754. * testHasManyWithClassName
  755. *
  756. * @return void
  757. */
  758. public function testHasManyWithClassName()
  759. {
  760. $table = $this->getTableLocator()->get('Articles');
  761. $table->hasMany('Comments', [
  762. 'className' => 'Comments',
  763. 'conditions' => ['published' => 'Y'],
  764. ]);
  765. $table->hasMany('UnapprovedComments', [
  766. 'className' => 'Comments',
  767. 'conditions' => ['published' => 'N'],
  768. 'propertyName' => 'unaproved_comments',
  769. ]);
  770. $expected = [
  771. 'id' => 1,
  772. 'title' => 'First Article',
  773. 'unaproved_comments' => [
  774. [
  775. 'id' => 4,
  776. 'article_id' => 1,
  777. 'comment' => 'Fourth Comment for First Article',
  778. ],
  779. ],
  780. 'comments' => [
  781. [
  782. 'id' => 1,
  783. 'article_id' => 1,
  784. 'comment' => 'First Comment for First Article',
  785. ],
  786. [
  787. 'id' => 2,
  788. 'article_id' => 1,
  789. 'comment' => 'Second Comment for First Article',
  790. ],
  791. [
  792. 'id' => 3,
  793. 'article_id' => 1,
  794. 'comment' => 'Third Comment for First Article',
  795. ],
  796. ],
  797. ];
  798. $result = $table->find()
  799. ->select(['id', 'title'])
  800. ->contain([
  801. 'Comments' => ['fields' => ['id', 'article_id', 'comment']],
  802. 'UnapprovedComments' => ['fields' => ['id', 'article_id', 'comment']],
  803. ])
  804. ->where(['id' => 1])
  805. ->first();
  806. $this->assertSame($expected, $result->toArray());
  807. }
  808. /**
  809. * Ensure associations use the plugin-prefixed model
  810. *
  811. * @return void
  812. */
  813. public function testHasManyPluginOverlap()
  814. {
  815. $this->getTableLocator()->get('Comments');
  816. $this->loadPlugins(['TestPlugin']);
  817. $table = new Table(['table' => 'authors']);
  818. $table->hasMany('TestPlugin.Comments');
  819. $comments = $table->Comments->getTarget();
  820. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  821. }
  822. /**
  823. * Ensure associations use the plugin-prefixed model
  824. * even if specified with config
  825. *
  826. * @return void
  827. */
  828. public function testHasManyPluginOverlapConfig()
  829. {
  830. $this->getTableLocator()->get('Comments');
  831. $this->loadPlugins(['TestPlugin']);
  832. $table = new Table(['table' => 'authors']);
  833. $table->hasMany('Comments', ['className' => 'TestPlugin.Comments']);
  834. $comments = $table->Comments->getTarget();
  835. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  836. }
  837. /**
  838. * Tests that BelongsToMany() creates and configures correctly the association
  839. *
  840. * @return void
  841. */
  842. public function testBelongsToMany()
  843. {
  844. $options = [
  845. 'foreignKey' => 'thing_id',
  846. 'joinTable' => 'things_tags',
  847. 'conditions' => ['b' => 'c'],
  848. 'sort' => ['foo' => 'asc'],
  849. ];
  850. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  851. $belongsToMany = $table->belongsToMany('tag', $options);
  852. $this->assertInstanceOf(BelongsToMany::class, $belongsToMany);
  853. $this->assertSame($belongsToMany, $table->getAssociation('tag'));
  854. $this->assertEquals('tag', $belongsToMany->getName());
  855. $this->assertEquals('thing_id', $belongsToMany->getForeignKey());
  856. $this->assertEquals(['b' => 'c'], $belongsToMany->getConditions());
  857. $this->assertEquals(['foo' => 'asc'], $belongsToMany->getSort());
  858. $this->assertSame($table, $belongsToMany->getSource());
  859. $this->assertSame('things_tags', $belongsToMany->junction()->getTable());
  860. }
  861. /**
  862. * Test addAssociations()
  863. *
  864. * @return void
  865. */
  866. public function testAddAssociations()
  867. {
  868. $params = [
  869. 'belongsTo' => [
  870. 'users' => ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']],
  871. ],
  872. 'hasOne' => ['profiles'],
  873. 'hasMany' => ['authors'],
  874. 'belongsToMany' => [
  875. 'tags' => [
  876. 'joinTable' => 'things_tags',
  877. 'conditions' => [
  878. 'Tags.starred' => true,
  879. ],
  880. ],
  881. ],
  882. ];
  883. $table = new Table(['table' => 'dates']);
  884. $result = $table->addAssociations($params);
  885. $this->assertSame($table, $result);
  886. $associations = $table->associations();
  887. $belongsTo = $associations->get('users');
  888. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  889. $this->assertEquals('users', $belongsTo->getName());
  890. $this->assertEquals('fake_id', $belongsTo->getForeignKey());
  891. $this->assertEquals(['a' => 'b'], $belongsTo->getConditions());
  892. $this->assertSame($table, $belongsTo->getSource());
  893. $hasOne = $associations->get('profiles');
  894. $this->assertInstanceOf(HasOne::class, $hasOne);
  895. $this->assertEquals('profiles', $hasOne->getName());
  896. $hasMany = $associations->get('authors');
  897. $this->assertInstanceOf(HasMany::class, $hasMany);
  898. $this->assertEquals('authors', $hasMany->getName());
  899. $belongsToMany = $associations->get('tags');
  900. $this->assertInstanceOf(BelongsToMany::class, $belongsToMany);
  901. $this->assertEquals('tags', $belongsToMany->getName());
  902. $this->assertSame('things_tags', $belongsToMany->junction()->getTable());
  903. $this->assertSame(['Tags.starred' => true], $belongsToMany->getConditions());
  904. }
  905. /**
  906. * Test basic multi row updates.
  907. *
  908. * @return void
  909. */
  910. public function testUpdateAll()
  911. {
  912. $table = new Table([
  913. 'table' => 'users',
  914. 'connection' => $this->connection,
  915. ]);
  916. $fields = ['username' => 'mark'];
  917. $result = $table->updateAll($fields, ['id <' => 4]);
  918. $this->assertSame(3, $result);
  919. $result = $table->find('all')
  920. ->select(['username'])
  921. ->order(['id' => 'asc'])
  922. ->enableHydration(false)
  923. ->toArray();
  924. $expected = array_fill(0, 3, $fields);
  925. $expected[] = ['username' => 'garrett'];
  926. $this->assertEquals($expected, $result);
  927. }
  928. /**
  929. * Test that exceptions from the Query bubble up.
  930. */
  931. public function testUpdateAllFailure()
  932. {
  933. $this->expectException(\Cake\Database\Exception::class);
  934. $table = $this->getMockBuilder('Cake\ORM\Table')
  935. ->setMethods(['query'])
  936. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  937. ->getMock();
  938. $query = $this->getMockBuilder('Cake\ORM\Query')
  939. ->setMethods(['execute'])
  940. ->setConstructorArgs([$this->connection, $table])
  941. ->getMock();
  942. $table->expects($this->once())
  943. ->method('query')
  944. ->will($this->returnValue($query));
  945. $query->expects($this->once())
  946. ->method('execute')
  947. ->will($this->throwException(new Exception('Not good')));
  948. $table->updateAll(['username' => 'mark'], []);
  949. }
  950. /**
  951. * Test deleting many records.
  952. *
  953. * @return void
  954. */
  955. public function testDeleteAll()
  956. {
  957. $table = new Table([
  958. 'table' => 'users',
  959. 'connection' => $this->connection,
  960. ]);
  961. $result = $table->deleteAll(['id <' => 4]);
  962. $this->assertSame(3, $result);
  963. $result = $table->find('all')->toArray();
  964. $this->assertCount(1, $result, 'Only one record should remain');
  965. $this->assertEquals(4, $result[0]['id']);
  966. }
  967. /**
  968. * Test deleting many records with conditions using the alias
  969. *
  970. * @return void
  971. */
  972. public function testDeleteAllAliasedConditions()
  973. {
  974. $table = new Table([
  975. 'table' => 'users',
  976. 'alias' => 'Managers',
  977. 'connection' => $this->connection,
  978. ]);
  979. $result = $table->deleteAll(['Managers.id <' => 4]);
  980. $this->assertSame(3, $result);
  981. $result = $table->find('all')->toArray();
  982. $this->assertCount(1, $result, 'Only one record should remain');
  983. $this->assertEquals(4, $result[0]['id']);
  984. }
  985. /**
  986. * Test that exceptions from the Query bubble up.
  987. */
  988. public function testDeleteAllFailure()
  989. {
  990. $this->expectException(\Cake\Database\Exception::class);
  991. $table = $this->getMockBuilder('Cake\ORM\Table')
  992. ->setMethods(['query'])
  993. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  994. ->getMock();
  995. $query = $this->getMockBuilder('Cake\ORM\Query')
  996. ->setMethods(['execute'])
  997. ->setConstructorArgs([$this->connection, $table])
  998. ->getMock();
  999. $table->expects($this->once())
  1000. ->method('query')
  1001. ->will($this->returnValue($query));
  1002. $query->expects($this->once())
  1003. ->method('execute')
  1004. ->will($this->throwException(new Exception('Not good')));
  1005. $table->deleteAll(['id >' => 4]);
  1006. }
  1007. /**
  1008. * Tests that array options are passed to the query object using applyOptions
  1009. *
  1010. * @return void
  1011. */
  1012. public function testFindApplyOptions()
  1013. {
  1014. $table = $this->getMockBuilder('Cake\ORM\Table')
  1015. ->setMethods(['query', 'findAll'])
  1016. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  1017. ->getMock();
  1018. $query = $this->getMockBuilder('Cake\ORM\Query')
  1019. ->setConstructorArgs([$this->connection, $table])
  1020. ->getMock();
  1021. $table->expects($this->once())
  1022. ->method('query')
  1023. ->will($this->returnValue($query));
  1024. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  1025. $query->expects($this->any())
  1026. ->method('select')
  1027. ->will($this->returnSelf());
  1028. $query->expects($this->once())->method('getOptions')
  1029. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  1030. $query->expects($this->once())
  1031. ->method('applyOptions')
  1032. ->with($options);
  1033. $table->expects($this->once())->method('findAll')
  1034. ->with($query, ['connections' => ['a >' => 1]]);
  1035. $table->find('all', $options);
  1036. }
  1037. /**
  1038. * Tests find('list')
  1039. *
  1040. * @return void
  1041. */
  1042. public function testFindListNoHydration()
  1043. {
  1044. $table = new Table([
  1045. 'table' => 'users',
  1046. 'connection' => $this->connection,
  1047. ]);
  1048. $table->setDisplayField('username');
  1049. $query = $table->find('list')
  1050. ->enableHydration(false)
  1051. ->order('id');
  1052. $expected = [
  1053. 1 => 'mariano',
  1054. 2 => 'nate',
  1055. 3 => 'larry',
  1056. 4 => 'garrett',
  1057. ];
  1058. $this->assertSame($expected, $query->toArray());
  1059. $query = $table->find('list', ['fields' => ['id', 'username']])
  1060. ->enableHydration(false)
  1061. ->order('id');
  1062. $expected = [
  1063. 1 => 'mariano',
  1064. 2 => 'nate',
  1065. 3 => 'larry',
  1066. 4 => 'garrett',
  1067. ];
  1068. $this->assertSame($expected, $query->toArray());
  1069. $query = $table->find('list', ['groupField' => 'odd'])
  1070. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  1071. ->enableHydration(false)
  1072. ->order('id');
  1073. $expected = [
  1074. 1 => [
  1075. 1 => 'mariano',
  1076. 3 => 'larry',
  1077. ],
  1078. 0 => [
  1079. 2 => 'nate',
  1080. 4 => 'garrett',
  1081. ],
  1082. ];
  1083. $this->assertSame($expected, $query->toArray());
  1084. }
  1085. /**
  1086. * Tests find('threaded')
  1087. *
  1088. * @return void
  1089. */
  1090. public function testFindThreadedNoHydration()
  1091. {
  1092. $table = new Table([
  1093. 'table' => 'categories',
  1094. 'connection' => $this->connection,
  1095. ]);
  1096. $expected = [
  1097. [
  1098. 'id' => 1,
  1099. 'parent_id' => 0,
  1100. 'name' => 'Category 1',
  1101. 'children' => [
  1102. [
  1103. 'id' => 2,
  1104. 'parent_id' => 1,
  1105. 'name' => 'Category 1.1',
  1106. 'children' => [
  1107. [
  1108. 'id' => 7,
  1109. 'parent_id' => 2,
  1110. 'name' => 'Category 1.1.1',
  1111. 'children' => [],
  1112. ],
  1113. [
  1114. 'id' => 8,
  1115. 'parent_id' => '2',
  1116. 'name' => 'Category 1.1.2',
  1117. 'children' => [],
  1118. ],
  1119. ],
  1120. ],
  1121. [
  1122. 'id' => 3,
  1123. 'parent_id' => '1',
  1124. 'name' => 'Category 1.2',
  1125. 'children' => [],
  1126. ],
  1127. ],
  1128. ],
  1129. [
  1130. 'id' => 4,
  1131. 'parent_id' => 0,
  1132. 'name' => 'Category 2',
  1133. 'children' => [],
  1134. ],
  1135. [
  1136. 'id' => 5,
  1137. 'parent_id' => 0,
  1138. 'name' => 'Category 3',
  1139. 'children' => [
  1140. [
  1141. 'id' => '6',
  1142. 'parent_id' => '5',
  1143. 'name' => 'Category 3.1',
  1144. 'children' => [],
  1145. ],
  1146. ],
  1147. ],
  1148. ];
  1149. $results = $table->find('all')
  1150. ->select(['id', 'parent_id', 'name'])
  1151. ->enableHydration(false)
  1152. ->find('threaded')
  1153. ->toArray();
  1154. $this->assertEquals($expected, $results);
  1155. }
  1156. /**
  1157. * Tests that finders can be stacked
  1158. *
  1159. * @return void
  1160. */
  1161. public function testStackingFinders()
  1162. {
  1163. $table = $this->getMockBuilder('\Cake\ORM\Table')
  1164. ->setMethods(['find', 'findList'])
  1165. ->disableOriginalConstructor()
  1166. ->getMock();
  1167. $params = [$this->connection, $table];
  1168. $query = $this->getMockBuilder('\Cake\ORM\Query')
  1169. ->setMethods(['addDefaultTypes'])
  1170. ->setConstructorArgs($params)
  1171. ->getMock();
  1172. $table->expects($this->once())
  1173. ->method('find')
  1174. ->with('threaded', ['order' => ['name' => 'ASC']])
  1175. ->will($this->returnValue($query));
  1176. $table->expects($this->once())
  1177. ->method('findList')
  1178. ->with($query, ['keyPath' => 'id'])
  1179. ->will($this->returnValue($query));
  1180. $result = $table
  1181. ->find('threaded', ['order' => ['name' => 'ASC']])
  1182. ->find('list', ['keyPath' => 'id']);
  1183. $this->assertSame($query, $result);
  1184. }
  1185. /**
  1186. * Tests find('threaded') with hydrated results
  1187. *
  1188. * @return void
  1189. */
  1190. public function testFindThreadedHydrated()
  1191. {
  1192. $table = new Table([
  1193. 'table' => 'categories',
  1194. 'connection' => $this->connection,
  1195. ]);
  1196. $results = $table->find('all')
  1197. ->find('threaded')
  1198. ->select(['id', 'parent_id', 'name'])
  1199. ->toArray();
  1200. $this->assertEquals(1, $results[0]->id);
  1201. $expected = [
  1202. 'id' => 8,
  1203. 'parent_id' => 2,
  1204. 'name' => 'Category 1.1.2',
  1205. 'children' => [],
  1206. ];
  1207. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  1208. }
  1209. /**
  1210. * Tests find('list') with hydrated records
  1211. *
  1212. * @return void
  1213. */
  1214. public function testFindListHydrated()
  1215. {
  1216. $table = new Table([
  1217. 'table' => 'users',
  1218. 'connection' => $this->connection,
  1219. ]);
  1220. $table->setDisplayField('username');
  1221. $query = $table
  1222. ->find('list', ['fields' => ['id', 'username']])
  1223. ->order('id');
  1224. $expected = [
  1225. 1 => 'mariano',
  1226. 2 => 'nate',
  1227. 3 => 'larry',
  1228. 4 => 'garrett',
  1229. ];
  1230. $this->assertSame($expected, $query->toArray());
  1231. $query = $table->find('list', ['groupField' => 'odd'])
  1232. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  1233. ->enableHydration(true)
  1234. ->order('id');
  1235. $expected = [
  1236. 1 => [
  1237. 1 => 'mariano',
  1238. 3 => 'larry',
  1239. ],
  1240. 0 => [
  1241. 2 => 'nate',
  1242. 4 => 'garrett',
  1243. ],
  1244. ];
  1245. $this->assertSame($expected, $query->toArray());
  1246. }
  1247. /**
  1248. * Test that find('list') only selects required fields.
  1249. *
  1250. * @return void
  1251. */
  1252. public function testFindListSelectedFields()
  1253. {
  1254. $table = new Table([
  1255. 'table' => 'users',
  1256. 'connection' => $this->connection,
  1257. ]);
  1258. $table->setDisplayField('username');
  1259. $query = $table->find('list');
  1260. $expected = ['id', 'username'];
  1261. $this->assertSame($expected, $query->clause('select'));
  1262. $query = $table->find('list', ['valueField' => function ($row) {
  1263. return $row->username;
  1264. }]);
  1265. $this->assertEmpty($query->clause('select'));
  1266. $expected = ['odd' => new QueryExpression('id % 2'), 'id', 'username'];
  1267. $query = $table->find('list', [
  1268. 'fields' => $expected,
  1269. 'groupField' => 'odd',
  1270. ]);
  1271. $this->assertSame($expected, $query->clause('select'));
  1272. $articles = new Table([
  1273. 'table' => 'articles',
  1274. 'connection' => $this->connection,
  1275. ]);
  1276. $query = $articles->find('list', ['groupField' => 'author_id']);
  1277. $expected = ['id', 'title', 'author_id'];
  1278. $this->assertSame($expected, $query->clause('select'));
  1279. $query = $articles->find('list', ['valueField' => ['author_id', 'title']])
  1280. ->order('id');
  1281. $expected = ['id', 'author_id', 'title'];
  1282. $this->assertSame($expected, $query->clause('select'));
  1283. $expected = [
  1284. 1 => '1;First Article',
  1285. 2 => '3;Second Article',
  1286. 3 => '1;Third Article',
  1287. ];
  1288. $this->assertSame($expected, $query->toArray());
  1289. }
  1290. /**
  1291. * test that find('list') does not auto add fields to select if using virtual properties
  1292. *
  1293. * @return void
  1294. */
  1295. public function testFindListWithVirtualField()
  1296. {
  1297. $table = new Table([
  1298. 'table' => 'users',
  1299. 'connection' => $this->connection,
  1300. 'entityClass' => '\TestApp\Model\Entity\VirtualUser',
  1301. ]);
  1302. $table->setDisplayField('bonus');
  1303. $query = $table
  1304. ->find('list')
  1305. ->order('id');
  1306. $this->assertEmpty($query->clause('select'));
  1307. $expected = [
  1308. 1 => 'bonus',
  1309. 2 => 'bonus',
  1310. 3 => 'bonus',
  1311. 4 => 'bonus',
  1312. ];
  1313. $this->assertSame($expected, $query->toArray());
  1314. $query = $table->find('list', ['groupField' => 'odd']);
  1315. $this->assertEmpty($query->clause('select'));
  1316. }
  1317. /**
  1318. * Test find('list') with value field from associated table
  1319. *
  1320. * @return void
  1321. */
  1322. public function testFindListWithAssociatedTable()
  1323. {
  1324. $articles = new Table([
  1325. 'table' => 'articles',
  1326. 'connection' => $this->connection,
  1327. ]);
  1328. $articles->belongsTo('Authors');
  1329. $query = $articles->find('list', ['valueField' => 'author.name'])
  1330. ->contain(['Authors'])
  1331. ->order('articles.id');
  1332. $this->assertEmpty($query->clause('select'));
  1333. $expected = [
  1334. 1 => 'mariano',
  1335. 2 => 'larry',
  1336. 3 => 'mariano',
  1337. ];
  1338. $this->assertSame($expected, $query->toArray());
  1339. }
  1340. /**
  1341. * Test the default entityClass.
  1342. *
  1343. * @return void
  1344. */
  1345. public function testEntityClassDefault()
  1346. {
  1347. $table = new Table();
  1348. $this->assertEquals('Cake\ORM\Entity', $table->getEntityClass());
  1349. }
  1350. /**
  1351. * Tests that using a simple string for entityClass will try to
  1352. * load the class from the App namespace
  1353. *
  1354. * @return void
  1355. */
  1356. public function testTableClassInApp()
  1357. {
  1358. $class = $this->getMockClass('\Cake\ORM\Entity');
  1359. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  1360. class_alias($class, 'TestApp\Model\Entity\TestUser');
  1361. }
  1362. $table = new Table();
  1363. $this->assertSame($table, $table->setEntityClass('TestUser'));
  1364. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->getEntityClass());
  1365. }
  1366. /**
  1367. * Test that entity class inflection works for compound nouns
  1368. *
  1369. * @return void
  1370. */
  1371. public function testEntityClassInflection()
  1372. {
  1373. $class = $this->getMockClass('\Cake\ORM\Entity');
  1374. if (!class_exists('TestApp\Model\Entity\CustomCookie')) {
  1375. class_alias($class, 'TestApp\Model\Entity\CustomCookie');
  1376. }
  1377. $table = $this->getTableLocator()->get('CustomCookies');
  1378. $this->assertEquals('TestApp\Model\Entity\CustomCookie', $table->getEntityClass());
  1379. if (!class_exists('TestApp\Model\Entity\Address')) {
  1380. class_alias($class, 'TestApp\Model\Entity\Address');
  1381. }
  1382. $table = $this->getTableLocator()->get('Addresses');
  1383. $this->assertEquals('TestApp\Model\Entity\Address', $table->getEntityClass());
  1384. }
  1385. /**
  1386. * Tests that using a simple string for entityClass will try to
  1387. * load the class from the Plugin namespace when using plugin notation
  1388. *
  1389. * @return void
  1390. */
  1391. public function testTableClassInPlugin()
  1392. {
  1393. $class = $this->getMockClass('\Cake\ORM\Entity');
  1394. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  1395. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  1396. }
  1397. $table = new Table();
  1398. $this->assertSame($table, $table->setEntityClass('MyPlugin.SuperUser'));
  1399. $this->assertEquals(
  1400. 'MyPlugin\Model\Entity\SuperUser',
  1401. $table->getEntityClass()
  1402. );
  1403. }
  1404. /**
  1405. * Tests that using a simple string for entityClass will throw an exception
  1406. * when the class does not exist in the namespace
  1407. *
  1408. * @return void
  1409. */
  1410. public function testTableClassNonExisting()
  1411. {
  1412. $this->expectException(\Cake\ORM\Exception\MissingEntityException::class);
  1413. $this->expectExceptionMessage('Entity class FooUser could not be found.');
  1414. $table = new Table();
  1415. $table->setEntityClass('FooUser');
  1416. }
  1417. /**
  1418. * Tests getting the entityClass based on conventions for the entity
  1419. * namespace
  1420. *
  1421. * @return void
  1422. */
  1423. public function testTableClassConventionForAPP()
  1424. {
  1425. $table = new \TestApp\Model\Table\ArticlesTable();
  1426. $this->assertEquals('TestApp\Model\Entity\Article', $table->getEntityClass());
  1427. }
  1428. /**
  1429. * Tests setting a entity class object using the setter method
  1430. *
  1431. * @group deprecated
  1432. * @return void
  1433. */
  1434. public function testEntityClass()
  1435. {
  1436. $this->deprecated(function () {
  1437. $table = new Table();
  1438. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  1439. $table->entityClass($class);
  1440. $this->assertEquals($class, $table->getEntityClass());
  1441. });
  1442. }
  1443. /**
  1444. * Tests setting a entity class object using the setter method
  1445. *
  1446. * @return void
  1447. */
  1448. public function testSetEntityClass()
  1449. {
  1450. $table = new Table();
  1451. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  1452. $this->assertSame($table, $table->setEntityClass($class));
  1453. $this->assertEquals($class, $table->getEntityClass());
  1454. }
  1455. /**
  1456. * Proves that associations, even though they are lazy loaded, will fetch
  1457. * records using the correct table class and hydrate with the correct entity
  1458. *
  1459. * @return void
  1460. */
  1461. public function testReciprocalBelongsToLoading()
  1462. {
  1463. $table = new \TestApp\Model\Table\ArticlesTable([
  1464. 'connection' => $this->connection,
  1465. ]);
  1466. $result = $table->find('all')->contain(['Authors'])->first();
  1467. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  1468. }
  1469. /**
  1470. * Proves that associations, even though they are lazy loaded, will fetch
  1471. * records using the correct table class and hydrate with the correct entity
  1472. *
  1473. * @return void
  1474. */
  1475. public function testReciprocalHasManyLoading()
  1476. {
  1477. $table = new \TestApp\Model\Table\ArticlesTable([
  1478. 'connection' => $this->connection,
  1479. ]);
  1480. $result = $table->find('all')->contain(['Authors' => ['Articles']])->first();
  1481. $this->assertCount(2, $result->author->articles);
  1482. foreach ($result->author->articles as $article) {
  1483. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  1484. }
  1485. }
  1486. /**
  1487. * Tests that the correct table and entity are loaded for the join association in
  1488. * a belongsToMany setup
  1489. *
  1490. * @return void
  1491. */
  1492. public function testReciprocalBelongsToMany()
  1493. {
  1494. $table = new \TestApp\Model\Table\ArticlesTable([
  1495. 'connection' => $this->connection,
  1496. ]);
  1497. $result = $table->find('all')->contain(['Tags'])->first();
  1498. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  1499. $this->assertInstanceOf(
  1500. 'TestApp\Model\Entity\ArticlesTag',
  1501. $result->tags[0]->_joinData
  1502. );
  1503. }
  1504. /**
  1505. * Tests that recently fetched entities are always clean
  1506. *
  1507. * @return void
  1508. */
  1509. public function testFindCleanEntities()
  1510. {
  1511. $table = new \TestApp\Model\Table\ArticlesTable([
  1512. 'connection' => $this->connection,
  1513. ]);
  1514. $results = $table->find('all')->contain(['Tags', 'Authors'])->toArray();
  1515. $this->assertCount(3, $results);
  1516. foreach ($results as $article) {
  1517. $this->assertFalse($article->isDirty('id'));
  1518. $this->assertFalse($article->isDirty('title'));
  1519. $this->assertFalse($article->isDirty('author_id'));
  1520. $this->assertFalse($article->isDirty('body'));
  1521. $this->assertFalse($article->isDirty('published'));
  1522. $this->assertFalse($article->isDirty('author'));
  1523. $this->assertFalse($article->author->isDirty('id'));
  1524. $this->assertFalse($article->author->isDirty('name'));
  1525. $this->assertFalse($article->isDirty('tag'));
  1526. if ($article->tag) {
  1527. $this->assertFalse($article->tag[0]->_joinData->isDirty('tag_id'));
  1528. }
  1529. }
  1530. }
  1531. /**
  1532. * Tests that recently fetched entities are marked as not new
  1533. *
  1534. * @return void
  1535. */
  1536. public function testFindPersistedEntities()
  1537. {
  1538. $table = new \TestApp\Model\Table\ArticlesTable([
  1539. 'connection' => $this->connection,
  1540. ]);
  1541. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1542. $this->assertCount(3, $results);
  1543. foreach ($results as $article) {
  1544. $this->assertFalse($article->isNew());
  1545. foreach ((array)$article->tag as $tag) {
  1546. $this->assertFalse($tag->isNew());
  1547. $this->assertFalse($tag->_joinData->isNew());
  1548. }
  1549. }
  1550. }
  1551. /**
  1552. * Tests the exists function
  1553. *
  1554. * @return void
  1555. */
  1556. public function testExists()
  1557. {
  1558. $table = $this->getTableLocator()->get('users');
  1559. $this->assertTrue($table->exists(['id' => 1]));
  1560. $this->assertFalse($table->exists(['id' => 501]));
  1561. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  1562. }
  1563. /**
  1564. * Test adding a behavior to a table.
  1565. *
  1566. * @return void
  1567. */
  1568. public function testAddBehavior()
  1569. {
  1570. $mock = $this->getMockBuilder('Cake\ORM\BehaviorRegistry')
  1571. ->disableOriginalConstructor()
  1572. ->getMock();
  1573. $mock->expects($this->once())
  1574. ->method('load')
  1575. ->with('Sluggable');
  1576. $table = new Table([
  1577. 'table' => 'articles',
  1578. 'behaviors' => $mock,
  1579. ]);
  1580. $result = $table->addBehavior('Sluggable');
  1581. $this->assertSame($table, $result);
  1582. }
  1583. /**
  1584. * Test adding a behavior that is a duplicate.
  1585. *
  1586. * @return void
  1587. */
  1588. public function testAddBehaviorDuplicate()
  1589. {
  1590. $table = new Table(['table' => 'articles']);
  1591. $this->assertSame($table, $table->addBehavior('Sluggable', ['test' => 'value']));
  1592. $this->assertSame($table, $table->addBehavior('Sluggable', ['test' => 'value']));
  1593. try {
  1594. $table->addBehavior('Sluggable', ['thing' => 'thing']);
  1595. $this->fail('No exception raised');
  1596. } catch (\RuntimeException $e) {
  1597. $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage());
  1598. }
  1599. }
  1600. /**
  1601. * Test removing a behavior from a table.
  1602. *
  1603. * @return void
  1604. */
  1605. public function testRemoveBehavior()
  1606. {
  1607. $mock = $this->getMockBuilder('Cake\ORM\BehaviorRegistry')
  1608. ->disableOriginalConstructor()
  1609. ->getMock();
  1610. $mock->expects($this->once())
  1611. ->method('unload')
  1612. ->with('Sluggable');
  1613. $table = new Table([
  1614. 'table' => 'articles',
  1615. 'behaviors' => $mock,
  1616. ]);
  1617. $result = $table->removeBehavior('Sluggable');
  1618. $this->assertSame($table, $result);
  1619. }
  1620. /**
  1621. * Test adding multiple behaviors to a table.
  1622. *
  1623. * @return void
  1624. */
  1625. public function testAddBehaviors()
  1626. {
  1627. $table = new Table(['table' => 'comments']);
  1628. $behaviors = [
  1629. 'Sluggable',
  1630. 'Timestamp' => [
  1631. 'events' => [
  1632. 'Model.beforeSave' => [
  1633. 'created' => 'new',
  1634. 'updated' => 'always',
  1635. ],
  1636. ],
  1637. ],
  1638. ];
  1639. $this->assertSame($table, $table->addBehaviors($behaviors));
  1640. $this->assertTrue($table->behaviors()->has('Sluggable'));
  1641. $this->assertTrue($table->behaviors()->has('Timestamp'));
  1642. $this->assertSame(
  1643. $behaviors['Timestamp']['events'],
  1644. $table->behaviors()->get('Timestamp')->getConfig('events')
  1645. );
  1646. }
  1647. /**
  1648. * Test getting a behavior instance from a table.
  1649. *
  1650. * @return void
  1651. */
  1652. public function testBehaviors()
  1653. {
  1654. $table = $this->getTableLocator()->get('article');
  1655. $result = $table->behaviors();
  1656. $this->assertInstanceOf('Cake\ORM\BehaviorRegistry', $result);
  1657. }
  1658. /**
  1659. * Test that the getBehavior() method retrieves a behavior from the table registry.
  1660. *
  1661. * @return void
  1662. */
  1663. public function testGetBehavior()
  1664. {
  1665. $table = new Table(['table' => 'comments']);
  1666. $table->addBehavior('Sluggable');
  1667. $this->assertSame($table->behaviors()->get('Sluggable'), $table->getBehavior('Sluggable'));
  1668. }
  1669. /**
  1670. * Test that the getBehavior() method will throw an exception when you try to
  1671. * get a behavior that does not exist.
  1672. *
  1673. * @return void
  1674. */
  1675. public function testGetBehaviorThrowsExceptionForMissingBehavior()
  1676. {
  1677. $table = new Table(['table' => 'comments']);
  1678. $this->expectException(InvalidArgumentException::class);
  1679. $this->expectExceptionMessage('The Sluggable behavior is not defined on ' . get_class($table) . '.');
  1680. $this->assertFalse($table->hasBehavior('Sluggable'));
  1681. $table->getBehavior('Sluggable');
  1682. }
  1683. /**
  1684. * Ensure exceptions are raised on missing behaviors.
  1685. */
  1686. public function testAddBehaviorMissing()
  1687. {
  1688. $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class);
  1689. $table = $this->getTableLocator()->get('article');
  1690. $this->assertNull($table->addBehavior('NopeNotThere'));
  1691. }
  1692. /**
  1693. * Test mixin methods from behaviors.
  1694. *
  1695. * @return void
  1696. */
  1697. public function testCallBehaviorMethod()
  1698. {
  1699. $table = $this->getTableLocator()->get('article');
  1700. $table->addBehavior('Sluggable');
  1701. $this->assertEquals('some-value', $table->slugify('some value'));
  1702. }
  1703. /**
  1704. * Test you can alias a behavior method
  1705. *
  1706. * @return void
  1707. */
  1708. public function testCallBehaviorAliasedMethod()
  1709. {
  1710. $table = $this->getTableLocator()->get('article');
  1711. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  1712. $this->assertEquals('some-value', $table->wednesday('some value'));
  1713. }
  1714. /**
  1715. * Test finder methods from behaviors.
  1716. *
  1717. * @return void
  1718. */
  1719. public function testCallBehaviorFinder()
  1720. {
  1721. $table = $this->getTableLocator()->get('articles');
  1722. $table->addBehavior('Sluggable');
  1723. $query = $table->find('noSlug');
  1724. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1725. $this->assertNotEmpty($query->clause('where'));
  1726. }
  1727. /**
  1728. * testCallBehaviorAliasedFinder
  1729. *
  1730. * @return void
  1731. */
  1732. public function testCallBehaviorAliasedFinder()
  1733. {
  1734. $table = $this->getTableLocator()->get('articles');
  1735. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  1736. $query = $table->find('special');
  1737. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1738. $this->assertNotEmpty($query->clause('where'));
  1739. }
  1740. /**
  1741. * Test implementedEvents
  1742. *
  1743. * @return void
  1744. */
  1745. public function testImplementedEvents()
  1746. {
  1747. $table = $this->getMockBuilder('Cake\ORM\Table')
  1748. ->setMethods([
  1749. 'buildValidator',
  1750. 'beforeMarshal',
  1751. 'beforeFind',
  1752. 'beforeSave',
  1753. 'afterSave',
  1754. 'beforeDelete',
  1755. 'afterDelete',
  1756. 'afterRules',
  1757. ])
  1758. ->getMock();
  1759. $result = $table->implementedEvents();
  1760. $expected = [
  1761. 'Model.beforeMarshal' => 'beforeMarshal',
  1762. 'Model.buildValidator' => 'buildValidator',
  1763. 'Model.beforeFind' => 'beforeFind',
  1764. 'Model.beforeSave' => 'beforeSave',
  1765. 'Model.afterSave' => 'afterSave',
  1766. 'Model.beforeDelete' => 'beforeDelete',
  1767. 'Model.afterDelete' => 'afterDelete',
  1768. 'Model.afterRules' => 'afterRules',
  1769. ];
  1770. $this->assertEquals($expected, $result, 'Events do not match.');
  1771. }
  1772. /**
  1773. * Tests that it is possible to insert a new row using the save method
  1774. *
  1775. * @group save
  1776. * @return void
  1777. */
  1778. public function testSaveNewEntity()
  1779. {
  1780. $entity = new Entity([
  1781. 'username' => 'superuser',
  1782. 'password' => 'root',
  1783. 'created' => new Time('2013-10-10 00:00'),
  1784. 'updated' => new Time('2013-10-10 00:00'),
  1785. ]);
  1786. $table = $this->getTableLocator()->get('users');
  1787. $this->assertSame($entity, $table->save($entity));
  1788. $this->assertEquals($entity->id, self::$nextUserId);
  1789. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1790. $this->assertEquals($entity->toArray(), $row->toArray());
  1791. }
  1792. /**
  1793. * Test that saving a new empty entity does nothing.
  1794. *
  1795. * @group save
  1796. * @return void
  1797. */
  1798. public function testSaveNewEmptyEntity()
  1799. {
  1800. $entity = new Entity();
  1801. $table = $this->getTableLocator()->get('users');
  1802. $this->assertFalse($table->save($entity));
  1803. }
  1804. /**
  1805. * Test that saving a new empty entity does not call exists.
  1806. *
  1807. * @group save
  1808. * @return void
  1809. */
  1810. public function testSaveNewEntityNoExists()
  1811. {
  1812. $table = $this->getMockBuilder('Cake\ORM\Table')
  1813. ->setMethods(['exists'])
  1814. ->setConstructorArgs([[
  1815. 'connection' => $this->connection,
  1816. 'alias' => 'Users',
  1817. 'table' => 'users',
  1818. ]])
  1819. ->getMock();
  1820. $entity = $table->newEntity(['username' => 'mark']);
  1821. $this->assertTrue($entity->isNew());
  1822. $table->expects($this->never())
  1823. ->method('exists');
  1824. $this->assertSame($entity, $table->save($entity));
  1825. }
  1826. /**
  1827. * Test that saving a new entity with a Primary Key set does call exists.
  1828. *
  1829. * @group save
  1830. * @return void
  1831. */
  1832. public function testSavePrimaryKeyEntityExists()
  1833. {
  1834. $this->skipIfSqlServer();
  1835. $table = $this->getMockBuilder('Cake\ORM\Table')
  1836. ->setMethods(['exists'])
  1837. ->setConstructorArgs([[
  1838. 'connection' => $this->connection,
  1839. 'alias' => 'Users',
  1840. 'table' => 'users',
  1841. ]])
  1842. ->getMock();
  1843. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1844. $this->assertTrue($entity->isNew());
  1845. $table->expects($this->once())->method('exists');
  1846. $this->assertSame($entity, $table->save($entity));
  1847. }
  1848. /**
  1849. * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false.
  1850. *
  1851. * @group save
  1852. * @return void
  1853. */
  1854. public function testSavePrimaryKeyEntityNoExists()
  1855. {
  1856. $this->skipIfSqlServer();
  1857. $table = $this->getMockBuilder('Cake\ORM\Table')
  1858. ->setMethods(['exists'])
  1859. ->setConstructorArgs([[
  1860. 'connection' => $this->connection,
  1861. 'alias' => 'Users',
  1862. 'table' => 'users',
  1863. ]])
  1864. ->getMock();
  1865. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1866. $this->assertTrue($entity->isNew());
  1867. $table->expects($this->never())->method('exists');
  1868. $this->assertSame($entity, $table->save($entity, ['checkExisting' => false]));
  1869. }
  1870. /**
  1871. * Tests that saving an entity will filter out properties that
  1872. * are not present in the table schema when saving
  1873. *
  1874. * @group save
  1875. * @return void
  1876. */
  1877. public function testSaveEntityOnlySchemaFields()
  1878. {
  1879. $entity = new Entity([
  1880. 'username' => 'superuser',
  1881. 'password' => 'root',
  1882. 'crazyness' => 'super crazy value',
  1883. 'created' => new Time('2013-10-10 00:00'),
  1884. 'updated' => new Time('2013-10-10 00:00'),
  1885. ]);
  1886. $table = $this->getTableLocator()->get('users');
  1887. $this->assertSame($entity, $table->save($entity));
  1888. $this->assertEquals($entity->id, self::$nextUserId);
  1889. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1890. $entity->unsetProperty('crazyness');
  1891. $this->assertEquals($entity->toArray(), $row->toArray());
  1892. }
  1893. /**
  1894. * Tests that it is possible to modify data from the beforeSave callback
  1895. *
  1896. * @group save
  1897. * @return void
  1898. */
  1899. public function testBeforeSaveModifyData()
  1900. {
  1901. $table = $this->getTableLocator()->get('users');
  1902. $data = new Entity([
  1903. 'username' => 'superuser',
  1904. 'created' => new Time('2013-10-10 00:00'),
  1905. 'updated' => new Time('2013-10-10 00:00'),
  1906. ]);
  1907. $listener = function ($e, $entity, $options) use ($data) {
  1908. $this->assertSame($data, $entity);
  1909. $entity->set('password', 'foo');
  1910. };
  1911. $table->getEventManager()->on('Model.beforeSave', $listener);
  1912. $this->assertSame($data, $table->save($data));
  1913. $this->assertEquals($data->id, self::$nextUserId);
  1914. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1915. $this->assertEquals('foo', $row->get('password'));
  1916. }
  1917. /**
  1918. * Tests that it is possible to modify the options array in beforeSave
  1919. *
  1920. * @group save
  1921. * @return void
  1922. */
  1923. public function testBeforeSaveModifyOptions()
  1924. {
  1925. $table = $this->getTableLocator()->get('users');
  1926. $data = new Entity([
  1927. 'username' => 'superuser',
  1928. 'password' => 'foo',
  1929. 'created' => new Time('2013-10-10 00:00'),
  1930. 'updated' => new Time('2013-10-10 00:00'),
  1931. ]);
  1932. $listener1 = function ($e, $entity, $options) {
  1933. $options['crazy'] = true;
  1934. };
  1935. $listener2 = function ($e, $entity, $options) {
  1936. $this->assertTrue($options['crazy']);
  1937. };
  1938. $table->getEventManager()->on('Model.beforeSave', $listener1);
  1939. $table->getEventManager()->on('Model.beforeSave', $listener2);
  1940. $this->assertSame($data, $table->save($data));
  1941. $this->assertEquals($data->id, self::$nextUserId);
  1942. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1943. $this->assertEquals($data->toArray(), $row->toArray());
  1944. }
  1945. /**
  1946. * Tests that it is possible to stop the saving altogether, without implying
  1947. * the save operation failed
  1948. *
  1949. * @group save
  1950. * @return void
  1951. */
  1952. public function testBeforeSaveStopEvent()
  1953. {
  1954. $table = $this->getTableLocator()->get('users');
  1955. $data = new Entity([
  1956. 'username' => 'superuser',
  1957. 'created' => new Time('2013-10-10 00:00'),
  1958. 'updated' => new Time('2013-10-10 00:00'),
  1959. ]);
  1960. $listener = function ($e, $entity) {
  1961. $e->stopPropagation();
  1962. return $entity;
  1963. };
  1964. $table->getEventManager()->on('Model.beforeSave', $listener);
  1965. $this->assertSame($data, $table->save($data));
  1966. $this->assertNull($data->id);
  1967. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1968. $this->assertNull($row);
  1969. }
  1970. /**
  1971. * Asserts that afterSave callback is called on successful save
  1972. *
  1973. * @group save
  1974. * @return void
  1975. */
  1976. public function testAfterSave()
  1977. {
  1978. $table = $this->getTableLocator()->get('users');
  1979. $data = $table->get(1);
  1980. $data->username = 'newusername';
  1981. $called = false;
  1982. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1983. $this->assertSame($data, $entity);
  1984. $this->assertTrue($entity->isDirty());
  1985. $called = true;
  1986. };
  1987. $table->getEventManager()->on('Model.afterSave', $listener);
  1988. $calledAfterCommit = false;
  1989. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1990. $this->assertSame($data, $entity);
  1991. $this->assertTrue($entity->isDirty());
  1992. $this->assertNotSame($data->get('username'), $data->getOriginal('username'));
  1993. $calledAfterCommit = true;
  1994. };
  1995. $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1996. $this->assertSame($data, $table->save($data));
  1997. $this->assertTrue($called);
  1998. $this->assertTrue($calledAfterCommit);
  1999. }
  2000. /**
  2001. * Asserts that afterSaveCommit is also triggered for non-atomic saves
  2002. *
  2003. * @return void
  2004. */
  2005. public function testAfterSaveCommitForNonAtomic()
  2006. {
  2007. $table = $this->getTableLocator()->get('users');
  2008. $data = new Entity([
  2009. 'username' => 'superuser',
  2010. 'created' => new Time('2013-10-10 00:00'),
  2011. 'updated' => new Time('2013-10-10 00:00'),
  2012. ]);
  2013. $called = false;
  2014. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2015. $this->assertSame($data, $entity);
  2016. $called = true;
  2017. };
  2018. $table->getEventManager()->on('Model.afterSave', $listener);
  2019. $calledAfterCommit = false;
  2020. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2021. $calledAfterCommit = true;
  2022. };
  2023. $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2024. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2025. $this->assertEquals($data->id, self::$nextUserId);
  2026. $this->assertTrue($called);
  2027. $this->assertTrue($calledAfterCommit);
  2028. }
  2029. /**
  2030. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2031. *
  2032. * @return void
  2033. */
  2034. public function testAfterSaveCommitWithTransactionRunning()
  2035. {
  2036. $table = $this->getTableLocator()->get('users');
  2037. $data = new Entity([
  2038. 'username' => 'superuser',
  2039. 'created' => new Time('2013-10-10 00:00'),
  2040. 'updated' => new Time('2013-10-10 00:00'),
  2041. ]);
  2042. $called = false;
  2043. $listener = function ($e, $entity, $options) use (&$called) {
  2044. $called = true;
  2045. };
  2046. $table->getEventManager()->on('Model.afterSaveCommit', $listener);
  2047. $this->connection->begin();
  2048. $this->assertSame($data, $table->save($data));
  2049. $this->assertFalse($called);
  2050. $this->connection->commit();
  2051. }
  2052. /**
  2053. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2054. *
  2055. * @return void
  2056. */
  2057. public function testAfterSaveCommitWithNonAtomicAndTransactionRunning()
  2058. {
  2059. $table = $this->getTableLocator()->get('users');
  2060. $data = new Entity([
  2061. 'username' => 'superuser',
  2062. 'created' => new Time('2013-10-10 00:00'),
  2063. 'updated' => new Time('2013-10-10 00:00'),
  2064. ]);
  2065. $called = false;
  2066. $listener = function ($e, $entity, $options) use (&$called) {
  2067. $called = true;
  2068. };
  2069. $table->getEventManager()->on('Model.afterSaveCommit', $listener);
  2070. $this->connection->begin();
  2071. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2072. $this->assertFalse($called);
  2073. $this->connection->commit();
  2074. }
  2075. /**
  2076. * Asserts that afterSave callback not is called on unsuccessful save
  2077. *
  2078. * @group save
  2079. * @return void
  2080. */
  2081. public function testAfterSaveNotCalled()
  2082. {
  2083. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2084. ->setMethods(['query'])
  2085. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2086. ->getMock();
  2087. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2088. ->setMethods(['execute', 'addDefaultTypes'])
  2089. ->setConstructorArgs([null, $table])
  2090. ->getMock();
  2091. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2092. $data = new Entity([
  2093. 'username' => 'superuser',
  2094. 'created' => new Time('2013-10-10 00:00'),
  2095. 'updated' => new Time('2013-10-10 00:00'),
  2096. ]);
  2097. $table->expects($this->once())->method('query')
  2098. ->will($this->returnValue($query));
  2099. $query->expects($this->once())->method('execute')
  2100. ->will($this->returnValue($statement));
  2101. $statement->expects($this->once())->method('rowCount')
  2102. ->will($this->returnValue(0));
  2103. $called = false;
  2104. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2105. $called = true;
  2106. };
  2107. $table->getEventManager()->on('Model.afterSave', $listener);
  2108. $calledAfterCommit = false;
  2109. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2110. $calledAfterCommit = true;
  2111. };
  2112. $table->getEventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2113. $this->assertFalse($table->save($data));
  2114. $this->assertFalse($called);
  2115. $this->assertFalse($calledAfterCommit);
  2116. }
  2117. /**
  2118. * Asserts that afterSaveCommit callback is triggered only for primary table
  2119. *
  2120. * @group save
  2121. * @return void
  2122. */
  2123. public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
  2124. {
  2125. $entity = new Entity([
  2126. 'title' => 'A Title',
  2127. 'body' => 'A body',
  2128. ]);
  2129. $entity->author = new Entity([
  2130. 'name' => 'Jose',
  2131. ]);
  2132. $table = $this->getTableLocator()->get('articles');
  2133. $table->belongsTo('authors');
  2134. $calledForArticle = false;
  2135. $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) {
  2136. $calledForArticle = true;
  2137. };
  2138. $table->getEventManager()->on('Model.afterSaveCommit', $listenerForArticle);
  2139. $calledForAuthor = false;
  2140. $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) {
  2141. $calledForAuthor = true;
  2142. };
  2143. $table->authors->getEventManager()->on('Model.afterSaveCommit', $listenerForAuthor);
  2144. $this->assertSame($entity, $table->save($entity));
  2145. $this->assertFalse($entity->isNew());
  2146. $this->assertFalse($entity->author->isNew());
  2147. $this->assertTrue($calledForArticle);
  2148. $this->assertFalse($calledForAuthor);
  2149. }
  2150. /**
  2151. * Test that you cannot save rows without a primary key.
  2152. *
  2153. * @group save
  2154. * @return void
  2155. */
  2156. public function testSaveNewErrorOnNoPrimaryKey()
  2157. {
  2158. $this->expectException(\RuntimeException::class);
  2159. $this->expectExceptionMessage('Cannot insert row in "users" table, it has no primary key');
  2160. $entity = new Entity(['username' => 'superuser']);
  2161. $table = $this->getTableLocator()->get('users', [
  2162. 'schema' => [
  2163. 'id' => ['type' => 'integer'],
  2164. 'username' => ['type' => 'string'],
  2165. ],
  2166. ]);
  2167. $table->save($entity);
  2168. }
  2169. /**
  2170. * Tests that save is wrapped around a transaction
  2171. *
  2172. * @group save
  2173. * @return void
  2174. */
  2175. public function testAtomicSave()
  2176. {
  2177. $config = ConnectionManager::getConfig('test');
  2178. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2179. ->setMethods(['begin', 'commit', 'inTransaction'])
  2180. ->setConstructorArgs([$config])
  2181. ->getMock();
  2182. $connection->setDriver($this->connection->getDriver());
  2183. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2184. ->setMethods(['getConnection'])
  2185. ->setConstructorArgs([['table' => 'users']])
  2186. ->getMock();
  2187. $table->expects($this->any())->method('getConnection')
  2188. ->will($this->returnValue($connection));
  2189. $connection->expects($this->once())->method('begin');
  2190. $connection->expects($this->once())->method('commit');
  2191. $connection->expects($this->any())->method('inTransaction')->will($this->returnValue(true));
  2192. $data = new Entity([
  2193. 'username' => 'superuser',
  2194. 'created' => new Time('2013-10-10 00:00'),
  2195. 'updated' => new Time('2013-10-10 00:00'),
  2196. ]);
  2197. $this->assertSame($data, $table->save($data));
  2198. }
  2199. /**
  2200. * Tests that save will rollback the transaction in the case of an exception
  2201. *
  2202. * @group save
  2203. * @return void
  2204. */
  2205. public function testAtomicSaveRollback()
  2206. {
  2207. $this->expectException(\PDOException::class);
  2208. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2209. ->setMethods(['begin', 'rollback'])
  2210. ->setConstructorArgs([ConnectionManager::getConfig('test')])
  2211. ->getMock();
  2212. $connection->setDriver(ConnectionManager::get('test')->getDriver());
  2213. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2214. ->setMethods(['query', 'getConnection'])
  2215. ->setConstructorArgs([['table' => 'users']])
  2216. ->getMock();
  2217. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2218. ->setMethods(['execute', 'addDefaultTypes'])
  2219. ->setConstructorArgs([null, $table])
  2220. ->getMock();
  2221. $table->expects($this->any())->method('getConnection')
  2222. ->will($this->returnValue($connection));
  2223. $table->expects($this->once())->method('query')
  2224. ->will($this->returnValue($query));
  2225. $connection->expects($this->once())->method('begin');
  2226. $connection->expects($this->once())->method('rollback');
  2227. $query->expects($this->once())->method('execute')
  2228. ->will($this->throwException(new \PDOException()));
  2229. $data = new Entity([
  2230. 'username' => 'superuser',
  2231. 'created' => new Time('2013-10-10 00:00'),
  2232. 'updated' => new Time('2013-10-10 00:00'),
  2233. ]);
  2234. $table->save($data);
  2235. }
  2236. /**
  2237. * Tests that save will rollback the transaction in the case of an exception
  2238. *
  2239. * @group save
  2240. * @return void
  2241. */
  2242. public function testAtomicSaveRollbackOnFailure()
  2243. {
  2244. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2245. ->setMethods(['begin', 'rollback'])
  2246. ->setConstructorArgs([ConnectionManager::getConfig('test')])
  2247. ->getMock();
  2248. $connection->setDriver(ConnectionManager::get('test')->getDriver());
  2249. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2250. ->setMethods(['query', 'getConnection', 'exists'])
  2251. ->setConstructorArgs([['table' => 'users']])
  2252. ->getMock();
  2253. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2254. ->setMethods(['execute', 'addDefaultTypes'])
  2255. ->setConstructorArgs([null, $table])
  2256. ->getMock();
  2257. $table->expects($this->any())->method('getConnection')
  2258. ->will($this->returnValue($connection));
  2259. $table->expects($this->once())->method('query')
  2260. ->will($this->returnValue($query));
  2261. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2262. $statement->expects($this->once())
  2263. ->method('rowCount')
  2264. ->will($this->returnValue(0));
  2265. $connection->expects($this->once())->method('begin');
  2266. $connection->expects($this->once())->method('rollback');
  2267. $query->expects($this->once())
  2268. ->method('execute')
  2269. ->will($this->returnValue($statement));
  2270. $data = new Entity([
  2271. 'username' => 'superuser',
  2272. 'created' => new Time('2013-10-10 00:00'),
  2273. 'updated' => new Time('2013-10-10 00:00'),
  2274. ]);
  2275. $table->save($data);
  2276. }
  2277. /**
  2278. * Tests that only the properties marked as dirty are actually saved
  2279. * to the database
  2280. *
  2281. * @group save
  2282. * @return void
  2283. */
  2284. public function testSaveOnlyDirtyProperties()
  2285. {
  2286. $entity = new Entity([
  2287. 'username' => 'superuser',
  2288. 'password' => 'root',
  2289. 'created' => new Time('2013-10-10 00:00'),
  2290. 'updated' => new Time('2013-10-10 00:00'),
  2291. ]);
  2292. $entity->clean();
  2293. $entity->setDirty('username', true);
  2294. $entity->setDirty('created', true);
  2295. $entity->setDirty('updated', true);
  2296. $table = $this->getTableLocator()->get('users');
  2297. $this->assertSame($entity, $table->save($entity));
  2298. $this->assertEquals($entity->id, self::$nextUserId);
  2299. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  2300. $entity->set('password', null);
  2301. $this->assertEquals($entity->toArray(), $row->toArray());
  2302. }
  2303. /**
  2304. * Tests that a recently saved entity is marked as clean
  2305. *
  2306. * @group save
  2307. * @return void
  2308. */
  2309. public function testASavedEntityIsClean()
  2310. {
  2311. $entity = new Entity([
  2312. 'username' => 'superuser',
  2313. 'password' => 'root',
  2314. 'created' => new Time('2013-10-10 00:00'),
  2315. 'updated' => new Time('2013-10-10 00:00'),
  2316. ]);
  2317. $table = $this->getTableLocator()->get('users');
  2318. $this->assertSame($entity, $table->save($entity));
  2319. $this->assertFalse($entity->isDirty('usermane'));
  2320. $this->assertFalse($entity->isDirty('password'));
  2321. $this->assertFalse($entity->isDirty('created'));
  2322. $this->assertFalse($entity->isDirty('updated'));
  2323. }
  2324. /**
  2325. * Tests that a recently saved entity is marked as not new
  2326. *
  2327. * @group save
  2328. * @return void
  2329. */
  2330. public function testASavedEntityIsNotNew()
  2331. {
  2332. $entity = new Entity([
  2333. 'username' => 'superuser',
  2334. 'password' => 'root',
  2335. 'created' => new Time('2013-10-10 00:00'),
  2336. 'updated' => new Time('2013-10-10 00:00'),
  2337. ]);
  2338. $table = $this->getTableLocator()->get('users');
  2339. $this->assertSame($entity, $table->save($entity));
  2340. $this->assertFalse($entity->isNew());
  2341. }
  2342. /**
  2343. * Tests that save can detect automatically if it needs to insert
  2344. * or update a row
  2345. *
  2346. * @group save
  2347. * @return void
  2348. */
  2349. public function testSaveUpdateAuto()
  2350. {
  2351. $entity = new Entity([
  2352. 'id' => 2,
  2353. 'username' => 'baggins',
  2354. ]);
  2355. $table = $this->getTableLocator()->get('users');
  2356. $original = $table->find('all')->where(['id' => 2])->first();
  2357. $this->assertSame($entity, $table->save($entity));
  2358. $row = $table->find('all')->where(['id' => 2])->first();
  2359. $this->assertEquals('baggins', $row->username);
  2360. $this->assertEquals($original->password, $row->password);
  2361. $this->assertEquals($original->created, $row->created);
  2362. $this->assertEquals($original->updated, $row->updated);
  2363. $this->assertFalse($entity->isNew());
  2364. $this->assertFalse($entity->isDirty('id'));
  2365. $this->assertFalse($entity->isDirty('username'));
  2366. }
  2367. /**
  2368. * Tests that beforeFind gets the correct isNew() state for the entity
  2369. *
  2370. * @return void
  2371. */
  2372. public function testBeforeSaveGetsCorrectPersistance()
  2373. {
  2374. $entity = new Entity([
  2375. 'id' => 2,
  2376. 'username' => 'baggins',
  2377. ]);
  2378. $table = $this->getTableLocator()->get('users');
  2379. $called = false;
  2380. $listener = function (Event $event, $entity) use (&$called) {
  2381. $this->assertFalse($entity->isNew());
  2382. $called = true;
  2383. };
  2384. $table->getEventManager()->on('Model.beforeSave', $listener);
  2385. $this->assertSame($entity, $table->save($entity));
  2386. $this->assertTrue($called);
  2387. }
  2388. /**
  2389. * Tests that marking an entity as already persisted will prevent the save
  2390. * method from trying to infer the entity's actual status.
  2391. *
  2392. * @group save
  2393. * @return void
  2394. */
  2395. public function testSaveUpdateWithHint()
  2396. {
  2397. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2398. ->setMethods(['exists'])
  2399. ->setConstructorArgs([['table' => 'users', 'connection' => ConnectionManager::get('test')]])
  2400. ->getMock();
  2401. $entity = new Entity([
  2402. 'id' => 2,
  2403. 'username' => 'baggins',
  2404. ], ['markNew' => false]);
  2405. $this->assertFalse($entity->isNew());
  2406. $table->expects($this->never())->method('exists');
  2407. $this->assertSame($entity, $table->save($entity));
  2408. }
  2409. /**
  2410. * Tests that when updating the primary key is not passed to the list of
  2411. * attributes to change
  2412. *
  2413. * @group save
  2414. * @return void
  2415. */
  2416. public function testSaveUpdatePrimaryKeyNotModified()
  2417. {
  2418. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2419. ->setMethods(['query'])
  2420. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2421. ->getMock();
  2422. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2423. ->setMethods(['execute', 'addDefaultTypes', 'set'])
  2424. ->setConstructorArgs([null, $table])
  2425. ->getMock();
  2426. $table->expects($this->once())->method('query')
  2427. ->will($this->returnValue($query));
  2428. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2429. $statement->expects($this->once())
  2430. ->method('errorCode')
  2431. ->will($this->returnValue('00000'));
  2432. $query->expects($this->once())
  2433. ->method('execute')
  2434. ->will($this->returnValue($statement));
  2435. $query->expects($this->once())->method('set')
  2436. ->with(['username' => 'baggins'])
  2437. ->will($this->returnValue($query));
  2438. $entity = new Entity([
  2439. 'id' => 2,
  2440. 'username' => 'baggins',
  2441. ], ['markNew' => false]);
  2442. $this->assertSame($entity, $table->save($entity));
  2443. }
  2444. /**
  2445. * Tests that passing only the primary key to save will not execute any queries
  2446. * but still return success
  2447. *
  2448. * @group save
  2449. * @return void
  2450. */
  2451. public function testUpdateNoChange()
  2452. {
  2453. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2454. ->setMethods(['query'])
  2455. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2456. ->getMock();
  2457. $table->expects($this->never())->method('query');
  2458. $entity = new Entity([
  2459. 'id' => 2,
  2460. ], ['markNew' => false]);
  2461. $this->assertSame($entity, $table->save($entity));
  2462. }
  2463. /**
  2464. * Tests that passing only the primary key to save will not execute any queries
  2465. * but still return success
  2466. *
  2467. * @group save
  2468. * @group integration
  2469. * @return void
  2470. */
  2471. public function testUpdateDirtyNoActualChanges()
  2472. {
  2473. $table = $this->getTableLocator()->get('Articles');
  2474. $entity = $table->get(1);
  2475. $entity->setAccess('*', true);
  2476. $entity->set($entity->toArray());
  2477. $this->assertSame($entity, $table->save($entity));
  2478. }
  2479. /**
  2480. * Tests that failing to pass a primary key to save will result in exception
  2481. *
  2482. * @group save
  2483. * @return void
  2484. */
  2485. public function testUpdateNoPrimaryButOtherKeys()
  2486. {
  2487. $this->expectException(\InvalidArgumentException::class);
  2488. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2489. ->setMethods(['query'])
  2490. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2491. ->getMock();
  2492. $table->expects($this->never())->method('query');
  2493. $entity = new Entity([
  2494. 'username' => 'mariano',
  2495. ], ['markNew' => false]);
  2496. $this->assertSame($entity, $table->save($entity));
  2497. }
  2498. /**
  2499. * Test saveMany() with entities array
  2500. *
  2501. * @return void
  2502. */
  2503. public function testSaveManyArray()
  2504. {
  2505. $entities = [
  2506. new Entity(['name' => 'admad']),
  2507. new Entity(['name' => 'dakota']),
  2508. ];
  2509. $table = $this->getTableLocator()->get('authors');
  2510. $result = $table->saveMany($entities);
  2511. $this->assertSame($entities, $result);
  2512. $this->assertTrue(isset($result[0]->id));
  2513. foreach ($entities as $entity) {
  2514. $this->assertFalse($entity->isNew());
  2515. }
  2516. }
  2517. /**
  2518. * Test saveMany() with ResultSet instance
  2519. *
  2520. * @return void
  2521. */
  2522. public function testSaveManyResultSet()
  2523. {
  2524. $table = $this->getTableLocator()->get('authors');
  2525. $entities = $table->find()
  2526. ->order(['id' => 'ASC'])
  2527. ->all();
  2528. $entities->first()->name = 'admad';
  2529. $result = $table->saveMany($entities);
  2530. $this->assertSame($entities, $result);
  2531. $first = $table->find()
  2532. ->order(['id' => 'ASC'])
  2533. ->first();
  2534. $this->assertSame('admad', $first->name);
  2535. }
  2536. /**
  2537. * Test saveMany() with failed save
  2538. *
  2539. * @return void
  2540. */
  2541. public function testSaveManyFailed()
  2542. {
  2543. $table = $this->getTableLocator()->get('authors');
  2544. $expectedCount = $table->find()->count();
  2545. $entities = [
  2546. new Entity(['name' => 'mark']),
  2547. new Entity(['name' => 'jose']),
  2548. ];
  2549. $entities[1]->setErrors(['name' => ['message']]);
  2550. $result = $table->saveMany($entities);
  2551. $this->assertFalse($result);
  2552. $this->assertSame($expectedCount, $table->find()->count());
  2553. foreach ($entities as $entity) {
  2554. $this->assertTrue($entity->isNew());
  2555. }
  2556. }
  2557. /**
  2558. * Test saveMany() with failed save due to an exception
  2559. *
  2560. * @return void
  2561. */
  2562. public function testSaveManyFailedWithException()
  2563. {
  2564. $table = $this->getTableLocator()
  2565. ->get('authors');
  2566. $entities = [
  2567. new Entity(['name' => 'mark']),
  2568. new Entity(['name' => 'jose']),
  2569. ];
  2570. $table->getEventManager()->on('Model.beforeSave', function (Event $event, Entity $entity) {
  2571. if ($entity->name === 'jose') {
  2572. throw new \Exception('Oh noes');
  2573. }
  2574. });
  2575. $this->expectException(\Exception::class);
  2576. try {
  2577. $table->saveMany($entities);
  2578. } finally {
  2579. foreach ($entities as $entity) {
  2580. $this->assertTrue($entity->isNew());
  2581. }
  2582. }
  2583. }
  2584. /**
  2585. * Test saveManyOrFail() with entities array
  2586. *
  2587. * @return void
  2588. */
  2589. public function testSaveManyOrFailArray()
  2590. {
  2591. $entities = [
  2592. new Entity(['name' => 'admad']),
  2593. new Entity(['name' => 'dakota']),
  2594. ];
  2595. $table = $this->getTableLocator()->get('authors');
  2596. $result = $table->saveManyOrFail($entities);
  2597. $this->assertSame($entities, $result);
  2598. $this->assertTrue(isset($result[0]->id));
  2599. foreach ($entities as $entity) {
  2600. $this->assertFalse($entity->isNew());
  2601. }
  2602. }
  2603. /**
  2604. * Test saveManyOrFail() with ResultSet instance
  2605. *
  2606. * @return void
  2607. */
  2608. public function testSaveManyOrFailResultSet()
  2609. {
  2610. $table = $this->getTableLocator()->get('authors');
  2611. $entities = $table->find()
  2612. ->order(['id' => 'ASC'])
  2613. ->all();
  2614. $entities->first()->name = 'admad';
  2615. $result = $table->saveManyOrFail($entities);
  2616. $this->assertSame($entities, $result);
  2617. $first = $table->find()
  2618. ->order(['id' => 'ASC'])
  2619. ->first();
  2620. $this->assertSame('admad', $first->name);
  2621. }
  2622. /**
  2623. * Test saveManyOrFail() with failed save
  2624. *
  2625. * @return void
  2626. */
  2627. public function testSaveManyOrFailFailed()
  2628. {
  2629. $table = $this->getTableLocator()->get('authors');
  2630. $entities = [
  2631. new Entity(['name' => 'mark']),
  2632. new Entity(['name' => 'jose']),
  2633. ];
  2634. $entities[1]->setErrors(['name' => ['message']]);
  2635. $this->expectException(PersistenceFailedException::class);
  2636. $table->saveManyOrFail($entities);
  2637. }
  2638. /**
  2639. * Test simple delete.
  2640. *
  2641. * @return void
  2642. */
  2643. public function testDelete()
  2644. {
  2645. $table = $this->getTableLocator()->get('users');
  2646. $conditions = [
  2647. 'limit' => 1,
  2648. 'conditions' => [
  2649. 'username' => 'nate',
  2650. ],
  2651. ];
  2652. $query = $table->find('all', $conditions);
  2653. $entity = $query->first();
  2654. $result = $table->delete($entity);
  2655. $this->assertTrue($result);
  2656. $query = $table->find('all', $conditions);
  2657. $results = $query->execute();
  2658. $this->assertCount(0, $results, 'Find should fail.');
  2659. }
  2660. /**
  2661. * Test delete with dependent records
  2662. *
  2663. * @return void
  2664. */
  2665. public function testDeleteDependent()
  2666. {
  2667. $table = $this->getTableLocator()->get('authors');
  2668. $table->hasOne('articles', [
  2669. 'foreignKey' => 'author_id',
  2670. 'dependent' => true,
  2671. ]);
  2672. $entity = $table->get(1);
  2673. $result = $table->delete($entity);
  2674. $articles = $table->getAssociation('articles')->getTarget();
  2675. $query = $articles->find('all', [
  2676. 'conditions' => [
  2677. 'author_id' => $entity->id,
  2678. ],
  2679. ]);
  2680. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2681. }
  2682. /**
  2683. * Test delete with dependent records
  2684. *
  2685. * @return void
  2686. */
  2687. public function testDeleteDependentHasMany()
  2688. {
  2689. $table = $this->getTableLocator()->get('authors');
  2690. $table->hasMany('articles', [
  2691. 'foreignKey' => 'author_id',
  2692. 'dependent' => true,
  2693. 'cascadeCallbacks' => true,
  2694. ]);
  2695. $entity = $table->get(1);
  2696. $result = $table->delete($entity);
  2697. $this->assertTrue($result);
  2698. }
  2699. /**
  2700. * Test delete with dependent = false does not cascade.
  2701. *
  2702. * @return void
  2703. */
  2704. public function testDeleteNoDependentNoCascade()
  2705. {
  2706. $table = $this->getTableLocator()->get('authors');
  2707. $table->hasMany('article', [
  2708. 'foreignKey' => 'author_id',
  2709. 'dependent' => false,
  2710. ]);
  2711. $query = $table->find('all')->where(['id' => 1]);
  2712. $entity = $query->first();
  2713. $result = $table->delete($entity);
  2714. $articles = $table->getAssociation('articles')->getTarget();
  2715. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  2716. $this->assertCount(2, $query->execute(), 'Should find rows.');
  2717. }
  2718. /**
  2719. * Test delete with BelongsToMany
  2720. *
  2721. * @return void
  2722. */
  2723. public function testDeleteBelongsToMany()
  2724. {
  2725. $table = $this->getTableLocator()->get('articles');
  2726. $table->belongsToMany('tag', [
  2727. 'foreignKey' => 'article_id',
  2728. 'joinTable' => 'articles_tags',
  2729. ]);
  2730. $query = $table->find('all')->where(['id' => 1]);
  2731. $entity = $query->first();
  2732. $table->delete($entity);
  2733. $junction = $table->getAssociation('tags')->junction();
  2734. $query = $junction->find('all')->where(['article_id' => 1]);
  2735. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2736. }
  2737. /**
  2738. * Test delete with dependent records belonging to an aliased
  2739. * belongsToMany association.
  2740. *
  2741. * @return void
  2742. */
  2743. public function testDeleteDependentAliased()
  2744. {
  2745. $Authors = $this->getTableLocator()->get('authors');
  2746. $Authors->associations()->removeAll();
  2747. $Articles = $this->getTableLocator()->get('articles');
  2748. $Articles->associations()->removeAll();
  2749. $Authors->hasMany('AliasedArticles', [
  2750. 'className' => 'Articles',
  2751. 'dependent' => true,
  2752. 'cascadeCallbacks' => true,
  2753. ]);
  2754. $Articles->belongsToMany('Tags');
  2755. $author = $Authors->get(1);
  2756. $result = $Authors->delete($author);
  2757. $this->assertTrue($result);
  2758. }
  2759. /**
  2760. * Test that cascading associations are deleted first.
  2761. *
  2762. * @return void
  2763. */
  2764. public function testDeleteAssociationsCascadingCallbacksOrder()
  2765. {
  2766. $groups = $this->getTableLocator()->get('Groups');
  2767. $members = $this->getTableLocator()->get('Members');
  2768. $groupsMembers = $this->getTableLocator()->get('GroupsMembers');
  2769. $groups->belongsToMany('Members');
  2770. $groups->hasMany('GroupsMembers', [
  2771. 'dependent' => true,
  2772. 'cascadeCallbacks' => true,
  2773. ]);
  2774. $groupsMembers->belongsTo('Members');
  2775. $groupsMembers->addBehavior('CounterCache', [
  2776. 'Members' => ['group_count'],
  2777. ]);
  2778. $member = $members->get(1);
  2779. $this->assertEquals(2, $member->group_count);
  2780. $group = $groups->get(1);
  2781. $groups->delete($group);
  2782. $member = $members->get(1);
  2783. $this->assertEquals(1, $member->group_count);
  2784. }
  2785. /**
  2786. * Test delete callbacks
  2787. *
  2788. * @return void
  2789. */
  2790. public function testDeleteCallbacks()
  2791. {
  2792. $entity = new Entity(['id' => 1, 'name' => 'mark']);
  2793. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]);
  2794. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2795. $mock->expects($this->at(0))
  2796. ->method('on');
  2797. $mock->expects($this->at(1))
  2798. ->method('dispatch');
  2799. $mock->expects($this->at(2))
  2800. ->method('dispatch')
  2801. ->with($this->logicalAnd(
  2802. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  2803. $this->attributeEqualTo(
  2804. '_data',
  2805. ['entity' => $entity, 'options' => $options]
  2806. )
  2807. ));
  2808. $mock->expects($this->at(3))
  2809. ->method('dispatch')
  2810. ->with($this->logicalAnd(
  2811. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  2812. $this->attributeEqualTo(
  2813. '_data',
  2814. ['entity' => $entity, 'options' => $options]
  2815. )
  2816. ));
  2817. $mock->expects($this->at(4))
  2818. ->method('dispatch')
  2819. ->with($this->logicalAnd(
  2820. $this->attributeEqualTo('_name', 'Model.afterDeleteCommit'),
  2821. $this->attributeEqualTo(
  2822. '_data',
  2823. ['entity' => $entity, 'options' => $options]
  2824. )
  2825. ));
  2826. $table = $this->getTableLocator()->get('users', ['eventManager' => $mock]);
  2827. $entity->setNew(false);
  2828. $table->delete($entity, ['checkRules' => false]);
  2829. }
  2830. /**
  2831. * Test afterDeleteCommit is also called for non-atomic delete
  2832. *
  2833. * @return void
  2834. */
  2835. public function testDeleteCallbacksNonAtomic()
  2836. {
  2837. $table = $this->getTableLocator()->get('users');
  2838. $data = $table->get(1);
  2839. $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]);
  2840. $called = false;
  2841. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2842. $this->assertSame($data, $entity);
  2843. $called = true;
  2844. };
  2845. $table->getEventManager()->on('Model.afterDelete', $listener);
  2846. $calledAfterCommit = false;
  2847. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2848. $calledAfterCommit = true;
  2849. };
  2850. $table->getEventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit);
  2851. $table->delete($data, ['atomic' => false]);
  2852. $this->assertTrue($called);
  2853. $this->assertTrue($calledAfterCommit);
  2854. }
  2855. /**
  2856. * Test that afterDeleteCommit is only triggered for primary table
  2857. *
  2858. * @return void
  2859. */
  2860. public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable()
  2861. {
  2862. $table = $this->getTableLocator()->get('authors');
  2863. $table->hasOne('articles', [
  2864. 'foreignKey' => 'author_id',
  2865. 'dependent' => true,
  2866. ]);
  2867. $called = false;
  2868. $listener = function ($e, $entity, $options) use (&$called) {
  2869. $called = true;
  2870. };
  2871. $table->getEventManager()->on('Model.afterDeleteCommit', $listener);
  2872. $called2 = false;
  2873. $listener = function ($e, $entity, $options) use (&$called2) {
  2874. $called2 = true;
  2875. };
  2876. $table->articles->getEventManager()->on('Model.afterDeleteCommit', $listener);
  2877. $entity = $table->get(1);
  2878. $this->assertTrue($table->delete($entity));
  2879. $this->assertTrue($called);
  2880. $this->assertFalse($called2);
  2881. }
  2882. /**
  2883. * Test delete beforeDelete can abort the delete.
  2884. *
  2885. * @return void
  2886. */
  2887. public function testDeleteBeforeDeleteAbort()
  2888. {
  2889. $entity = new Entity(['id' => 1, 'name' => 'mark']);
  2890. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2891. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2892. $mock->expects($this->at(2))
  2893. ->method('dispatch')
  2894. ->will($this->returnCallback(function (Event $event) {
  2895. $event->stopPropagation();
  2896. }));
  2897. $table = $this->getTableLocator()->get('users', ['eventManager' => $mock]);
  2898. $entity->setNew(false);
  2899. $result = $table->delete($entity, ['checkRules' => false]);
  2900. $this->assertNull($result);
  2901. }
  2902. /**
  2903. * Test delete beforeDelete return result
  2904. *
  2905. * @return void
  2906. */
  2907. public function testDeleteBeforeDeleteReturnResult()
  2908. {
  2909. $entity = new Entity(['id' => 1, 'name' => 'mark']);
  2910. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2911. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2912. $mock->expects($this->at(2))
  2913. ->method('dispatch')
  2914. ->will($this->returnCallback(function (Event $event) {
  2915. $event->stopPropagation();
  2916. $event->setResult('got stopped');
  2917. }));
  2918. $table = $this->getTableLocator()->get('users', ['eventManager' => $mock]);
  2919. $entity->setNew(false);
  2920. $result = $table->delete($entity, ['checkRules' => false]);
  2921. $this->assertEquals('got stopped', $result);
  2922. }
  2923. /**
  2924. * Test deleting new entities does nothing.
  2925. *
  2926. * @return void
  2927. */
  2928. public function testDeleteIsNew()
  2929. {
  2930. $entity = new Entity(['id' => 1, 'name' => 'mark']);
  2931. $table = $this->getMockBuilder('Cake\ORM\Table')
  2932. ->setMethods(['query'])
  2933. ->setConstructorArgs([['connection' => $this->connection]])
  2934. ->getMock();
  2935. $table->expects($this->never())
  2936. ->method('query');
  2937. $entity->setNew(true);
  2938. $result = $table->delete($entity);
  2939. $this->assertFalse($result);
  2940. }
  2941. /**
  2942. * test hasField()
  2943. *
  2944. * @return void
  2945. */
  2946. public function testHasField()
  2947. {
  2948. $table = $this->getTableLocator()->get('articles');
  2949. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  2950. $this->assertTrue($table->hasField('title'), 'Should be there.');
  2951. $this->assertTrue($table->hasField('body'), 'Should be there.');
  2952. }
  2953. /**
  2954. * Tests that there exists a default validator
  2955. *
  2956. * @return void
  2957. */
  2958. public function testValidatorDefault()
  2959. {
  2960. $table = new Table();
  2961. $validator = $table->getValidator();
  2962. $this->assertSame($table, $validator->getProvider('table'));
  2963. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  2964. $default = $table->getValidator('default');
  2965. $this->assertSame($validator, $default);
  2966. }
  2967. /**
  2968. * Tests that there exists a validator defined in a behavior.
  2969. *
  2970. * @return void
  2971. */
  2972. public function testValidatorBehavior()
  2973. {
  2974. $table = new Table();
  2975. $table->addBehavior('Validation');
  2976. $validator = $table->getValidator('Behavior');
  2977. $set = $validator->field('name');
  2978. $this->assertArrayHasKey('behaviorRule', $set);
  2979. }
  2980. /**
  2981. * Tests that it is possible to define custom validator methods
  2982. *
  2983. * @return void
  2984. */
  2985. public function testValidationWithDefiner()
  2986. {
  2987. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2988. ->setMethods(['validationForOtherStuff'])
  2989. ->getMock();
  2990. $table->expects($this->once())->method('validationForOtherStuff')
  2991. ->will($this->returnArgument(0));
  2992. $other = $table->getValidator('forOtherStuff');
  2993. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  2994. $this->assertNotSame($other, $table->getValidator());
  2995. $this->assertSame($table, $other->getProvider('table'));
  2996. }
  2997. /**
  2998. * Tests that a RuntimeException is thrown if the custom validator does not return an Validator instance
  2999. *
  3000. * @return void
  3001. */
  3002. public function testValidationWithBadDefiner()
  3003. {
  3004. $this->expectException(\RuntimeException::class);
  3005. $this->expectExceptionMessage('The Cake\ORM\Table::validationBad() validation method must return an instance of Cake\Validation\Validator.');
  3006. $table = $this->getMockBuilder('\Cake\ORM\Table')
  3007. ->setMethods(['validationBad'])
  3008. ->getMock();
  3009. $table->expects($this->once())
  3010. ->method('validationBad');
  3011. $table->getValidator('bad');
  3012. }
  3013. /**
  3014. * Tests that a RuntimeException is thrown if the custom validator method does not exist.
  3015. *
  3016. * @return void
  3017. */
  3018. public function testValidatorWithMissingMethod()
  3019. {
  3020. $this->expectException(\RuntimeException::class);
  3021. $this->expectExceptionMessage('The Cake\ORM\Table::validationMissing() validation method does not exists.');
  3022. $table = new Table();
  3023. $table->getValidator('missing');
  3024. }
  3025. /**
  3026. * Tests that it is possible to set a custom validator under a name
  3027. *
  3028. * @return void
  3029. */
  3030. public function testValidatorSetter()
  3031. {
  3032. $table = new Table();
  3033. $validator = new \Cake\Validation\Validator();
  3034. $table->setValidator('other', $validator);
  3035. $this->assertSame($validator, $table->getValidator('other'));
  3036. $this->assertSame($table, $validator->getProvider('table'));
  3037. }
  3038. /**
  3039. * Tests hasValidator method.
  3040. *
  3041. * @return void
  3042. */
  3043. public function testHasValidator()
  3044. {
  3045. $table = new Table();
  3046. $this->assertTrue($table->hasValidator('default'));
  3047. $this->assertFalse($table->hasValidator('other'));
  3048. $validator = new \Cake\Validation\Validator();
  3049. $table->setValidator('other', $validator);
  3050. $this->assertTrue($table->hasValidator('other'));
  3051. }
  3052. /**
  3053. * Tests that the source of an existing Entity is the same as a new one
  3054. *
  3055. * @return void
  3056. */
  3057. public function testEntitySourceExistingAndNew()
  3058. {
  3059. $this->loadPlugins(['TestPlugin']);
  3060. $table = $this->getTableLocator()->get('TestPlugin.Authors');
  3061. $existingAuthor = $table->find()->first();
  3062. $newAuthor = $table->newEntity();
  3063. $this->assertEquals('TestPlugin.Authors', $existingAuthor->getSource());
  3064. $this->assertEquals('TestPlugin.Authors', $newAuthor->getSource());
  3065. }
  3066. /**
  3067. * Tests that calling an entity with an empty array will run validation
  3068. * whereas calling it with no parameters will not run any validation.
  3069. *
  3070. * @return void
  3071. */
  3072. public function testNewEntityAndValidation()
  3073. {
  3074. $table = $this->getTableLocator()->get('Articles');
  3075. $validator = $table->getValidator()->requirePresence('title');
  3076. $entity = $table->newEntity([]);
  3077. $errors = $entity->getErrors();
  3078. $this->assertNotEmpty($errors['title']);
  3079. $entity = $table->newEntity();
  3080. $this->assertEmpty($entity->getErrors());
  3081. }
  3082. /**
  3083. * Test magic findByXX method.
  3084. *
  3085. * @return void
  3086. */
  3087. public function testMagicFindDefaultToAll()
  3088. {
  3089. $table = $this->getTableLocator()->get('Users');
  3090. $result = $table->findByUsername('garrett');
  3091. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3092. $expected = new QueryExpression(['Users.username' => 'garrett'], $this->usersTypeMap);
  3093. $this->assertEquals($expected, $result->clause('where'));
  3094. }
  3095. /**
  3096. * Test magic findByXX errors on missing arguments.
  3097. *
  3098. * @return void
  3099. */
  3100. public function testMagicFindError()
  3101. {
  3102. $this->expectException(\BadMethodCallException::class);
  3103. $this->expectExceptionMessage('Not enough arguments for magic finder. Got 0 required 1');
  3104. $table = $this->getTableLocator()->get('Users');
  3105. $table->findByUsername();
  3106. }
  3107. /**
  3108. * Test magic findByXX errors on missing arguments.
  3109. *
  3110. * @return void
  3111. */
  3112. public function testMagicFindErrorMissingField()
  3113. {
  3114. $this->expectException(\BadMethodCallException::class);
  3115. $this->expectExceptionMessage('Not enough arguments for magic finder. Got 1 required 2');
  3116. $table = $this->getTableLocator()->get('Users');
  3117. $table->findByUsernameAndId('garrett');
  3118. }
  3119. /**
  3120. * Test magic findByXX errors when there is a mix of or & and.
  3121. *
  3122. * @return void
  3123. */
  3124. public function testMagicFindErrorMixOfOperators()
  3125. {
  3126. $this->expectException(\BadMethodCallException::class);
  3127. $this->expectExceptionMessage('Cannot mix "and" & "or" in a magic finder. Use find() instead.');
  3128. $table = $this->getTableLocator()->get('Users');
  3129. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  3130. }
  3131. /**
  3132. * Test magic findByXX method.
  3133. *
  3134. * @return void
  3135. */
  3136. public function testMagicFindFirstAnd()
  3137. {
  3138. $table = $this->getTableLocator()->get('Users');
  3139. $result = $table->findByUsernameAndId('garrett', 4);
  3140. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3141. $expected = new QueryExpression(['Users.username' => 'garrett', 'Users.id' => 4], $this->usersTypeMap);
  3142. $this->assertEquals($expected, $result->clause('where'));
  3143. }
  3144. /**
  3145. * Test magic findByXX method.
  3146. *
  3147. * @return void
  3148. */
  3149. public function testMagicFindFirstOr()
  3150. {
  3151. $table = $this->getTableLocator()->get('Users');
  3152. $result = $table->findByUsernameOrId('garrett', 4);
  3153. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3154. $expected = new QueryExpression([], $this->usersTypeMap);
  3155. $expected->add(
  3156. [
  3157. 'OR' => [
  3158. 'Users.username' => 'garrett',
  3159. 'Users.id' => 4,
  3160. ]]
  3161. );
  3162. $this->assertEquals($expected, $result->clause('where'));
  3163. }
  3164. /**
  3165. * Test magic findAllByXX method.
  3166. *
  3167. * @return void
  3168. */
  3169. public function testMagicFindAll()
  3170. {
  3171. $table = $this->getTableLocator()->get('Articles');
  3172. $result = $table->findAllByAuthorId(1);
  3173. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3174. $this->assertNull($result->clause('limit'));
  3175. $expected = new QueryExpression(['Articles.author_id' => 1], $this->articlesTypeMap);
  3176. $this->assertEquals($expected, $result->clause('where'));
  3177. }
  3178. /**
  3179. * Test magic findAllByXX method.
  3180. *
  3181. * @return void
  3182. */
  3183. public function testMagicFindAllAnd()
  3184. {
  3185. $table = $this->getTableLocator()->get('Users');
  3186. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  3187. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3188. $this->assertNull($result->clause('limit'));
  3189. $expected = new QueryExpression(
  3190. ['Users.author_id' => 1, 'Users.published' => 'Y'],
  3191. $this->usersTypeMap
  3192. );
  3193. $this->assertEquals($expected, $result->clause('where'));
  3194. }
  3195. /**
  3196. * Test magic findAllByXX method.
  3197. *
  3198. * @return void
  3199. */
  3200. public function testMagicFindAllOr()
  3201. {
  3202. $table = $this->getTableLocator()->get('Users');
  3203. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  3204. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3205. $this->assertNull($result->clause('limit'));
  3206. $expected = new QueryExpression();
  3207. $expected->getTypeMap()->setDefaults($this->usersTypeMap->toArray());
  3208. $expected->add(
  3209. ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']]
  3210. );
  3211. $this->assertEquals($expected, $result->clause('where'));
  3212. $this->assertNull($result->clause('order'));
  3213. }
  3214. /**
  3215. * Test the behavior method.
  3216. *
  3217. * @return void
  3218. */
  3219. public function testBehaviorIntrospection()
  3220. {
  3221. $table = $this->getTableLocator()->get('users');
  3222. $table->addBehavior('Timestamp');
  3223. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  3224. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  3225. }
  3226. /**
  3227. * Tests saving belongsTo association
  3228. *
  3229. * @group save
  3230. * @return void
  3231. */
  3232. public function testSaveBelongsTo()
  3233. {
  3234. $entity = new Entity([
  3235. 'title' => 'A Title',
  3236. 'body' => 'A body',
  3237. ]);
  3238. $entity->author = new Entity([
  3239. 'name' => 'Jose',
  3240. ]);
  3241. $table = $this->getTableLocator()->get('articles');
  3242. $table->belongsTo('authors');
  3243. $this->assertSame($entity, $table->save($entity));
  3244. $this->assertFalse($entity->isNew());
  3245. $this->assertFalse($entity->author->isNew());
  3246. $this->assertEquals(5, $entity->author->id);
  3247. $this->assertEquals(5, $entity->get('author_id'));
  3248. }
  3249. /**
  3250. * Tests saving hasOne association
  3251. *
  3252. * @group save
  3253. * @return void
  3254. */
  3255. public function testSaveHasOne()
  3256. {
  3257. $entity = new Entity([
  3258. 'name' => 'Jose',
  3259. ]);
  3260. $entity->article = new Entity([
  3261. 'title' => 'A Title',
  3262. 'body' => 'A body',
  3263. ]);
  3264. $table = $this->getTableLocator()->get('authors');
  3265. $table->hasOne('articles');
  3266. $this->assertSame($entity, $table->save($entity));
  3267. $this->assertFalse($entity->isNew());
  3268. $this->assertFalse($entity->article->isNew());
  3269. $this->assertEquals(4, $entity->article->id);
  3270. $this->assertEquals(5, $entity->article->get('author_id'));
  3271. $this->assertFalse($entity->article->isDirty('author_id'));
  3272. }
  3273. /**
  3274. * Tests saving associations only saves associations
  3275. * if they are entities.
  3276. *
  3277. * @group save
  3278. * @return void
  3279. */
  3280. public function testSaveOnlySaveAssociatedEntities()
  3281. {
  3282. $entity = new Entity([
  3283. 'name' => 'Jose',
  3284. ]);
  3285. // Not an entity.
  3286. $entity->article = [
  3287. 'title' => 'A Title',
  3288. 'body' => 'A body',
  3289. ];
  3290. $table = $this->getTableLocator()->get('authors');
  3291. $table->hasOne('articles');
  3292. $table->save($entity);
  3293. $this->assertFalse($entity->isNew());
  3294. $this->assertInternalType('array', $entity->article);
  3295. }
  3296. /**
  3297. * Tests saving multiple entities in a hasMany association
  3298. *
  3299. * @return void
  3300. */
  3301. public function testSaveHasMany()
  3302. {
  3303. $entity = new Entity([
  3304. 'name' => 'Jose',
  3305. ]);
  3306. $entity->articles = [
  3307. new Entity([
  3308. 'title' => 'A Title',
  3309. 'body' => 'A body',
  3310. ]),
  3311. new Entity([
  3312. 'title' => 'Another Title',
  3313. 'body' => 'Another body',
  3314. ]),
  3315. ];
  3316. $table = $this->getTableLocator()->get('authors');
  3317. $table->hasMany('articles');
  3318. $this->assertSame($entity, $table->save($entity));
  3319. $this->assertFalse($entity->isNew());
  3320. $this->assertFalse($entity->articles[0]->isNew());
  3321. $this->assertFalse($entity->articles[1]->isNew());
  3322. $this->assertEquals(4, $entity->articles[0]->id);
  3323. $this->assertEquals(5, $entity->articles[1]->id);
  3324. $this->assertEquals(5, $entity->articles[0]->author_id);
  3325. $this->assertEquals(5, $entity->articles[1]->author_id);
  3326. }
  3327. /**
  3328. * Tests overwriting hasMany associations in an integration scenario.
  3329. *
  3330. * @return void
  3331. */
  3332. public function testSaveHasManyOverwrite()
  3333. {
  3334. $table = $this->getTableLocator()->get('authors');
  3335. $table->hasMany('articles');
  3336. $entity = $table->get(3, ['contain' => ['articles']]);
  3337. $data = [
  3338. 'name' => 'big jose',
  3339. 'articles' => [
  3340. [
  3341. 'id' => 2,
  3342. 'title' => 'New title',
  3343. ],
  3344. ],
  3345. ];
  3346. $entity = $table->patchEntity($entity, $data, ['associated' => 'articles']);
  3347. $this->assertSame($entity, $table->save($entity));
  3348. $entity = $table->get(3, ['contain' => ['articles']]);
  3349. $this->assertEquals('big jose', $entity->name, 'Author did not persist');
  3350. $this->assertEquals('New title', $entity->articles[0]->title, 'Article did not persist');
  3351. }
  3352. /**
  3353. * Tests saving belongsToMany records
  3354. *
  3355. * @group save
  3356. * @return void
  3357. */
  3358. public function testSaveBelongsToMany()
  3359. {
  3360. $entity = new Entity([
  3361. 'title' => 'A Title',
  3362. 'body' => 'A body',
  3363. ]);
  3364. $entity->tags = [
  3365. new Entity([
  3366. 'name' => 'Something New',
  3367. ]),
  3368. new Entity([
  3369. 'name' => 'Another Something',
  3370. ]),
  3371. ];
  3372. $table = $this->getTableLocator()->get('articles');
  3373. $table->belongsToMany('tags');
  3374. $this->assertSame($entity, $table->save($entity));
  3375. $this->assertFalse($entity->isNew());
  3376. $this->assertFalse($entity->tags[0]->isNew());
  3377. $this->assertFalse($entity->tags[1]->isNew());
  3378. $this->assertEquals(4, $entity->tags[0]->id);
  3379. $this->assertEquals(5, $entity->tags[1]->id);
  3380. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  3381. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  3382. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  3383. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  3384. }
  3385. /**
  3386. * Tests saving belongsToMany records when record exists.
  3387. *
  3388. * @group save
  3389. * @return void
  3390. */
  3391. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  3392. {
  3393. $tags = $this->getTableLocator()->get('Tags');
  3394. $table = $this->getTableLocator()->get('Articles');
  3395. $table->belongsToMany('Tags');
  3396. $entity = $table->find()->contain('Tags')->first();
  3397. // not associated to the article already.
  3398. $entity->tags[] = $tags->get(3);
  3399. $entity->setDirty('tags', true);
  3400. $this->assertSame($entity, $table->save($entity));
  3401. $this->assertFalse($entity->isNew());
  3402. $this->assertFalse($entity->tags[0]->isNew());
  3403. $this->assertFalse($entity->tags[1]->isNew());
  3404. $this->assertFalse($entity->tags[2]->isNew());
  3405. $this->assertNotEmpty($entity->tags[0]->_joinData);
  3406. $this->assertNotEmpty($entity->tags[1]->_joinData);
  3407. $this->assertNotEmpty($entity->tags[2]->_joinData);
  3408. }
  3409. /**
  3410. * Test that belongsToMany can be saved with _joinData data.
  3411. *
  3412. * @return void
  3413. */
  3414. public function testSaveBelongsToManyJoinData()
  3415. {
  3416. $articles = $this->getTableLocator()->get('Articles');
  3417. $article = $articles->get(1, ['contain' => ['tags']]);
  3418. $data = [
  3419. 'tags' => [
  3420. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  3421. ['id' => 3],
  3422. ],
  3423. ];
  3424. $article = $articles->patchEntity($article, $data);
  3425. $result = $articles->save($article);
  3426. $this->assertSame($result, $article);
  3427. }
  3428. /**
  3429. * Test to check that association condition are used when fetching existing
  3430. * records to decide which records to unlink.
  3431. *
  3432. * @return void
  3433. */
  3434. public function testPolymorphicBelongsToManySave()
  3435. {
  3436. $articles = $this->getTableLocator()->get('Articles');
  3437. $articles->belongsToMany('Tags', [
  3438. 'through' => 'PolymorphicTagged',
  3439. 'foreignKey' => 'foreign_key',
  3440. 'conditions' => [
  3441. 'PolymorphicTagged.foreign_model' => 'Articles',
  3442. ],
  3443. 'sort' => ['PolymorphicTagged.position' => 'ASC'],
  3444. ]);
  3445. $articles->Tags->junction()->belongsTo('Tags');
  3446. $entity = $articles->get(1, ['contain' => ['Tags']]);
  3447. $data = [
  3448. 'id' => 1,
  3449. 'tags' => [
  3450. [
  3451. 'id' => 1,
  3452. '_joinData' => [
  3453. 'id' => 2,
  3454. 'foreign_model' => 'Articles',
  3455. 'position' => 2,
  3456. ],
  3457. ],
  3458. [
  3459. 'id' => 2,
  3460. '_joinData' => [
  3461. 'foreign_model' => 'Articles',
  3462. 'position' => 1,
  3463. ],
  3464. ],
  3465. ],
  3466. ];
  3467. $entity = $articles->patchEntity($entity, $data, ['associated' => ['Tags._joinData']]);
  3468. $entity = $articles->save($entity);
  3469. $expected = [
  3470. [
  3471. 'id' => 1,
  3472. 'tag_id' => 1,
  3473. 'foreign_key' => 1,
  3474. 'foreign_model' => 'Posts',
  3475. 'position' => 1,
  3476. ],
  3477. [
  3478. 'id' => 2,
  3479. 'tag_id' => 1,
  3480. 'foreign_key' => 1,
  3481. 'foreign_model' => 'Articles',
  3482. 'position' => 2,
  3483. ],
  3484. [
  3485. 'id' => 3,
  3486. 'tag_id' => 2,
  3487. 'foreign_key' => 1,
  3488. 'foreign_model' => 'Articles',
  3489. 'position' => 1,
  3490. ],
  3491. ];
  3492. $result = $this->getTableLocator()->get('PolymorphicTagged')
  3493. ->find('all', ['sort' => ['id' => 'DESC']])
  3494. ->enableHydration(false)
  3495. ->toArray();
  3496. $this->assertEquals($expected, $result);
  3497. }
  3498. /**
  3499. * Tests saving belongsToMany records can delete all links.
  3500. *
  3501. * @group save
  3502. * @return void
  3503. */
  3504. public function testSaveBelongsToManyDeleteAllLinks()
  3505. {
  3506. $table = $this->getTableLocator()->get('articles');
  3507. $table->belongsToMany('tags', [
  3508. 'saveStrategy' => 'replace',
  3509. ]);
  3510. $entity = $table->get(1, ['contain' => 'tags']);
  3511. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3512. $entity->tags = [];
  3513. $result = $table->save($entity);
  3514. $this->assertSame($result, $entity);
  3515. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  3516. $entity = $table->get(1, ['contain' => 'tags']);
  3517. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  3518. }
  3519. /**
  3520. * Tests saving belongsToMany records can delete some links.
  3521. *
  3522. * @group save
  3523. * @return void
  3524. */
  3525. public function testSaveBelongsToManyDeleteSomeLinks()
  3526. {
  3527. $table = $this->getTableLocator()->get('articles');
  3528. $table->belongsToMany('tags', [
  3529. 'saveStrategy' => 'replace',
  3530. ]);
  3531. $entity = $table->get(1, ['contain' => 'tags']);
  3532. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3533. $tag = new Entity([
  3534. 'id' => 2,
  3535. ]);
  3536. $entity->tags = [$tag];
  3537. $result = $table->save($entity);
  3538. $this->assertSame($result, $entity);
  3539. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  3540. $this->assertEquals($tag, $entity->tags[0]);
  3541. $entity = $table->get(1, ['contain' => 'tags']);
  3542. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  3543. $this->assertEquals($tag->id, $entity->tags[0]->id);
  3544. }
  3545. /**
  3546. * Test that belongsToMany ignores non-entity data.
  3547. *
  3548. * @return void
  3549. */
  3550. public function testSaveBelongsToManyIgnoreNonEntityData()
  3551. {
  3552. $articles = $this->getTableLocator()->get('articles');
  3553. $article = $articles->get(1, ['contain' => ['tags']]);
  3554. $article->tags = [
  3555. '_ids' => [2, 1],
  3556. ];
  3557. $result = $articles->save($article);
  3558. $this->assertSame($result, $article);
  3559. }
  3560. /**
  3561. * Test that a save call takes a SaveOptionBuilder object as well.
  3562. *
  3563. * @group save
  3564. * @return void
  3565. */
  3566. public function testSaveWithOptionBuilder()
  3567. {
  3568. $articles = new Table([
  3569. 'table' => 'articles',
  3570. 'connection' => $this->connection,
  3571. ]);
  3572. $articles->belongsTo('Authors');
  3573. $optionBuilder = new SaveOptionsBuilder($articles, [
  3574. 'associated' => [
  3575. 'Authors',
  3576. ],
  3577. ]);
  3578. $entity = $articles->newEntity([
  3579. 'title' => 'test save options',
  3580. 'author' => [
  3581. 'name' => 'author name',
  3582. ],
  3583. ]);
  3584. $articles->save($entity, $optionBuilder);
  3585. $this->assertFalse($entity->isNew());
  3586. $this->assertEquals('test save options', $entity->title);
  3587. $this->assertNotEmpty($entity->id);
  3588. $this->assertNotEmpty($entity->author->id);
  3589. $this->assertEquals('author name', $entity->author->name);
  3590. $entity = $articles->newEntity([
  3591. 'title' => 'test save options 2',
  3592. 'author' => [
  3593. 'name' => 'author name',
  3594. ],
  3595. ]);
  3596. $optionBuilder = new SaveOptionsBuilder($articles, [
  3597. 'associated' => [],
  3598. ]);
  3599. $articles->save($entity, $optionBuilder);
  3600. $this->assertFalse($entity->isNew());
  3601. $this->assertEquals('test save options 2', $entity->title);
  3602. $this->assertNotEmpty($entity->id);
  3603. $this->assertEmpty($entity->author->id);
  3604. $this->assertTrue($entity->author->isNew());
  3605. }
  3606. /**
  3607. * Tests that saving a persisted and clean entity will is a no-op
  3608. *
  3609. * @group save
  3610. * @return void
  3611. */
  3612. public function testSaveCleanEntity()
  3613. {
  3614. $table = $this->getMockBuilder('\Cake\ORM\Table')
  3615. ->setMethods(['_processSave'])
  3616. ->getMock();
  3617. $entity = new Entity(
  3618. ['id' => 'foo'],
  3619. ['markNew' => false, 'markClean' => true]
  3620. );
  3621. $table->expects($this->never())->method('_processSave');
  3622. $this->assertSame($entity, $table->save($entity));
  3623. }
  3624. /**
  3625. * Integration test to show how to append a new tag to an article
  3626. *
  3627. * @group save
  3628. * @return void
  3629. */
  3630. public function testBelongsToManyIntegration()
  3631. {
  3632. $table = $this->getTableLocator()->get('articles');
  3633. $table->belongsToMany('tags');
  3634. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3635. $tags = $article->tags;
  3636. $this->assertNotEmpty($tags);
  3637. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  3638. $article->tags = $tags;
  3639. $this->assertSame($article, $table->save($article));
  3640. $tags = $article->tags;
  3641. $this->assertCount(3, $tags);
  3642. $this->assertFalse($tags[2]->isNew());
  3643. $this->assertEquals(4, $tags[2]->id);
  3644. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  3645. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  3646. }
  3647. /**
  3648. * Tests that it is possible to do a deep save and control what associations get saved,
  3649. * while having control of the options passed to each level of the save
  3650. *
  3651. * @group save
  3652. * @return void
  3653. */
  3654. public function testSaveDeepAssociationOptions()
  3655. {
  3656. $articles = $this->getMockBuilder('\Cake\ORM\Table')
  3657. ->setMethods(['_insert'])
  3658. ->setConstructorArgs([['table' => 'articles', 'connection' => $this->connection]])
  3659. ->getMock();
  3660. $authors = $this->getMockBuilder('\Cake\ORM\Table')
  3661. ->setMethods(['_insert'])
  3662. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3663. ->getMock();
  3664. $supervisors = $this->getMockBuilder('\Cake\ORM\Table')
  3665. ->setMethods(['_insert', 'validate'])
  3666. ->setConstructorArgs([[
  3667. 'table' => 'authors',
  3668. 'alias' => 'supervisors',
  3669. 'connection' => $this->connection,
  3670. ]])
  3671. ->getMock();
  3672. $tags = $this->getMockBuilder('\Cake\ORM\Table')
  3673. ->setMethods(['_insert'])
  3674. ->setConstructorArgs([['table' => 'tags', 'connection' => $this->connection]])
  3675. ->getMock();
  3676. $articles->belongsTo('authors', ['targetTable' => $authors]);
  3677. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  3678. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  3679. $entity = new Entity([
  3680. 'title' => 'bar',
  3681. 'author' => new Entity([
  3682. 'name' => 'Juan',
  3683. 'supervisor' => new Entity(['name' => 'Marc']),
  3684. 'tags' => [
  3685. new Entity(['name' => 'foo']),
  3686. ],
  3687. ]),
  3688. ]);
  3689. $entity->setNew(true);
  3690. $entity->author->setNew(true);
  3691. $entity->author->supervisor->setNew(true);
  3692. $entity->author->tags[0]->setNew(true);
  3693. $articles->expects($this->once())
  3694. ->method('_insert')
  3695. ->with($entity, ['title' => 'bar'])
  3696. ->will($this->returnValue($entity));
  3697. $authors->expects($this->once())
  3698. ->method('_insert')
  3699. ->with($entity->author, ['name' => 'Juan'])
  3700. ->will($this->returnValue($entity->author));
  3701. $supervisors->expects($this->once())
  3702. ->method('_insert')
  3703. ->with($entity->author->supervisor, ['name' => 'Marc'])
  3704. ->will($this->returnValue($entity->author->supervisor));
  3705. $tags->expects($this->never())->method('_insert');
  3706. $this->assertSame($entity, $articles->save($entity, [
  3707. 'associated' => [
  3708. 'authors' => [],
  3709. 'authors.supervisors' => [
  3710. 'atomic' => false,
  3711. 'associated' => false,
  3712. ],
  3713. ],
  3714. ]));
  3715. }
  3716. /**
  3717. * @return void
  3718. */
  3719. public function testBelongsToFluentInterface()
  3720. {
  3721. /** @var \TestApp\Model\Table\ArticlesTable $articles */
  3722. $articles = $this->getMockBuilder(Table::class)
  3723. ->setMethods(['_insert'])
  3724. ->setConstructorArgs([['table' => 'articles', 'connection' => $this->connection]])
  3725. ->getMock();
  3726. $authors = $this->getMockBuilder(Table::class)
  3727. ->setMethods(['_insert'])
  3728. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3729. ->getMock();
  3730. try {
  3731. $articles->belongsTo('authors')
  3732. ->setForeignKey('author_id')
  3733. ->setName('Authors')
  3734. ->setTarget($authors)
  3735. ->setBindingKey('id')
  3736. ->setConditions([])
  3737. ->setFinder('list')
  3738. ->setProperty('authors')
  3739. ->setJoinType('inner');
  3740. } catch (\BadMethodCallException $e) {
  3741. $this->fail('Method chaining should be ok');
  3742. }
  3743. $this->assertSame('articles', $articles->getTable());
  3744. }
  3745. /**
  3746. * @return void
  3747. */
  3748. public function testHasOneFluentInterface()
  3749. {
  3750. /** @var \TestApp\Model\Table\AuthorsTable $authors */
  3751. $authors = $this->getMockBuilder(Table::class)
  3752. ->setMethods(['_insert'])
  3753. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3754. ->getMock();
  3755. try {
  3756. $authors->hasOne('articles')
  3757. ->setForeignKey('author_id')
  3758. ->setName('Articles')
  3759. ->setDependent(true)
  3760. ->setBindingKey('id')
  3761. ->setConditions([])
  3762. ->setCascadeCallbacks(true)
  3763. ->setFinder('list')
  3764. ->setStrategy('select')
  3765. ->setProperty('authors')
  3766. ->setJoinType('inner');
  3767. } catch (\BadMethodCallException $e) {
  3768. $this->fail('Method chaining should be ok');
  3769. }
  3770. $this->assertSame('authors', $authors->getTable());
  3771. }
  3772. /**
  3773. * @return void
  3774. */
  3775. public function testHasManyFluentInterface()
  3776. {
  3777. /** @var \TestApp\Model\Table\AuthorsTable $authors */
  3778. $authors = $this->getMockBuilder(Table::class)
  3779. ->setMethods(['_insert'])
  3780. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3781. ->getMock();
  3782. try {
  3783. $authors->hasMany('articles')
  3784. ->setForeignKey('author_id')
  3785. ->setName('Articles')
  3786. ->setDependent(true)
  3787. ->setSort(['created' => 'DESC'])
  3788. ->setBindingKey('id')
  3789. ->setConditions([])
  3790. ->setCascadeCallbacks(true)
  3791. ->setFinder('list')
  3792. ->setStrategy('select')
  3793. ->setSaveStrategy('replace')
  3794. ->setProperty('authors')
  3795. ->setJoinType('inner');
  3796. } catch (\BadMethodCallException $e) {
  3797. $this->fail('Method chaining should be ok');
  3798. }
  3799. $this->assertSame('authors', $authors->getTable());
  3800. }
  3801. /**
  3802. * @return void
  3803. */
  3804. public function testBelongsToManyFluentInterface()
  3805. {
  3806. /** @var \TestApp\Model\Table\AuthorsTable $authors */
  3807. $authors = $this->getMockBuilder(Table::class)
  3808. ->setMethods(['_insert'])
  3809. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3810. ->getMock();
  3811. try {
  3812. $authors->belongsToMany('articles')
  3813. ->setForeignKey('author_id')
  3814. ->setName('Articles')
  3815. ->setDependent(true)
  3816. ->setTargetForeignKey('article_id')
  3817. ->setBindingKey('id')
  3818. ->setConditions([])
  3819. ->setFinder('list')
  3820. ->setProperty('authors')
  3821. ->setSource($authors)
  3822. ->setStrategy('select')
  3823. ->setSaveStrategy('append')
  3824. ->setThrough('author_articles')
  3825. ->setJoinType('inner');
  3826. } catch (\BadMethodCallException $e) {
  3827. $this->fail('Method chaining should be ok');
  3828. }
  3829. $this->assertSame('authors', $authors->getTable());
  3830. }
  3831. /**
  3832. * Integration test for linking entities with belongsToMany
  3833. *
  3834. * @return void
  3835. */
  3836. public function testLinkBelongsToMany()
  3837. {
  3838. $table = $this->getTableLocator()->get('articles');
  3839. $table->belongsToMany('tags');
  3840. $tagsTable = $this->getTableLocator()->get('tags');
  3841. $source = ['source' => 'tags'];
  3842. $options = ['markNew' => false];
  3843. $article = new Entity([
  3844. 'id' => 1,
  3845. ], $options);
  3846. $newTag = new \TestApp\Model\Entity\Tag([
  3847. 'name' => 'Foo',
  3848. 'description' => 'Foo desc',
  3849. 'created' => null,
  3850. ], $source);
  3851. $tags[] = new \TestApp\Model\Entity\Tag([
  3852. 'id' => 3,
  3853. ], $options + $source);
  3854. $tags[] = $newTag;
  3855. $tagsTable->save($newTag);
  3856. $table->getAssociation('tags')->link($article, $tags);
  3857. $this->assertEquals($article->tags, $tags);
  3858. foreach ($tags as $tag) {
  3859. $this->assertFalse($tag->isNew());
  3860. }
  3861. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3862. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  3863. $this->assertEquals($article->tags[3], $tags[1]);
  3864. }
  3865. /**
  3866. * Integration test for linking entities with HasMany
  3867. *
  3868. * @return void
  3869. */
  3870. public function testLinkHasMany()
  3871. {
  3872. $authors = $this->getTableLocator()->get('Authors');
  3873. $articles = $this->getTableLocator()->get('Articles');
  3874. $authors->hasMany('Articles', [
  3875. 'foreignKey' => 'author_id',
  3876. ]);
  3877. $author = $authors->newEntity(['name' => 'mylux']);
  3878. $author = $authors->save($author);
  3879. $newArticles = $articles->newEntities(
  3880. [
  3881. [
  3882. 'title' => 'New bakery next corner',
  3883. 'body' => 'They sell tastefull cakes',
  3884. ],
  3885. [
  3886. 'title' => 'Spicy cake recipe',
  3887. 'body' => 'chocolate and peppers',
  3888. ],
  3889. ]
  3890. );
  3891. $sizeArticles = count($newArticles);
  3892. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3893. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3894. $this->assertCount($sizeArticles, $author->articles);
  3895. $this->assertFalse($author->isDirty('articles'));
  3896. }
  3897. /**
  3898. * Integration test for linking entities with HasMany combined with ReplaceSaveStrategy. It must append, not unlinking anything
  3899. *
  3900. * @return void
  3901. */
  3902. public function testLinkHasManyReplaceSaveStrategy()
  3903. {
  3904. $authors = $this->getTableLocator()->get('Authors');
  3905. $articles = $this->getTableLocator()->get('Articles');
  3906. $authors->hasMany('Articles', [
  3907. 'foreignKey' => 'author_id',
  3908. 'saveStrategy' => 'replace',
  3909. ]);
  3910. $author = $authors->newEntity(['name' => 'mylux']);
  3911. $author = $authors->save($author);
  3912. $newArticles = $articles->newEntities(
  3913. [
  3914. [
  3915. 'title' => 'New bakery next corner',
  3916. 'body' => 'They sell tastefull cakes',
  3917. ],
  3918. [
  3919. 'title' => 'Spicy cake recipe',
  3920. 'body' => 'chocolate and peppers',
  3921. ],
  3922. ]
  3923. );
  3924. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3925. $sizeArticles = count($newArticles);
  3926. $newArticles = $articles->newEntities(
  3927. [
  3928. [
  3929. 'title' => 'Nothing but the cake',
  3930. 'body' => 'It is all that we need',
  3931. ],
  3932. ]
  3933. );
  3934. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3935. $sizeArticles++;
  3936. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3937. $this->assertCount($sizeArticles, $author->articles);
  3938. $this->assertFalse($author->isDirty('articles'));
  3939. }
  3940. /**
  3941. * Integration test for linking entities with HasMany. The input contains already linked entities and they should not appeat duplicated
  3942. *
  3943. * @return void
  3944. */
  3945. public function testLinkHasManyExisting()
  3946. {
  3947. $authors = $this->getTableLocator()->get('Authors');
  3948. $articles = $this->getTableLocator()->get('Articles');
  3949. $authors->hasMany('Articles', [
  3950. 'foreignKey' => 'author_id',
  3951. 'saveStrategy' => 'replace',
  3952. ]);
  3953. $author = $authors->newEntity(['name' => 'mylux']);
  3954. $author = $authors->save($author);
  3955. $newArticles = $articles->newEntities(
  3956. [
  3957. [
  3958. 'title' => 'New bakery next corner',
  3959. 'body' => 'They sell tastefull cakes',
  3960. ],
  3961. [
  3962. 'title' => 'Spicy cake recipe',
  3963. 'body' => 'chocolate and peppers',
  3964. ],
  3965. ]
  3966. );
  3967. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3968. $sizeArticles = count($newArticles);
  3969. $newArticles = array_merge(
  3970. $author->articles,
  3971. $articles->newEntities(
  3972. [
  3973. [
  3974. 'title' => 'Nothing but the cake',
  3975. 'body' => 'It is all that we need',
  3976. ],
  3977. ]
  3978. )
  3979. );
  3980. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3981. $sizeArticles++;
  3982. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3983. $this->assertCount($sizeArticles, $author->articles);
  3984. $this->assertFalse($author->isDirty('articles'));
  3985. }
  3986. /**
  3987. * Integration test for unlinking entities with HasMany. The association property must be cleaned
  3988. *
  3989. * @return void
  3990. */
  3991. public function testUnlinkHasManyCleanProperty()
  3992. {
  3993. $authors = $this->getTableLocator()->get('Authors');
  3994. $articles = $this->getTableLocator()->get('Articles');
  3995. $authors->hasMany('Articles', [
  3996. 'foreignKey' => 'author_id',
  3997. 'saveStrategy' => 'replace',
  3998. ]);
  3999. $author = $authors->newEntity(['name' => 'mylux']);
  4000. $author = $authors->save($author);
  4001. $newArticles = $articles->newEntities(
  4002. [
  4003. [
  4004. 'title' => 'New bakery next corner',
  4005. 'body' => 'They sell tastefull cakes',
  4006. ],
  4007. [
  4008. 'title' => 'Spicy cake recipe',
  4009. 'body' => 'chocolate and peppers',
  4010. ],
  4011. [
  4012. 'title' => 'Creamy cake recipe',
  4013. 'body' => 'chocolate and cream',
  4014. ],
  4015. ]
  4016. );
  4017. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4018. $sizeArticles = count($newArticles);
  4019. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  4020. $authors->Articles->unlink($author, $articlesToUnlink);
  4021. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  4022. $this->assertCount($sizeArticles - count($articlesToUnlink), $author->articles);
  4023. $this->assertFalse($author->isDirty('articles'));
  4024. }
  4025. /**
  4026. * Integration test for unlinking entities with HasMany. The association property must stay unchanged
  4027. *
  4028. * @return void
  4029. */
  4030. public function testUnlinkHasManyNotCleanProperty()
  4031. {
  4032. $authors = $this->getTableLocator()->get('Authors');
  4033. $articles = $this->getTableLocator()->get('Articles');
  4034. $authors->hasMany('Articles', [
  4035. 'foreignKey' => 'author_id',
  4036. 'saveStrategy' => 'replace',
  4037. ]);
  4038. $author = $authors->newEntity(['name' => 'mylux']);
  4039. $author = $authors->save($author);
  4040. $newArticles = $articles->newEntities(
  4041. [
  4042. [
  4043. 'title' => 'New bakery next corner',
  4044. 'body' => 'They sell tastefull cakes',
  4045. ],
  4046. [
  4047. 'title' => 'Spicy cake recipe',
  4048. 'body' => 'chocolate and peppers',
  4049. ],
  4050. [
  4051. 'title' => 'Creamy cake recipe',
  4052. 'body' => 'chocolate and cream',
  4053. ],
  4054. ]
  4055. );
  4056. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4057. $sizeArticles = count($newArticles);
  4058. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  4059. $authors->Articles->unlink($author, $articlesToUnlink, ['cleanProperty' => false]);
  4060. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  4061. $this->assertCount($sizeArticles, $author->articles);
  4062. $this->assertFalse($author->isDirty('articles'));
  4063. }
  4064. /**
  4065. * Integration test for unlinking entities with HasMany.
  4066. * Checking that no error happens when the hasMany property is originally
  4067. * null
  4068. *
  4069. * @return void
  4070. */
  4071. public function testUnlinkHasManyEmpty()
  4072. {
  4073. $authors = $this->getTableLocator()->get('Authors');
  4074. $articles = $this->getTableLocator()->get('Articles');
  4075. $authors->hasMany('Articles');
  4076. $author = $authors->get(1);
  4077. $article = $authors->Articles->get(1);
  4078. $authors->Articles->unlink($author, [$article]);
  4079. $this->assertNotEmpty($authors);
  4080. }
  4081. /**
  4082. * Integration test for replacing entities which depend on their source entity with HasMany and failing transaction. False should be returned when
  4083. * unlinking fails while replacing even when cascadeCallbacks is enabled
  4084. *
  4085. * @return void
  4086. */
  4087. public function testReplaceHasManyOnErrorDependentCascadeCallbacks()
  4088. {
  4089. $articles = $this->getMockBuilder('Cake\ORM\Table')
  4090. ->setMethods(['delete'])
  4091. ->setConstructorArgs([[
  4092. 'connection' => $this->connection,
  4093. 'alias' => 'Articles',
  4094. 'table' => 'articles',
  4095. ]])
  4096. ->getMock();
  4097. $articles->method('delete')->willReturn(false);
  4098. $associations = new AssociationCollection();
  4099. $hasManyArticles = $this->getMockBuilder('Cake\ORM\Association\HasMany')
  4100. ->setMethods(['getTarget'])
  4101. ->setConstructorArgs([
  4102. 'articles',
  4103. [
  4104. 'target' => $articles,
  4105. 'foreignKey' => 'author_id',
  4106. 'dependent' => true,
  4107. 'cascadeCallbacks' => true,
  4108. ],
  4109. ])
  4110. ->getMock();
  4111. $hasManyArticles->method('getTarget')->willReturn($articles);
  4112. $associations->add('articles', $hasManyArticles);
  4113. $authors = new Table([
  4114. 'connection' => $this->connection,
  4115. 'alias' => 'Authors',
  4116. 'table' => 'authors',
  4117. 'associations' => $associations,
  4118. ]);
  4119. $authors->Articles->setSource($authors);
  4120. $author = $authors->newEntity(['name' => 'mylux']);
  4121. $author = $authors->save($author);
  4122. $newArticles = $articles->newEntities(
  4123. [
  4124. [
  4125. 'title' => 'New bakery next corner',
  4126. 'body' => 'They sell tastefull cakes',
  4127. ],
  4128. [
  4129. 'title' => 'Spicy cake recipe',
  4130. 'body' => 'chocolate and peppers',
  4131. ],
  4132. ]
  4133. );
  4134. $sizeArticles = count($newArticles);
  4135. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4136. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  4137. $this->assertCount($sizeArticles, $author->articles);
  4138. $newArticles = array_merge(
  4139. $author->articles,
  4140. $articles->newEntities(
  4141. [
  4142. [
  4143. 'title' => 'Cheese cake recipe',
  4144. 'body' => 'The secrets of mixing salt and sugar',
  4145. ],
  4146. [
  4147. 'title' => 'Not another piece of cake',
  4148. 'body' => 'This is the best',
  4149. ],
  4150. ]
  4151. )
  4152. );
  4153. unset($newArticles[0]);
  4154. $this->assertFalse($authors->Articles->replace($author, $newArticles));
  4155. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  4156. }
  4157. /**
  4158. * Integration test for replacing entities with HasMany and an empty target list. The transaction must be successful
  4159. *
  4160. * @return void
  4161. */
  4162. public function testReplaceHasManyEmptyList()
  4163. {
  4164. $authors = new Table([
  4165. 'connection' => $this->connection,
  4166. 'alias' => 'Authors',
  4167. 'table' => 'authors',
  4168. ]);
  4169. $authors->hasMany('Articles');
  4170. $author = $authors->newEntity(['name' => 'mylux']);
  4171. $author = $authors->save($author);
  4172. $newArticles = $authors->Articles->newEntities(
  4173. [
  4174. [
  4175. 'title' => 'New bakery next corner',
  4176. 'body' => 'They sell tastefull cakes',
  4177. ],
  4178. [
  4179. 'title' => 'Spicy cake recipe',
  4180. 'body' => 'chocolate and peppers',
  4181. ],
  4182. ]
  4183. );
  4184. $sizeArticles = count($newArticles);
  4185. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4186. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  4187. $this->assertCount($sizeArticles, $author->articles);
  4188. $newArticles = [];
  4189. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  4190. $this->assertCount(0, $authors->Articles->findAllByAuthorId($author->id));
  4191. }
  4192. /**
  4193. * Integration test for replacing entities with HasMany and no already persisted entities. The transaction must be successful.
  4194. * Replace operation should prevent considering 0 changed records an error when they are not found in the table
  4195. *
  4196. * @return void
  4197. */
  4198. public function testReplaceHasManyNoPersistedEntities()
  4199. {
  4200. $authors = new Table([
  4201. 'connection' => $this->connection,
  4202. 'alias' => 'Authors',
  4203. 'table' => 'authors',
  4204. ]);
  4205. $authors->hasMany('Articles');
  4206. $author = $authors->newEntity(['name' => 'mylux']);
  4207. $author = $authors->save($author);
  4208. $newArticles = $authors->Articles->newEntities(
  4209. [
  4210. [
  4211. 'title' => 'New bakery next corner',
  4212. 'body' => 'They sell tastefull cakes',
  4213. ],
  4214. [
  4215. 'title' => 'Spicy cake recipe',
  4216. 'body' => 'chocolate and peppers',
  4217. ],
  4218. ]
  4219. );
  4220. $authors->Articles->deleteAll(['1=1']);
  4221. $sizeArticles = count($newArticles);
  4222. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4223. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  4224. $this->assertCount($sizeArticles, $author->articles);
  4225. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  4226. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  4227. }
  4228. /**
  4229. * Integration test for replacing entities with HasMany.
  4230. *
  4231. * @return void
  4232. */
  4233. public function testReplaceHasMany()
  4234. {
  4235. $authors = $this->getTableLocator()->get('Authors');
  4236. $articles = $this->getTableLocator()->get('Articles');
  4237. $authors->hasMany('Articles', [
  4238. 'foreignKey' => 'author_id',
  4239. ]);
  4240. $author = $authors->newEntity(['name' => 'mylux']);
  4241. $author = $authors->save($author);
  4242. $newArticles = $articles->newEntities(
  4243. [
  4244. [
  4245. 'title' => 'New bakery next corner',
  4246. 'body' => 'They sell tastefull cakes',
  4247. ],
  4248. [
  4249. 'title' => 'Spicy cake recipe',
  4250. 'body' => 'chocolate and peppers',
  4251. ],
  4252. ]
  4253. );
  4254. $sizeArticles = count($newArticles);
  4255. $this->assertTrue($authors->Articles->link($author, $newArticles));
  4256. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  4257. $this->assertCount($sizeArticles, $author->articles);
  4258. $newArticles = array_merge(
  4259. $author->articles,
  4260. $articles->newEntities(
  4261. [
  4262. [
  4263. 'title' => 'Cheese cake recipe',
  4264. 'body' => 'The secrets of mixing salt and sugar',
  4265. ],
  4266. [
  4267. 'title' => 'Not another piece of cake',
  4268. 'body' => 'This is the best',
  4269. ],
  4270. ]
  4271. )
  4272. );
  4273. unset($newArticles[0]);
  4274. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  4275. $this->assertCount(count($newArticles), $author->articles);
  4276. $this->assertEquals((new Collection($newArticles))->extract('title'), (new Collection($author->articles))->extract('title'));
  4277. }
  4278. /**
  4279. * Integration test to show how to unlink a single record from a belongsToMany
  4280. *
  4281. * @return void
  4282. */
  4283. public function testUnlinkBelongsToMany()
  4284. {
  4285. $table = $this->getTableLocator()->get('articles');
  4286. $table->belongsToMany('tags');
  4287. $tagsTable = $this->getTableLocator()->get('tags');
  4288. $options = ['markNew' => false];
  4289. $article = $table->find('all')
  4290. ->where(['id' => 1])
  4291. ->contain(['tags'])->first();
  4292. $table->getAssociation('tags')->unlink($article, [$article->tags[0]]);
  4293. $this->assertCount(1, $article->tags);
  4294. $this->assertEquals(2, $article->tags[0]->get('id'));
  4295. $this->assertFalse($article->isDirty('tags'));
  4296. }
  4297. /**
  4298. * Integration test to show how to unlink multiple records from a belongsToMany
  4299. *
  4300. * @return void
  4301. */
  4302. public function testUnlinkBelongsToManyMultiple()
  4303. {
  4304. $table = $this->getTableLocator()->get('articles');
  4305. $table->belongsToMany('tags');
  4306. $tagsTable = $this->getTableLocator()->get('tags');
  4307. $options = ['markNew' => false];
  4308. $article = new Entity(['id' => 1], $options);
  4309. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  4310. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4311. $table->getAssociation('tags')->unlink($article, $tags);
  4312. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4313. $this->assertEmpty($left->tags);
  4314. }
  4315. /**
  4316. * Integration test to show how to unlink multiple records from a belongsToMany
  4317. * providing some of the joint
  4318. *
  4319. * @return void
  4320. */
  4321. public function testUnlinkBelongsToManyPassingJoint()
  4322. {
  4323. $table = $this->getTableLocator()->get('articles');
  4324. $table->belongsToMany('tags');
  4325. $tagsTable = $this->getTableLocator()->get('tags');
  4326. $options = ['markNew' => false];
  4327. $article = new Entity(['id' => 1], $options);
  4328. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  4329. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4330. $tags[1]->_joinData = new Entity([
  4331. 'article_id' => 1,
  4332. 'tag_id' => 2,
  4333. ], $options);
  4334. $table->getAssociation('tags')->unlink($article, $tags);
  4335. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4336. $this->assertEmpty($left->tags);
  4337. }
  4338. /**
  4339. * Integration test to show how to replace records from a belongsToMany
  4340. *
  4341. * @return void
  4342. */
  4343. public function testReplacelinksBelongsToMany()
  4344. {
  4345. $table = $this->getTableLocator()->get('articles');
  4346. $table->belongsToMany('tags');
  4347. $tagsTable = $this->getTableLocator()->get('tags');
  4348. $options = ['markNew' => false];
  4349. $article = new Entity(['id' => 1], $options);
  4350. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4351. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  4352. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  4353. $table->getAssociation('tags')->replaceLinks($article, $tags);
  4354. $this->assertEquals(2, $article->tags[0]->id);
  4355. $this->assertEquals(3, $article->tags[1]->id);
  4356. $this->assertEquals(4, $article->tags[2]->id);
  4357. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4358. $this->assertCount(3, $article->tags);
  4359. $this->assertEquals(2, $article->tags[0]->id);
  4360. $this->assertEquals(3, $article->tags[1]->id);
  4361. $this->assertEquals(4, $article->tags[2]->id);
  4362. $this->assertEquals('foo', $article->tags[2]->name);
  4363. }
  4364. /**
  4365. * Integration test to show how remove all links from a belongsToMany
  4366. *
  4367. * @return void
  4368. */
  4369. public function testReplacelinksBelongsToManyWithEmpty()
  4370. {
  4371. $table = $this->getTableLocator()->get('articles');
  4372. $table->belongsToMany('tags');
  4373. $tagsTable = $this->getTableLocator()->get('tags');
  4374. $options = ['markNew' => false];
  4375. $article = new Entity(['id' => 1], $options);
  4376. $tags = [];
  4377. $table->getAssociation('tags')->replaceLinks($article, $tags);
  4378. $this->assertSame($tags, $article->tags);
  4379. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4380. $this->assertEmpty($article->tags);
  4381. }
  4382. /**
  4383. * Integration test to show how to replace records from a belongsToMany
  4384. * passing the joint property along in the target entity
  4385. *
  4386. * @return void
  4387. */
  4388. public function testReplacelinksBelongsToManyWithJoint()
  4389. {
  4390. $table = $this->getTableLocator()->get('articles');
  4391. $table->belongsToMany('tags');
  4392. $tagsTable = $this->getTableLocator()->get('tags');
  4393. $options = ['markNew' => false];
  4394. $article = new Entity(['id' => 1], $options);
  4395. $tags[] = new \TestApp\Model\Entity\Tag([
  4396. 'id' => 2,
  4397. '_joinData' => new Entity([
  4398. 'article_id' => 1,
  4399. 'tag_id' => 2,
  4400. ]),
  4401. ], $options);
  4402. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  4403. $table->getAssociation('tags')->replaceLinks($article, $tags);
  4404. $this->assertSame($tags, $article->tags);
  4405. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4406. $this->assertCount(2, $article->tags);
  4407. $this->assertEquals(2, $article->tags[0]->id);
  4408. $this->assertEquals(3, $article->tags[1]->id);
  4409. }
  4410. /**
  4411. * Tests that options are being passed through to the internal table method calls.
  4412. *
  4413. * @return void
  4414. */
  4415. public function testOptionsBeingPassedToImplicitBelongsToManyDeletesUsingSaveReplace()
  4416. {
  4417. $articles = $this->getTableLocator()->get('Articles');
  4418. $tags = $articles->belongsToMany('Tags');
  4419. $tags->setSaveStrategy(BelongsToMany::SAVE_REPLACE)
  4420. ->setDependent(true)
  4421. ->setCascadeCallbacks(true);
  4422. $actualOptions = null;
  4423. $tags->junction()->getEventManager()->on(
  4424. 'Model.beforeDelete',
  4425. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4426. $actualOptions = $options->getArrayCopy();
  4427. }
  4428. );
  4429. $article = $articles->get(1);
  4430. $article->tags = [];
  4431. $article->setDirty('tags', true);
  4432. $result = $articles->save($article, ['foo' => 'bar']);
  4433. $this->assertNotEmpty($result);
  4434. $expected = [
  4435. '_primary' => false,
  4436. 'foo' => 'bar',
  4437. 'atomic' => true,
  4438. 'checkRules' => true,
  4439. 'checkExisting' => true,
  4440. ];
  4441. $this->assertEquals($expected, $actualOptions);
  4442. }
  4443. /**
  4444. * Tests that options are being passed through to the internal table method calls.
  4445. *
  4446. * @return void
  4447. */
  4448. public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyLink()
  4449. {
  4450. $articles = $this->getTableLocator()->get('Articles');
  4451. $tags = $articles->belongsToMany('Tags');
  4452. $actualOptions = null;
  4453. $tags->junction()->getEventManager()->on(
  4454. 'Model.beforeSave',
  4455. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4456. $actualOptions = $options->getArrayCopy();
  4457. }
  4458. );
  4459. $article = $articles->get(1);
  4460. $result = $tags->link($article, [$tags->getTarget()->get(2)], ['foo' => 'bar']);
  4461. $this->assertTrue($result);
  4462. $expected = [
  4463. '_primary' => true,
  4464. 'foo' => 'bar',
  4465. 'atomic' => true,
  4466. 'checkRules' => true,
  4467. 'checkExisting' => true,
  4468. 'associated' => [
  4469. 'articles' => [],
  4470. 'tags' => [],
  4471. ],
  4472. ];
  4473. $this->assertEquals($expected, $actualOptions);
  4474. }
  4475. /**
  4476. * Tests that options are being passed through to the internal table method calls.
  4477. *
  4478. * @return void
  4479. */
  4480. public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyUnlink()
  4481. {
  4482. $articles = $this->getTableLocator()->get('Articles');
  4483. $tags = $articles->belongsToMany('Tags');
  4484. $actualOptions = null;
  4485. $tags->junction()->getEventManager()->on(
  4486. 'Model.beforeDelete',
  4487. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4488. $actualOptions = $options->getArrayCopy();
  4489. }
  4490. );
  4491. $article = $articles->get(1);
  4492. $tags->unlink($article, [$tags->getTarget()->get(2)], ['foo' => 'bar']);
  4493. $expected = [
  4494. '_primary' => true,
  4495. 'foo' => 'bar',
  4496. 'atomic' => true,
  4497. 'checkRules' => true,
  4498. 'cleanProperty' => true,
  4499. ];
  4500. $this->assertEquals($expected, $actualOptions);
  4501. }
  4502. /**
  4503. * Tests that options are being passed through to the internal table method calls.
  4504. *
  4505. * @return void
  4506. */
  4507. public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingBelongsToManyReplaceLinks()
  4508. {
  4509. $articles = $this->getTableLocator()->get('Articles');
  4510. $tags = $articles->belongsToMany('Tags');
  4511. $actualSaveOptions = null;
  4512. $actualDeleteOptions = null;
  4513. $tags->junction()->getEventManager()->on(
  4514. 'Model.beforeSave',
  4515. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) {
  4516. $actualSaveOptions = $options->getArrayCopy();
  4517. }
  4518. );
  4519. $tags->junction()->getEventManager()->on(
  4520. 'Model.beforeDelete',
  4521. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) {
  4522. $actualDeleteOptions = $options->getArrayCopy();
  4523. }
  4524. );
  4525. $article = $articles->get(1);
  4526. $result = $tags->replaceLinks(
  4527. $article,
  4528. [
  4529. $tags->getTarget()->newEntity(['name' => 'new']),
  4530. $tags->getTarget()->get(2),
  4531. ],
  4532. ['foo' => 'bar']
  4533. );
  4534. $this->assertTrue($result);
  4535. $expected = [
  4536. '_primary' => true,
  4537. 'foo' => 'bar',
  4538. 'atomic' => true,
  4539. 'checkRules' => true,
  4540. 'checkExisting' => true,
  4541. 'associated' => [],
  4542. ];
  4543. $this->assertEquals($expected, $actualSaveOptions);
  4544. $expected = [
  4545. '_primary' => true,
  4546. 'foo' => 'bar',
  4547. 'atomic' => true,
  4548. 'checkRules' => true,
  4549. ];
  4550. $this->assertEquals($expected, $actualDeleteOptions);
  4551. }
  4552. /**
  4553. * Tests that options are being passed through to the internal table method calls.
  4554. *
  4555. * @return void
  4556. */
  4557. public function testOptionsBeingPassedToImplicitHasManyDeletesUsingSaveReplace()
  4558. {
  4559. $authors = $this->getTableLocator()->get('Authors');
  4560. $articles = $authors->hasMany('Articles');
  4561. $articles->setSaveStrategy(HasMany::SAVE_REPLACE)
  4562. ->setDependent(true)
  4563. ->setCascadeCallbacks(true);
  4564. $actualOptions = null;
  4565. $articles->getTarget()->getEventManager()->on(
  4566. 'Model.beforeDelete',
  4567. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4568. $actualOptions = $options->getArrayCopy();
  4569. }
  4570. );
  4571. $author = $authors->get(1);
  4572. $author->articles = [];
  4573. $author->setDirty('articles', true);
  4574. $result = $authors->save($author, ['foo' => 'bar']);
  4575. $this->assertNotEmpty($result);
  4576. $expected = [
  4577. '_primary' => false,
  4578. 'foo' => 'bar',
  4579. 'atomic' => true,
  4580. 'checkRules' => true,
  4581. 'checkExisting' => true,
  4582. '_sourceTable' => $authors,
  4583. ];
  4584. $this->assertEquals($expected, $actualOptions);
  4585. }
  4586. /**
  4587. * Tests that options are being passed through to the internal table method calls.
  4588. *
  4589. * @return void
  4590. */
  4591. public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyLink()
  4592. {
  4593. $authors = $this->getTableLocator()->get('Authors');
  4594. $articles = $authors->hasMany('Articles');
  4595. $actualOptions = null;
  4596. $articles->getTarget()->getEventManager()->on(
  4597. 'Model.beforeSave',
  4598. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4599. $actualOptions = $options->getArrayCopy();
  4600. }
  4601. );
  4602. $author = $authors->get(1);
  4603. $author->articles = [];
  4604. $author->setDirty('articles', true);
  4605. $result = $articles->link($author, [$articles->getTarget()->get(2)], ['foo' => 'bar']);
  4606. $this->assertTrue($result);
  4607. $expected = [
  4608. '_primary' => true,
  4609. 'foo' => 'bar',
  4610. 'atomic' => true,
  4611. 'checkRules' => true,
  4612. 'checkExisting' => true,
  4613. '_sourceTable' => $authors,
  4614. 'associated' => [
  4615. 'authors' => [],
  4616. 'tags' => [],
  4617. 'articlestags' => [],
  4618. ],
  4619. ];
  4620. $this->assertEquals($expected, $actualOptions);
  4621. }
  4622. /**
  4623. * Tests that options are being passed through to the internal table method calls.
  4624. *
  4625. * @return void
  4626. */
  4627. public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyUnlink()
  4628. {
  4629. $authors = $this->getTableLocator()->get('Authors');
  4630. $articles = $authors->hasMany('Articles');
  4631. $articles->setDependent(true);
  4632. $articles->setCascadeCallbacks(true);
  4633. $actualOptions = null;
  4634. $articles->getTarget()->getEventManager()->on(
  4635. 'Model.beforeDelete',
  4636. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4637. $actualOptions = $options->getArrayCopy();
  4638. }
  4639. );
  4640. $author = $authors->get(1);
  4641. $author->articles = [];
  4642. $author->setDirty('articles', true);
  4643. $articles->unlink($author, [$articles->getTarget()->get(1)], ['foo' => 'bar']);
  4644. $expected = [
  4645. '_primary' => true,
  4646. 'foo' => 'bar',
  4647. 'atomic' => true,
  4648. 'checkRules' => true,
  4649. 'cleanProperty' => true,
  4650. ];
  4651. $this->assertEquals($expected, $actualOptions);
  4652. }
  4653. /**
  4654. * Tests that options are being passed through to the internal table method calls.
  4655. *
  4656. * @return void
  4657. */
  4658. public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingHasManyReplace()
  4659. {
  4660. $authors = $this->getTableLocator()->get('Authors');
  4661. $articles = $authors->hasMany('Articles');
  4662. $articles->setDependent(true);
  4663. $articles->setCascadeCallbacks(true);
  4664. $actualSaveOptions = null;
  4665. $actualDeleteOptions = null;
  4666. $articles->getTarget()->getEventManager()->on(
  4667. 'Model.beforeSave',
  4668. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) {
  4669. $actualSaveOptions = $options->getArrayCopy();
  4670. }
  4671. );
  4672. $articles->getTarget()->getEventManager()->on(
  4673. 'Model.beforeDelete',
  4674. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) {
  4675. $actualDeleteOptions = $options->getArrayCopy();
  4676. }
  4677. );
  4678. $author = $authors->get(1);
  4679. $result = $articles->replace(
  4680. $author,
  4681. [
  4682. $articles->getTarget()->newEntity(['title' => 'new', 'body' => 'new']),
  4683. $articles->getTarget()->get(1),
  4684. ],
  4685. ['foo' => 'bar']
  4686. );
  4687. $this->assertTrue($result);
  4688. $expected = [
  4689. '_primary' => true,
  4690. 'foo' => 'bar',
  4691. 'atomic' => true,
  4692. 'checkRules' => true,
  4693. 'checkExisting' => true,
  4694. '_sourceTable' => $authors,
  4695. 'associated' => [
  4696. 'authors' => [],
  4697. 'tags' => [],
  4698. 'articlestags' => [],
  4699. ],
  4700. ];
  4701. $this->assertEquals($expected, $actualSaveOptions);
  4702. $expected = [
  4703. '_primary' => true,
  4704. 'foo' => 'bar',
  4705. 'atomic' => true,
  4706. 'checkRules' => true,
  4707. '_sourceTable' => $authors,
  4708. ];
  4709. $this->assertEquals($expected, $actualDeleteOptions);
  4710. }
  4711. /**
  4712. * Tests backwards compatibility of the the `$options` argument, formerly `$cleanProperty`.
  4713. *
  4714. * @return void
  4715. */
  4716. public function testBackwardsCompatibilityForBelongsToManyUnlinkCleanPropertyOption()
  4717. {
  4718. $articles = $this->getTableLocator()->get('Articles');
  4719. $tags = $articles->belongsToMany('Tags');
  4720. $actualOptions = null;
  4721. $tags->junction()->getEventManager()->on(
  4722. 'Model.beforeDelete',
  4723. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4724. $actualOptions = $options->getArrayCopy();
  4725. }
  4726. );
  4727. $article = $articles->get(1);
  4728. $tags->unlink($article, [$tags->getTarget()->get(1)], false);
  4729. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4730. $this->assertFalse($actualOptions['cleanProperty']);
  4731. $actualOptions = null;
  4732. $tags->unlink($article, [$tags->getTarget()->get(2)]);
  4733. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4734. $this->assertTrue($actualOptions['cleanProperty']);
  4735. }
  4736. /**
  4737. * Tests backwards compatibility of the the `$options` argument, formerly `$cleanProperty`.
  4738. *
  4739. * @return void
  4740. */
  4741. public function testBackwardsCompatibilityForHasManyUnlinkCleanPropertyOption()
  4742. {
  4743. $authors = $this->getTableLocator()->get('Authors');
  4744. $articles = $authors->hasMany('Articles');
  4745. $articles->setDependent(true);
  4746. $articles->setCascadeCallbacks(true);
  4747. $actualOptions = null;
  4748. $articles->getTarget()->getEventManager()->on(
  4749. 'Model.beforeDelete',
  4750. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4751. $actualOptions = $options->getArrayCopy();
  4752. }
  4753. );
  4754. $author = $authors->get(1);
  4755. $author->articles = [];
  4756. $author->setDirty('articles', true);
  4757. $articles->unlink($author, [$articles->getTarget()->get(1)], false);
  4758. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4759. $this->assertFalse($actualOptions['cleanProperty']);
  4760. $actualOptions = null;
  4761. $articles->unlink($author, [$articles->getTarget()->get(3)]);
  4762. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4763. $this->assertTrue($actualOptions['cleanProperty']);
  4764. }
  4765. /**
  4766. * Tests that it is possible to call find with no arguments
  4767. *
  4768. * @return void
  4769. */
  4770. public function testSimplifiedFind()
  4771. {
  4772. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4773. ->setMethods(['callFinder'])
  4774. ->setConstructorArgs([[
  4775. 'connection' => $this->connection,
  4776. 'schema' => ['id' => ['type' => 'integer']],
  4777. ]])
  4778. ->getMock();
  4779. $query = (new Query($this->connection, $table))->select();
  4780. $table->expects($this->once())->method('callFinder')
  4781. ->with('all', $query, []);
  4782. $table->find();
  4783. }
  4784. public function providerForTestGet()
  4785. {
  4786. return [
  4787. [ ['fields' => ['id']] ],
  4788. [ ['fields' => ['id'], 'cache' => false] ],
  4789. ];
  4790. }
  4791. /**
  4792. * Test that get() will use the primary key for searching and return the first
  4793. * entity found
  4794. *
  4795. * @dataProvider providerForTestGet
  4796. * @param array $options
  4797. * @return void
  4798. */
  4799. public function testGet($options)
  4800. {
  4801. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4802. ->setMethods(['callFinder', 'query'])
  4803. ->setConstructorArgs([[
  4804. 'connection' => $this->connection,
  4805. 'schema' => [
  4806. 'id' => ['type' => 'integer'],
  4807. 'bar' => ['type' => 'integer'],
  4808. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]],
  4809. ],
  4810. ]])
  4811. ->getMock();
  4812. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4813. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4814. ->setConstructorArgs([$this->connection, $table])
  4815. ->getMock();
  4816. $entity = new Entity();
  4817. $table->expects($this->once())->method('query')
  4818. ->will($this->returnValue($query));
  4819. $table->expects($this->once())->method('callFinder')
  4820. ->with('all', $query, ['fields' => ['id']])
  4821. ->will($this->returnValue($query));
  4822. $query->expects($this->once())->method('where')
  4823. ->with([$table->getAlias() . '.bar' => 10])
  4824. ->will($this->returnSelf());
  4825. $query->expects($this->never())->method('cache');
  4826. $query->expects($this->once())->method('firstOrFail')
  4827. ->will($this->returnValue($entity));
  4828. $result = $table->get(10, $options);
  4829. $this->assertSame($entity, $result);
  4830. }
  4831. public function providerForTestGetWithCustomFinder()
  4832. {
  4833. return [
  4834. [ ['fields' => ['id'], 'finder' => 'custom'] ],
  4835. ];
  4836. }
  4837. /**
  4838. * Test that get() will call a custom finder.
  4839. *
  4840. * @dataProvider providerForTestGetWithCustomFinder
  4841. * @param array $options
  4842. * @return void
  4843. */
  4844. public function testGetWithCustomFinder($options)
  4845. {
  4846. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4847. ->setMethods(['callFinder', 'query'])
  4848. ->setConstructorArgs([[
  4849. 'connection' => $this->connection,
  4850. 'schema' => [
  4851. 'id' => ['type' => 'integer'],
  4852. 'bar' => ['type' => 'integer'],
  4853. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]],
  4854. ],
  4855. ]])
  4856. ->getMock();
  4857. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4858. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4859. ->setConstructorArgs([$this->connection, $table])
  4860. ->getMock();
  4861. $entity = new Entity();
  4862. $table->expects($this->once())->method('query')
  4863. ->will($this->returnValue($query));
  4864. $table->expects($this->once())->method('callFinder')
  4865. ->with('custom', $query, ['fields' => ['id']])
  4866. ->will($this->returnValue($query));
  4867. $query->expects($this->once())->method('where')
  4868. ->with([$table->getAlias() . '.bar' => 10])
  4869. ->will($this->returnSelf());
  4870. $query->expects($this->never())->method('cache');
  4871. $query->expects($this->once())->method('firstOrFail')
  4872. ->will($this->returnValue($entity));
  4873. $result = $table->get(10, $options);
  4874. $this->assertSame($entity, $result);
  4875. }
  4876. public function providerForTestGetWithCache()
  4877. {
  4878. return [
  4879. [
  4880. ['fields' => ['id'], 'cache' => 'default'],
  4881. 'get:test.table_name[10]', 'default',
  4882. ],
  4883. [
  4884. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  4885. 'custom_key', 'default',
  4886. ],
  4887. ];
  4888. }
  4889. /**
  4890. * Test that get() will use the cache.
  4891. *
  4892. * @dataProvider providerForTestGetWithCache
  4893. * @param array $options
  4894. * @param string $cacheKey
  4895. * @param string $cacheConfig
  4896. * @return void
  4897. */
  4898. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  4899. {
  4900. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4901. ->setMethods(['callFinder', 'query'])
  4902. ->setConstructorArgs([[
  4903. 'connection' => $this->connection,
  4904. 'schema' => [
  4905. 'id' => ['type' => 'integer'],
  4906. 'bar' => ['type' => 'integer'],
  4907. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]],
  4908. ],
  4909. ]])
  4910. ->getMock();
  4911. $table->setTable('table_name');
  4912. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4913. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4914. ->setConstructorArgs([$this->connection, $table])
  4915. ->getMock();
  4916. $entity = new Entity();
  4917. $table->expects($this->once())->method('query')
  4918. ->will($this->returnValue($query));
  4919. $table->expects($this->once())->method('callFinder')
  4920. ->with('all', $query, ['fields' => ['id']])
  4921. ->will($this->returnValue($query));
  4922. $query->expects($this->once())->method('where')
  4923. ->with([$table->getAlias() . '.bar' => 10])
  4924. ->will($this->returnSelf());
  4925. $query->expects($this->once())->method('cache')
  4926. ->with($cacheKey, $cacheConfig)
  4927. ->will($this->returnSelf());
  4928. $query->expects($this->once())->method('firstOrFail')
  4929. ->will($this->returnValue($entity));
  4930. $result = $table->get(10, $options);
  4931. $this->assertSame($entity, $result);
  4932. }
  4933. /**
  4934. * Tests that get() will throw an exception if the record was not found
  4935. *
  4936. * @return void
  4937. */
  4938. public function testGetNotFoundException()
  4939. {
  4940. $this->expectException(\Cake\Datasource\Exception\RecordNotFoundException::class);
  4941. $this->expectExceptionMessage('Record not found in table "articles"');
  4942. $table = new Table([
  4943. 'name' => 'Articles',
  4944. 'connection' => $this->connection,
  4945. 'table' => 'articles',
  4946. ]);
  4947. $table->get(10);
  4948. }
  4949. /**
  4950. * Test that an exception is raised when there are not enough keys.
  4951. *
  4952. * @return void
  4953. */
  4954. public function testGetExceptionOnNoData()
  4955. {
  4956. $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class);
  4957. $this->expectExceptionMessage('Record not found in table "articles" with primary key [NULL]');
  4958. $table = new Table([
  4959. 'name' => 'Articles',
  4960. 'connection' => $this->connection,
  4961. 'table' => 'articles',
  4962. ]);
  4963. $table->get(null);
  4964. }
  4965. /**
  4966. * Test that an exception is raised when there are too many keys.
  4967. *
  4968. * @return void
  4969. */
  4970. public function testGetExceptionOnTooMuchData()
  4971. {
  4972. $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class);
  4973. $this->expectExceptionMessage('Record not found in table "articles" with primary key [1, \'two\']');
  4974. $table = new Table([
  4975. 'name' => 'Articles',
  4976. 'connection' => $this->connection,
  4977. 'table' => 'articles',
  4978. ]);
  4979. $table->get([1, 'two']);
  4980. }
  4981. /**
  4982. * Tests that patchEntity delegates the task to the marshaller and passed
  4983. * all associations
  4984. *
  4985. * @return void
  4986. */
  4987. public function testPatchEntityMarshallerUsage()
  4988. {
  4989. $table = $this->getMockBuilder('Cake\ORM\Table')
  4990. ->setMethods(['marshaller'])
  4991. ->getMock();
  4992. $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
  4993. ->setConstructorArgs([$table])
  4994. ->getMock();
  4995. $table->belongsTo('users');
  4996. $table->hasMany('articles');
  4997. $table->expects($this->once())->method('marshaller')
  4998. ->will($this->returnValue($marshaller));
  4999. $entity = new Entity();
  5000. $data = ['foo' => 'bar'];
  5001. $marshaller->expects($this->once())
  5002. ->method('merge')
  5003. ->with($entity, $data, ['associated' => ['users', 'articles']])
  5004. ->will($this->returnValue($entity));
  5005. $table->patchEntity($entity, $data);
  5006. }
  5007. /**
  5008. * Tests patchEntity in a simple scenario. The tests for Marshaller cover
  5009. * patch scenarios in more depth.
  5010. *
  5011. * @return void
  5012. */
  5013. public function testPatchEntity()
  5014. {
  5015. $table = $this->getTableLocator()->get('Articles');
  5016. $entity = new Entity(['title' => 'old title'], ['markNew' => false]);
  5017. $data = ['title' => 'new title'];
  5018. $entity = $table->patchEntity($entity, $data);
  5019. $this->assertSame($data['title'], $entity->title);
  5020. $this->assertFalse($entity->isNew(), 'entity should not be new.');
  5021. }
  5022. /**
  5023. * Tests that patchEntities delegates the task to the marshaller and passed
  5024. * all associations
  5025. *
  5026. * @return void
  5027. */
  5028. public function testPatchEntitiesMarshallerUsage()
  5029. {
  5030. $table = $this->getMockBuilder('Cake\ORM\Table')
  5031. ->setMethods(['marshaller'])
  5032. ->getMock();
  5033. $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
  5034. ->setConstructorArgs([$table])
  5035. ->getMock();
  5036. $table->belongsTo('users');
  5037. $table->hasMany('articles');
  5038. $table->expects($this->once())->method('marshaller')
  5039. ->will($this->returnValue($marshaller));
  5040. $entities = [new Entity()];
  5041. $data = [['foo' => 'bar']];
  5042. $marshaller->expects($this->once())
  5043. ->method('mergeMany')
  5044. ->with($entities, $data, ['associated' => ['users', 'articles']])
  5045. ->will($this->returnValue($entities));
  5046. $table->patchEntities($entities, $data);
  5047. }
  5048. /**
  5049. * Tests patchEntities in a simple scenario. The tests for Marshaller cover
  5050. * patch scenarios in more depth.
  5051. *
  5052. * @return void
  5053. */
  5054. public function testPatchEntities()
  5055. {
  5056. $table = $this->getTableLocator()->get('Articles');
  5057. $entities = $table->find()->limit(2)->toArray();
  5058. $data = [
  5059. ['id' => $entities[0]->id, 'title' => 'new title'],
  5060. ['id' => $entities[1]->id, 'title' => 'new title2'],
  5061. ];
  5062. $entities = $table->patchEntities($entities, $data);
  5063. foreach ($entities as $i => $entity) {
  5064. $this->assertFalse($entity->isNew(), 'entities should not be new.');
  5065. $this->assertSame($data[$i]['title'], $entity->title);
  5066. }
  5067. }
  5068. /**
  5069. * Tests __debugInfo
  5070. *
  5071. * @return void
  5072. */
  5073. public function testDebugInfo()
  5074. {
  5075. $articles = $this->getTableLocator()->get('articles');
  5076. $articles->addBehavior('Timestamp');
  5077. $result = $articles->__debugInfo();
  5078. $expected = [
  5079. 'registryAlias' => 'articles',
  5080. 'table' => 'articles',
  5081. 'alias' => 'articles',
  5082. 'entityClass' => 'TestApp\Model\Entity\Article',
  5083. 'associations' => ['authors', 'tags', 'articlestags'],
  5084. 'behaviors' => ['Timestamp'],
  5085. 'defaultConnection' => 'default',
  5086. 'connectionName' => 'test',
  5087. ];
  5088. $this->assertEquals($expected, $result);
  5089. $articles = $this->getTableLocator()->get('Foo.Articles');
  5090. $result = $articles->__debugInfo();
  5091. $expected = [
  5092. 'registryAlias' => 'Foo.Articles',
  5093. 'table' => 'articles',
  5094. 'alias' => 'Articles',
  5095. 'entityClass' => 'Cake\ORM\Entity',
  5096. 'associations' => [],
  5097. 'behaviors' => [],
  5098. 'defaultConnection' => 'default',
  5099. 'connectionName' => 'test',
  5100. ];
  5101. $this->assertEquals($expected, $result);
  5102. }
  5103. /**
  5104. * Test that findOrCreate creates a new entity, and then finds that entity.
  5105. *
  5106. * @return void
  5107. */
  5108. public function testFindOrCreateNewEntity()
  5109. {
  5110. $articles = $this->getTableLocator()->get('Articles');
  5111. $callbackExecuted = false;
  5112. $firstArticle = $articles->findOrCreate(['title' => 'Not there'], function ($article) use (&$callbackExecuted) {
  5113. $this->assertInstanceOf(EntityInterface::class, $article);
  5114. $article->body = 'New body';
  5115. $callbackExecuted = true;
  5116. });
  5117. $this->assertTrue($callbackExecuted);
  5118. $this->assertFalse($firstArticle->isNew());
  5119. $this->assertNotNull($firstArticle->id);
  5120. $this->assertEquals('Not there', $firstArticle->title);
  5121. $this->assertEquals('New body', $firstArticle->body);
  5122. $secondArticle = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  5123. $this->fail('Should not be called for existing entities.');
  5124. });
  5125. $this->assertFalse($secondArticle->isNew());
  5126. $this->assertNotNull($secondArticle->id);
  5127. $this->assertEquals('Not there', $secondArticle->title);
  5128. $this->assertEquals($firstArticle->id, $secondArticle->id);
  5129. }
  5130. /**
  5131. * Test that findOrCreate finds fixture data.
  5132. *
  5133. * @return void
  5134. */
  5135. public function testFindOrCreateExistingEntity()
  5136. {
  5137. $articles = $this->getTableLocator()->get('Articles');
  5138. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  5139. $this->fail('Should not be called for existing entities.');
  5140. });
  5141. $this->assertFalse($article->isNew());
  5142. $this->assertNotNull($article->id);
  5143. $this->assertEquals('First Article', $article->title);
  5144. }
  5145. /**
  5146. * Test that findOrCreate uses the search conditions as defaults for new entity.
  5147. *
  5148. * @return void
  5149. */
  5150. public function testFindOrCreateDefaults()
  5151. {
  5152. $articles = $this->getTableLocator()->get('Articles');
  5153. $callbackExecuted = false;
  5154. $article = $articles->findOrCreate(
  5155. ['author_id' => 2, 'title' => 'First Article'],
  5156. function ($article) use (&$callbackExecuted) {
  5157. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  5158. $article->set(['published' => 'N', 'body' => 'New body']);
  5159. $callbackExecuted = true;
  5160. }
  5161. );
  5162. $this->assertTrue($callbackExecuted);
  5163. $this->assertFalse($article->isNew());
  5164. $this->assertNotNull($article->id);
  5165. $this->assertEquals('First Article', $article->title);
  5166. $this->assertEquals('New body', $article->body);
  5167. $this->assertEquals('N', $article->published);
  5168. $this->assertEquals(2, $article->author_id);
  5169. $query = $articles->find()->where(['author_id' => 2, 'title' => 'First Article']);
  5170. $article = $articles->findOrCreate($query);
  5171. $this->assertEquals('First Article', $article->title);
  5172. $this->assertEquals(2, $article->author_id);
  5173. $this->assertFalse($article->isNew());
  5174. }
  5175. /**
  5176. * Test that findOrCreate adds new entity without using a callback.
  5177. *
  5178. * @return void
  5179. */
  5180. public function testFindOrCreateNoCallable()
  5181. {
  5182. $articles = $this->getTableLocator()->get('Articles');
  5183. $article = $articles->findOrCreate(['title' => 'Just Something New']);
  5184. $this->assertFalse($article->isNew());
  5185. $this->assertNotNull($article->id);
  5186. $this->assertEquals('Just Something New', $article->title);
  5187. }
  5188. /**
  5189. * Test that findOrCreate executes search conditions as a callable.
  5190. *
  5191. * @return void
  5192. */
  5193. public function testFindOrCreateSearchCallable()
  5194. {
  5195. $articles = $this->getTableLocator()->get('Articles');
  5196. $calledOne = false;
  5197. $calledTwo = false;
  5198. $article = $articles->findOrCreate(function ($query) use (&$calledOne) {
  5199. $this->assertInstanceOf('Cake\ORM\Query', $query);
  5200. $query->where(['title' => 'Something Else']);
  5201. $calledOne = true;
  5202. }, function ($article) use (&$calledTwo) {
  5203. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  5204. $article->title = 'Set Defaults Here';
  5205. $calledTwo = true;
  5206. });
  5207. $this->assertTrue($calledOne);
  5208. $this->assertTrue($calledTwo);
  5209. $this->assertFalse($article->isNew());
  5210. $this->assertNotNull($article->id);
  5211. $this->assertEquals('Set Defaults Here', $article->title);
  5212. }
  5213. /**
  5214. * Test that findOrCreate options disable defaults.
  5215. *
  5216. * @return void
  5217. */
  5218. public function testFindOrCreateNoDefaults()
  5219. {
  5220. $articles = $this->getTableLocator()->get('Articles');
  5221. $article = $articles->findOrCreate(['title' => 'A New Article', 'published' => 'Y'], function ($article) {
  5222. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  5223. $article->title = 'A Different Title';
  5224. }, ['defaults' => false]);
  5225. $this->assertFalse($article->isNew());
  5226. $this->assertNotNull($article->id);
  5227. $this->assertEquals('A Different Title', $article->title);
  5228. $this->assertNull($article->published, 'Expected Null since defaults are disabled.');
  5229. }
  5230. /**
  5231. * Test that findOrCreate executes callable inside transaction.
  5232. *
  5233. * @return void
  5234. */
  5235. public function testFindOrCreateTransactions()
  5236. {
  5237. $articles = $this->getTableLocator()->get('Articles');
  5238. $articles->getEventManager()->on('Model.afterSaveCommit', function (Event $event, EntityInterface $entity, ArrayObject $options) {
  5239. $entity->afterSaveCommit = true;
  5240. });
  5241. $article = $articles->findOrCreate(function ($query) {
  5242. $this->assertInstanceOf('Cake\ORM\Query', $query);
  5243. $query->where(['title' => 'Find Something New']);
  5244. $this->assertTrue($this->connection->inTransaction());
  5245. }, function ($article) {
  5246. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  5247. $article->title = 'Success';
  5248. $this->assertTrue($this->connection->inTransaction());
  5249. });
  5250. $this->assertFalse($article->isNew());
  5251. $this->assertNotNull($article->id);
  5252. $this->assertEquals('Success', $article->title);
  5253. $this->assertTrue($article->afterSaveCommit);
  5254. }
  5255. /**
  5256. * Test that findOrCreate executes callable without transaction.
  5257. *
  5258. * @return void
  5259. */
  5260. public function testFindOrCreateNoTransaction()
  5261. {
  5262. $articles = $this->getTableLocator()->get('Articles');
  5263. $article = $articles->findOrCreate(function ($query) {
  5264. $this->assertInstanceOf('Cake\ORM\Query', $query);
  5265. $query->where(['title' => 'Find Something New']);
  5266. $this->assertFalse($this->connection->inTransaction());
  5267. }, function ($article) {
  5268. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  5269. $this->assertFalse($this->connection->inTransaction());
  5270. $article->title = 'Success';
  5271. }, ['atomic' => false]);
  5272. $this->assertFalse($article->isNew());
  5273. $this->assertNotNull($article->id);
  5274. $this->assertEquals('Success', $article->title);
  5275. }
  5276. /**
  5277. * Test that findOrCreate throws a PersistenceFailedException when it cannot save
  5278. * an entity created from $search
  5279. *
  5280. * @return void
  5281. */
  5282. public function testFindOrCreateWithInvalidEntity()
  5283. {
  5284. $this->expectException(PersistenceFailedException::class);
  5285. $this->expectExceptionMessage(
  5286. 'Entity findOrCreate failure. ' .
  5287. 'Found the following errors (title._empty: "This field cannot be left empty").'
  5288. );
  5289. $articles = $this->getTableLocator()->get('Articles');
  5290. $validator = new Validator();
  5291. $validator->notBlank('title');
  5292. $articles->setValidator('default', $validator);
  5293. $articles->findOrCreate(['title' => '']);
  5294. }
  5295. /**
  5296. * Test that findOrCreate allows patching of all $search keys
  5297. *
  5298. * @return void
  5299. */
  5300. public function testFindOrCreateAccessibleFields()
  5301. {
  5302. $articles = $this->getTableLocator()->get('Articles');
  5303. $articles->setEntityClass(ProtectedEntity::class);
  5304. $validator = new Validator();
  5305. $validator->notBlank('title');
  5306. $articles->setValidator('default', $validator);
  5307. $article = $articles->findOrCreate(['title' => 'test']);
  5308. $this->assertInstanceOf(ProtectedEntity::class, $article);
  5309. $this->assertSame('test', $article->title);
  5310. }
  5311. /**
  5312. * Test that findOrCreate cannot accidentally bypass required validation.
  5313. *
  5314. * @return void
  5315. */
  5316. public function testFindOrCreatePartialValidation()
  5317. {
  5318. $articles = $this->getTableLocator()->get('Articles');
  5319. $articles->setEntityClass(ProtectedEntity::class);
  5320. $validator = new Validator();
  5321. $validator->notBlank('title')->requirePresence('title', 'create');
  5322. $validator->notBlank('body')->requirePresence('body', 'create');
  5323. $articles->setValidator('default', $validator);
  5324. $this->expectException(PersistenceFailedException::class);
  5325. $this->expectExceptionMessage(
  5326. 'Entity findOrCreate failure. ' .
  5327. 'Found the following errors (title._required: "This field is required").'
  5328. );
  5329. $articles->findOrCreate(['body' => 'test']);
  5330. }
  5331. /**
  5332. * Test that creating a table fires the initialize event.
  5333. *
  5334. * @return void
  5335. */
  5336. public function testInitializeEvent()
  5337. {
  5338. $count = 0;
  5339. $cb = function (Event $event) use (&$count) {
  5340. $count++;
  5341. };
  5342. EventManager::instance()->on('Model.initialize', $cb);
  5343. $articles = $this->getTableLocator()->get('Articles');
  5344. $this->assertEquals(1, $count, 'Callback should be called');
  5345. EventManager::instance()->off('Model.initialize', $cb);
  5346. }
  5347. /**
  5348. * Tests the hasFinder method
  5349. *
  5350. * @return void
  5351. */
  5352. public function testHasFinder()
  5353. {
  5354. $table = $this->getTableLocator()->get('articles');
  5355. $table->addBehavior('Sluggable');
  5356. $this->assertTrue($table->hasFinder('list'));
  5357. $this->assertTrue($table->hasFinder('noSlug'));
  5358. $this->assertFalse($table->hasFinder('noFind'));
  5359. }
  5360. /**
  5361. * Tests that calling validator() trigger the buildValidator event
  5362. *
  5363. * @return void
  5364. */
  5365. public function testBuildValidatorEvent()
  5366. {
  5367. $count = 0;
  5368. $cb = function (Event $event) use (&$count) {
  5369. $count++;
  5370. };
  5371. EventManager::instance()->on('Model.buildValidator', $cb);
  5372. $articles = $this->getTableLocator()->get('Articles');
  5373. $articles->getValidator();
  5374. $this->assertEquals(1, $count, 'Callback should be called');
  5375. $articles->getValidator();
  5376. $this->assertEquals(1, $count, 'Callback should be called only once');
  5377. }
  5378. /**
  5379. * Tests the validateUnique method with different combinations
  5380. *
  5381. * @return void
  5382. */
  5383. public function testValidateUnique()
  5384. {
  5385. $table = $this->getTableLocator()->get('Users');
  5386. $validator = new Validator();
  5387. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  5388. $validator->setProvider('table', $table);
  5389. $data = ['username' => ['larry', 'notthere']];
  5390. $this->assertNotEmpty($validator->validate($data));
  5391. $data = ['username' => 'larry'];
  5392. $this->assertNotEmpty($validator->validate($data));
  5393. $data = ['username' => 'jose'];
  5394. $this->assertEmpty($validator->validate($data));
  5395. $data = ['username' => 'larry', 'id' => 3];
  5396. $this->assertEmpty($validator->validate($data, false));
  5397. $data = ['username' => 'larry', 'id' => 3];
  5398. $this->assertNotEmpty($validator->validate($data));
  5399. $data = ['username' => 'larry'];
  5400. $this->assertNotEmpty($validator->validate($data, false));
  5401. $validator->add('username', 'unique', [
  5402. 'rule' => 'validateUnique', 'provider' => 'table',
  5403. ]);
  5404. $data = ['username' => 'larry'];
  5405. $this->assertNotEmpty($validator->validate($data, false));
  5406. }
  5407. /**
  5408. * Tests the validateUnique method with scope
  5409. *
  5410. * @return void
  5411. */
  5412. public function testValidateUniqueScope()
  5413. {
  5414. $table = $this->getTableLocator()->get('Users');
  5415. $validator = new Validator();
  5416. $validator->add('username', 'unique', [
  5417. 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']],
  5418. 'provider' => 'table',
  5419. ]);
  5420. $validator->setProvider('table', $table);
  5421. $data = ['username' => 'larry', 'id' => 3];
  5422. $this->assertNotEmpty($validator->validate($data));
  5423. $data = ['username' => 'larry', 'id' => 1];
  5424. $this->assertEmpty($validator->validate($data));
  5425. $data = ['username' => 'jose'];
  5426. $this->assertEmpty($validator->validate($data));
  5427. }
  5428. /**
  5429. * Tests the validateUnique method with options
  5430. *
  5431. * @return void
  5432. */
  5433. public function testValidateUniqueMultipleNulls()
  5434. {
  5435. $entity = new Entity([
  5436. 'id' => 9,
  5437. 'site_id' => 1,
  5438. 'author_id' => null,
  5439. 'title' => 'Null title',
  5440. ]);
  5441. $table = $this->getTableLocator()->get('SiteArticles');
  5442. $table->save($entity);
  5443. $validator = new Validator();
  5444. $validator->add('site_id', 'unique', [
  5445. 'rule' => [
  5446. 'validateUnique',
  5447. [
  5448. 'allowMultipleNulls' => false,
  5449. 'scope' => ['author_id'],
  5450. ],
  5451. ],
  5452. 'provider' => 'table',
  5453. 'message' => 'Must be unique.',
  5454. ]);
  5455. $validator->setProvider('table', $table);
  5456. $data = ['site_id' => 1, 'author_id' => null, 'title' => 'Null dupe'];
  5457. $expected = ['site_id' => ['unique' => 'Must be unique.']];
  5458. $this->assertEquals($expected, $validator->validate($data));
  5459. }
  5460. /**
  5461. * Tests that the callbacks receive the expected types of arguments.
  5462. *
  5463. * @return void
  5464. */
  5465. public function testCallbackArgumentTypes()
  5466. {
  5467. $table = $this->getTableLocator()->get('articles');
  5468. $table->belongsTo('authors');
  5469. $eventManager = $table->getEventManager();
  5470. $associationBeforeFindCount = 0;
  5471. $table->getAssociation('authors')->getTarget()->getEventManager()->on(
  5472. 'Model.beforeFind',
  5473. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
  5474. $this->assertInternalType('bool', $primary);
  5475. $associationBeforeFindCount++;
  5476. }
  5477. );
  5478. $beforeFindCount = 0;
  5479. $eventManager->on(
  5480. 'Model.beforeFind',
  5481. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
  5482. $this->assertInternalType('bool', $primary);
  5483. $beforeFindCount++;
  5484. }
  5485. );
  5486. $table->find()->contain('authors')->first();
  5487. $this->assertEquals(1, $associationBeforeFindCount);
  5488. $this->assertEquals(1, $beforeFindCount);
  5489. $buildValidatorCount = 0;
  5490. $eventManager->on(
  5491. 'Model.buildValidator',
  5492. $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) {
  5493. $this->assertInternalType('string', $name);
  5494. $buildValidatorCount++;
  5495. }
  5496. );
  5497. $table->getValidator();
  5498. $this->assertEquals(1, $buildValidatorCount);
  5499. $buildRulesCount =
  5500. $beforeRulesCount =
  5501. $afterRulesCount =
  5502. $beforeSaveCount =
  5503. $afterSaveCount = 0;
  5504. $eventManager->on(
  5505. 'Model.buildRules',
  5506. function (Event $event, RulesChecker $rules) use (&$buildRulesCount) {
  5507. $buildRulesCount++;
  5508. }
  5509. );
  5510. $eventManager->on(
  5511. 'Model.beforeRules',
  5512. function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
  5513. $this->assertInternalType('string', $operation);
  5514. $beforeRulesCount++;
  5515. }
  5516. );
  5517. $eventManager->on(
  5518. 'Model.afterRules',
  5519. function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
  5520. $this->assertInternalType('bool', $result);
  5521. $this->assertInternalType('string', $operation);
  5522. $afterRulesCount++;
  5523. }
  5524. );
  5525. $eventManager->on(
  5526. 'Model.beforeSave',
  5527. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) {
  5528. $beforeSaveCount++;
  5529. }
  5530. );
  5531. $eventManager->on(
  5532. 'Model.afterSave',
  5533. $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) {
  5534. $afterSaveCount++;
  5535. }
  5536. );
  5537. $entity = new Entity(['title' => 'Title']);
  5538. $this->assertNotFalse($table->save($entity));
  5539. $this->assertEquals(1, $buildRulesCount);
  5540. $this->assertEquals(1, $beforeRulesCount);
  5541. $this->assertEquals(1, $afterRulesCount);
  5542. $this->assertEquals(1, $beforeSaveCount);
  5543. $this->assertEquals(1, $afterSaveCount);
  5544. $beforeDeleteCount =
  5545. $afterDeleteCount = 0;
  5546. $eventManager->on(
  5547. 'Model.beforeDelete',
  5548. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) {
  5549. $beforeDeleteCount++;
  5550. }
  5551. );
  5552. $eventManager->on(
  5553. 'Model.afterDelete',
  5554. function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) {
  5555. $afterDeleteCount++;
  5556. }
  5557. );
  5558. $this->assertTrue($table->delete($entity, ['checkRules' => false]));
  5559. $this->assertEquals(1, $beforeDeleteCount);
  5560. $this->assertEquals(1, $afterDeleteCount);
  5561. }
  5562. /**
  5563. * Tests that calling newEntity() on a table sets the right source alias
  5564. *
  5565. * @group deprecated
  5566. * @return void
  5567. */
  5568. public function testEntitySource()
  5569. {
  5570. $this->deprecated(function () {
  5571. $table = $this->getTableLocator()->get('Articles');
  5572. $this->assertEquals('Articles', $table->newEntity()->source());
  5573. $this->loadPlugins(['TestPlugin']);
  5574. $table = $this->getTableLocator()->get('TestPlugin.Comments');
  5575. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source());
  5576. });
  5577. }
  5578. /**
  5579. * Tests that calling newEntity() on a table sets the right source alias
  5580. *
  5581. * @return void
  5582. */
  5583. public function testSetEntitySource()
  5584. {
  5585. $table = $this->getTableLocator()->get('Articles');
  5586. $this->assertEquals('Articles', $table->newEntity()->getSource());
  5587. $this->loadPlugins(['TestPlugin']);
  5588. $table = $this->getTableLocator()->get('TestPlugin.Comments');
  5589. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->getSource());
  5590. }
  5591. /**
  5592. * Tests that passing a coned entity that was marked as new to save() will
  5593. * actually save it as a new entity
  5594. *
  5595. * @group save
  5596. * @return void
  5597. */
  5598. public function testSaveWithClonedEntity()
  5599. {
  5600. $table = $this->getTableLocator()->get('Articles');
  5601. $article = $table->get(1);
  5602. $cloned = clone $article;
  5603. $cloned->unsetProperty('id');
  5604. $cloned->setNew(true);
  5605. $this->assertSame($cloned, $table->save($cloned));
  5606. $this->assertEquals(
  5607. $article->extract(['title', 'author_id']),
  5608. $cloned->extract(['title', 'author_id'])
  5609. );
  5610. $this->assertEquals(4, $cloned->id);
  5611. }
  5612. /**
  5613. * Tests that the _ids notation can be used for HasMany
  5614. *
  5615. * @return void
  5616. */
  5617. public function testSaveHasManyWithIds()
  5618. {
  5619. $data = [
  5620. 'username' => 'lux',
  5621. 'password' => 'passphrase',
  5622. 'comments' => [
  5623. '_ids' => [1, 2],
  5624. ],
  5625. ];
  5626. $userTable = $this->getTableLocator()->get('Users');
  5627. $userTable->hasMany('Comments');
  5628. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  5629. $retrievedUser = $userTable->find('all')->where(['id' => $savedUser->id])->contain(['Comments'])->first();
  5630. $this->assertEquals($savedUser->comments[0]->user_id, $retrievedUser->comments[0]->user_id);
  5631. $this->assertEquals($savedUser->comments[1]->user_id, $retrievedUser->comments[1]->user_id);
  5632. }
  5633. /**
  5634. * Tests that on second save, entities for the has many relation are not marked
  5635. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  5636. * for a cleaner transaction log
  5637. *
  5638. * @return void
  5639. */
  5640. public function testSaveHasManyNoWasteSave()
  5641. {
  5642. $data = [
  5643. 'username' => 'lux',
  5644. 'password' => 'passphrase',
  5645. 'comments' => [
  5646. '_ids' => [1, 2],
  5647. ],
  5648. ];
  5649. $userTable = $this->getTableLocator()->get('Users');
  5650. $userTable->hasMany('Comments');
  5651. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  5652. $counter = 0;
  5653. $userTable->Comments
  5654. ->getEventManager()
  5655. ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) {
  5656. if ($entity->isDirty()) {
  5657. $counter++;
  5658. }
  5659. });
  5660. $savedUser->comments[] = $userTable->Comments->get(5);
  5661. $this->assertCount(3, $savedUser->comments);
  5662. $savedUser->setDirty('comments', true);
  5663. $userTable->save($savedUser);
  5664. $this->assertEquals(1, $counter);
  5665. }
  5666. /**
  5667. * Tests that on second save, entities for the belongsToMany relation are not marked
  5668. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  5669. * for a cleaner transaction log
  5670. *
  5671. * @return void
  5672. */
  5673. public function testSaveBelongsToManyNoWasteSave()
  5674. {
  5675. $data = [
  5676. 'title' => 'foo',
  5677. 'body' => 'bar',
  5678. 'tags' => [
  5679. '_ids' => [1, 2],
  5680. ],
  5681. ];
  5682. $table = $this->getTableLocator()->get('Articles');
  5683. $table->belongsToMany('Tags');
  5684. $article = $table->save($table->newEntity($data, ['associated' => ['Tags']]));
  5685. $counter = 0;
  5686. $table->Tags->junction()
  5687. ->getEventManager()
  5688. ->on('Model.afterSave', function (Event $event, $entity) use (&$counter) {
  5689. if ($entity->isDirty()) {
  5690. $counter++;
  5691. }
  5692. });
  5693. $article->tags[] = $table->Tags->get(3);
  5694. $this->assertCount(3, $article->tags);
  5695. $article->setDirty('tags', true);
  5696. $table->save($article);
  5697. $this->assertEquals(1, $counter);
  5698. }
  5699. /**
  5700. * Tests that after saving then entity contains the right primary
  5701. * key casted to the right type
  5702. *
  5703. * @group save
  5704. * @return void
  5705. */
  5706. public function testSaveCorrectPrimaryKeyType()
  5707. {
  5708. $entity = new Entity([
  5709. 'username' => 'superuser',
  5710. 'created' => new Time('2013-10-10 00:00'),
  5711. 'updated' => new Time('2013-10-10 00:00'),
  5712. ], ['markNew' => true]);
  5713. $table = $this->getTableLocator()->get('Users');
  5714. $this->assertSame($entity, $table->save($entity));
  5715. $this->assertSame(self::$nextUserId, $entity->id);
  5716. }
  5717. /**
  5718. * Tests entity clean()
  5719. *
  5720. * @return void
  5721. */
  5722. public function testEntityClean()
  5723. {
  5724. $table = $this->getTableLocator()->get('Articles');
  5725. $validator = $table->getValidator()->requirePresence('body');
  5726. $entity = $table->newEntity(['title' => 'mark']);
  5727. $entity->setDirty('title', true);
  5728. $entity->setInvalidField('title', 'albert');
  5729. $this->assertNotEmpty($entity->getErrors());
  5730. $this->assertTrue($entity->isDirty());
  5731. $this->assertEquals(['title' => 'albert'], $entity->getInvalid());
  5732. $entity->title = 'alex';
  5733. $this->assertSame($entity->getOriginal('title'), 'mark');
  5734. $entity->clean();
  5735. $this->assertEmpty($entity->getErrors());
  5736. $this->assertFalse($entity->isDirty());
  5737. $this->assertEquals([], $entity->getInvalid());
  5738. $this->assertSame($entity->getOriginal('title'), 'alex');
  5739. }
  5740. /**
  5741. * Tests the loadInto() method
  5742. *
  5743. * @return void
  5744. */
  5745. public function testLoadIntoEntity()
  5746. {
  5747. $table = $this->getTableLocator()->get('Authors');
  5748. $table->hasMany('SiteArticles');
  5749. $articles = $table->hasMany('Articles');
  5750. $articles->belongsToMany('Tags');
  5751. $entity = $table->get(1);
  5752. $result = $table->loadInto($entity, ['SiteArticles', 'Articles.Tags']);
  5753. $this->assertSame($entity, $result);
  5754. $expected = $table->get(1, ['contain' => ['SiteArticles', 'Articles.Tags']]);
  5755. $this->assertEquals($expected, $result);
  5756. }
  5757. /**
  5758. * Tests that it is possible to pass conditions and fields to loadInto()
  5759. *
  5760. * @return void
  5761. */
  5762. public function testLoadIntoWithConditions()
  5763. {
  5764. $table = $this->getTableLocator()->get('Authors');
  5765. $table->hasMany('SiteArticles');
  5766. $articles = $table->hasMany('Articles');
  5767. $articles->belongsToMany('Tags');
  5768. $entity = $table->get(1);
  5769. $options = [
  5770. 'SiteArticles' => ['fields' => ['title', 'author_id']],
  5771. 'Articles.Tags' => function ($q) {
  5772. return $q->where(['Tags.name' => 'tag2']);
  5773. },
  5774. ];
  5775. $result = $table->loadInto($entity, $options);
  5776. $this->assertSame($entity, $result);
  5777. $expected = $table->get(1, ['contain' => $options]);
  5778. $this->assertEquals($expected, $result);
  5779. }
  5780. /**
  5781. * Tests loadInto() with a belongsTo association
  5782. *
  5783. * @return void
  5784. */
  5785. public function testLoadBelongsTo()
  5786. {
  5787. $table = $this->getTableLocator()->get('Articles');
  5788. $table->belongsTo('Authors');
  5789. $entity = $table->get(2);
  5790. $result = $table->loadInto($entity, ['Authors']);
  5791. $this->assertSame($entity, $result);
  5792. $expected = $table->get(2, ['contain' => ['Authors']]);
  5793. $this->assertEquals($expected, $entity);
  5794. }
  5795. /**
  5796. * Tests that it is possible to post-load associations for many entities at
  5797. * the same time
  5798. *
  5799. * @return void
  5800. */
  5801. public function testLoadIntoMany()
  5802. {
  5803. $table = $this->getTableLocator()->get('Authors');
  5804. $table->hasMany('SiteArticles');
  5805. $articles = $table->hasMany('Articles');
  5806. $articles->belongsToMany('Tags');
  5807. $entities = $table->find()->compile();
  5808. $contain = ['SiteArticles', 'Articles.Tags'];
  5809. $result = $table->loadInto($entities, $contain);
  5810. foreach ($entities as $k => $v) {
  5811. $this->assertSame($v, $result[$k]);
  5812. }
  5813. $expected = $table->find()->contain($contain)->toList();
  5814. $this->assertEquals($expected, $result);
  5815. }
  5816. /**
  5817. * Tests that saveOrFail triggers an exception on not successful save
  5818. *
  5819. * @return void
  5820. */
  5821. public function testSaveOrFail()
  5822. {
  5823. $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
  5824. $this->expectExceptionMessage('Entity save failure.');
  5825. $entity = new Entity([
  5826. 'foo' => 'bar',
  5827. ]);
  5828. $table = $this->getTableLocator()->get('users');
  5829. $table->saveOrFail($entity);
  5830. }
  5831. /**
  5832. * Tests that saveOrFail displays useful messages on output, especially in tests for CLI.
  5833. *
  5834. * @return void
  5835. */
  5836. public function testSaveOrFailErrorDisplay()
  5837. {
  5838. $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
  5839. $this->expectExceptionMessage('Entity save failure. Found the following errors (field.0: "Some message", multiple.one: "One", multiple.two: "Two")');
  5840. $entity = new Entity([
  5841. 'foo' => 'bar',
  5842. ]);
  5843. $entity->setError('field', 'Some message');
  5844. $entity->setError('multiple', ['one' => 'One', 'two' => 'Two']);
  5845. $table = $this->getTableLocator()->get('users');
  5846. $table->saveOrFail($entity);
  5847. }
  5848. /**
  5849. * Tests that saveOrFail with nested errors
  5850. *
  5851. * @return void
  5852. */
  5853. public function testSaveOrFailNestedError()
  5854. {
  5855. $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
  5856. $this->expectExceptionMessage('Entity save failure. Found the following errors (articles.0.title.0: "Bad value")');
  5857. $entity = new Entity([
  5858. 'username' => 'bad',
  5859. 'articles' => [
  5860. new Entity(['title' => 'not an entity']),
  5861. ],
  5862. ]);
  5863. $entity->articles[0]->setError('title', 'Bad value');
  5864. $table = $this->getTableLocator()->get('Users');
  5865. $table->hasMany('Articles');
  5866. $table->saveOrFail($entity);
  5867. }
  5868. /**
  5869. * Tests that saveOrFail returns the right entity
  5870. *
  5871. * @return void
  5872. */
  5873. public function testSaveOrFailGetEntity()
  5874. {
  5875. $entity = new Entity([
  5876. 'foo' => 'bar',
  5877. ]);
  5878. $table = $this->getTableLocator()->get('users');
  5879. try {
  5880. $table->saveOrFail($entity);
  5881. } catch (\Cake\ORM\Exception\PersistenceFailedException $e) {
  5882. $this->assertSame($entity, $e->getEntity());
  5883. }
  5884. }
  5885. /**
  5886. * Tests that deleteOrFail triggers an exception on not successful delete
  5887. *
  5888. * @return void
  5889. */
  5890. public function testDeleteOrFail()
  5891. {
  5892. $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
  5893. $this->expectExceptionMessage('Entity delete failure.');
  5894. $entity = new Entity([
  5895. 'id' => 999,
  5896. ]);
  5897. $table = $this->getTableLocator()->get('users');
  5898. $result = $table->deleteOrFail($entity);
  5899. }
  5900. /**
  5901. * Tests that deleteOrFail returns the right entity
  5902. *
  5903. * @return void
  5904. */
  5905. public function testDeleteOrFailGetEntity()
  5906. {
  5907. $entity = new Entity([
  5908. 'id' => 999,
  5909. ]);
  5910. $table = $this->getTableLocator()->get('users');
  5911. try {
  5912. $table->deleteOrFail($entity);
  5913. } catch (\Cake\ORM\Exception\PersistenceFailedException $e) {
  5914. $this->assertSame($entity, $e->getEntity());
  5915. }
  5916. }
  5917. /**
  5918. * Test simple delete.
  5919. *
  5920. * @return void
  5921. */
  5922. public function testDeleteMany()
  5923. {
  5924. $table = $this->getTableLocator()->get('users');
  5925. $entities = $table->find()->limit(2)->all()->toArray();
  5926. $this->assertCount(2, $entities);
  5927. $result = $table->deleteMany($entities);
  5928. $this->assertSame($entities, $result);
  5929. $count = $table->find()->where(['id IN' => Hash::extract($entities, '{n}.id')])->count();
  5930. $this->assertSame(0, $count, 'Find should not return > 0.');
  5931. }
  5932. /**
  5933. * Test simple delete.
  5934. *
  5935. * @return void
  5936. */
  5937. public function testDeleteManyOrFail()
  5938. {
  5939. $table = $this->getTableLocator()->get('users');
  5940. $entities = $table->find()->limit(2)->all()->toArray();
  5941. $this->assertCount(2, $entities);
  5942. $result = $table->deleteManyOrFail($entities);
  5943. $this->assertSame($entities, $result);
  5944. $count = $table->find()->where(['id IN' => Hash::extract($entities, '{n}.id')])->count();
  5945. $this->assertSame(0, $count, 'Find should not return > 0.');
  5946. }
  5947. /**
  5948. * Test getting the save options builder.
  5949. *
  5950. * @return void
  5951. */
  5952. public function getSaveOptionsBuilder()
  5953. {
  5954. $table = $this->getTableLocator()->get('Authors');
  5955. $result = $table->getSaveOptionsBuilder();
  5956. $this->assertInstanceOf('Cake\ORM\SaveOptionsBuilder', $result);
  5957. }
  5958. /**
  5959. * Helper method to skip tests when connection is SQLServer.
  5960. *
  5961. * @return void
  5962. */
  5963. public function skipIfSqlServer()
  5964. {
  5965. $this->skipIf(
  5966. $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver,
  5967. 'SQLServer does not support the requirements of this test.'
  5968. );
  5969. }
  5970. }