TableTest.php 217 KB

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