TableTest.php 212 KB

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