TableTest.php 216 KB

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