TableTest.php 217 KB

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