TableTest.php 224 KB

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