TableTest.php 222 KB

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