TableTest.php 211 KB

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