TableTest.php 182 KB

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