TableTest.php 185 KB

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