TableTest.php 208 KB

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