TableTest.php 215 KB

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