TableTest.php 222 KB

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