TableTest.php 223 KB

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