TableTest.php 188 KB

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