TableTest.php 212 KB

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