TableTest.php 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506
  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\Core\Configure;
  18. use Cake\Core\Plugin;
  19. use Cake\Database\Exception;
  20. use Cake\Database\Expression\QueryExpression;
  21. use Cake\Database\TypeMap;
  22. use Cake\Datasource\ConnectionManager;
  23. use Cake\Event\Event;
  24. use Cake\Event\EventManager;
  25. use Cake\I18n\Time;
  26. use Cake\ORM\Entity;
  27. use Cake\ORM\Query;
  28. use Cake\ORM\RulesChecker;
  29. use Cake\ORM\Table;
  30. use Cake\ORM\TableRegistry;
  31. use Cake\TestSuite\TestCase;
  32. use Cake\Validation\Validator;
  33. /**
  34. * Used to test correct class is instantiated when using TableRegistry::get();
  35. */
  36. class UsersTable extends Table
  37. {
  38. }
  39. /**
  40. * Tests Table class
  41. *
  42. */
  43. class TableTest extends TestCase
  44. {
  45. public $fixtures = [
  46. 'core.comments',
  47. 'core.users',
  48. 'core.categories',
  49. 'core.articles',
  50. 'core.authors',
  51. 'core.tags',
  52. 'core.articles_tags',
  53. 'core.site_articles',
  54. 'core.members',
  55. 'core.groups',
  56. 'core.groups_members',
  57. 'core.polymorphic_tagged',
  58. ];
  59. /**
  60. * Handy variable containing the next primary key that will be inserted in the
  61. * users table
  62. *
  63. * @var int
  64. */
  65. public static $nextUserId = 5;
  66. public function setUp()
  67. {
  68. parent::setUp();
  69. $this->connection = ConnectionManager::get('test');
  70. Configure::write('App.namespace', 'TestApp');
  71. $this->usersTypeMap = new TypeMap([
  72. 'Users.id' => 'integer',
  73. 'id' => 'integer',
  74. 'Users.username' => 'string',
  75. 'username' => 'string',
  76. 'Users.password' => 'string',
  77. 'password' => 'string',
  78. 'Users.created' => 'timestamp',
  79. 'created' => 'timestamp',
  80. 'Users.updated' => 'timestamp',
  81. 'updated' => 'timestamp',
  82. ]);
  83. $this->articlesTypeMap = new TypeMap([
  84. 'Articles.id' => 'integer',
  85. 'id' => 'integer',
  86. 'Articles.title' => 'string',
  87. 'title' => 'string',
  88. 'Articles.author_id' => 'integer',
  89. 'author_id' => 'integer',
  90. 'Articles.body' => 'text',
  91. 'body' => 'text',
  92. 'Articles.published' => 'string',
  93. 'published' => 'string',
  94. ]);
  95. }
  96. /**
  97. * teardown method
  98. *
  99. * @return void
  100. */
  101. public function tearDown()
  102. {
  103. parent::tearDown();
  104. TableRegistry::clear();
  105. }
  106. /**
  107. * Tests the table method
  108. *
  109. * @return void
  110. */
  111. public function testTableMethod()
  112. {
  113. $table = new Table(['table' => 'users']);
  114. $this->assertEquals('users', $table->table());
  115. $table = new UsersTable;
  116. $this->assertEquals('users', $table->table());
  117. $table = $this->getMockBuilder('\Cake\ORM\Table')
  118. ->setMethods(['find'])
  119. ->setMockClassName('SpecialThingsTable')
  120. ->getMock();
  121. $this->assertEquals('special_things', $table->table());
  122. $table = new Table(['alias' => 'LoveBoats']);
  123. $this->assertEquals('love_boats', $table->table());
  124. $table->table('other');
  125. $this->assertEquals('other', $table->table());
  126. $table->table('database.other');
  127. $this->assertEquals('database.other', $table->table());
  128. }
  129. /**
  130. * Tests the alias method
  131. *
  132. * @return void
  133. */
  134. public function testAliasMethod()
  135. {
  136. $table = new Table(['alias' => 'users']);
  137. $this->assertEquals('users', $table->alias());
  138. $table = new Table(['table' => 'stuffs']);
  139. $this->assertEquals('stuffs', $table->alias());
  140. $table = new UsersTable;
  141. $this->assertEquals('Users', $table->alias());
  142. $table = $this->getMockBuilder('\Cake\ORM\Table')
  143. ->setMethods(['find'])
  144. ->setMockClassName('SpecialThingTable')
  145. ->getMock();
  146. $this->assertEquals('SpecialThing', $table->alias());
  147. $table->alias('AnotherOne');
  148. $this->assertEquals('AnotherOne', $table->alias());
  149. }
  150. /**
  151. * Test that aliasField() works.
  152. *
  153. * @return void
  154. */
  155. public function testAliasField()
  156. {
  157. $table = new Table(['alias' => 'Users']);
  158. $this->assertEquals('Users.id', $table->aliasField('id'));
  159. }
  160. /**
  161. * Tests connection method
  162. *
  163. * @return void
  164. */
  165. public function testConnection()
  166. {
  167. $table = new Table(['table' => 'users']);
  168. $this->assertNull($table->connection());
  169. $table->connection($this->connection);
  170. $this->assertSame($this->connection, $table->connection());
  171. }
  172. /**
  173. * Tests primaryKey method
  174. *
  175. * @return void
  176. */
  177. public function testPrimaryKey()
  178. {
  179. $table = new Table([
  180. 'table' => 'users',
  181. 'schema' => [
  182. 'id' => ['type' => 'integer'],
  183. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  184. ]
  185. ]);
  186. $this->assertEquals('id', $table->primaryKey());
  187. $table->primaryKey('thingID');
  188. $this->assertEquals('thingID', $table->primaryKey());
  189. $table->primaryKey(['thingID', 'user_id']);
  190. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  191. }
  192. /**
  193. * Tests that name will be selected as a displayField
  194. *
  195. * @return void
  196. */
  197. public function testDisplayFieldName()
  198. {
  199. $table = new Table([
  200. 'table' => 'users',
  201. 'schema' => [
  202. 'foo' => ['type' => 'string'],
  203. 'name' => ['type' => 'string']
  204. ]
  205. ]);
  206. $this->assertEquals('name', $table->displayField());
  207. }
  208. /**
  209. * Tests that title will be selected as a displayField
  210. *
  211. * @return void
  212. */
  213. public function testDisplayFieldTitle()
  214. {
  215. $table = new Table([
  216. 'table' => 'users',
  217. 'schema' => [
  218. 'foo' => ['type' => 'string'],
  219. 'title' => ['type' => 'string']
  220. ]
  221. ]);
  222. $this->assertEquals('title', $table->displayField());
  223. }
  224. /**
  225. * Tests that no displayField will fallback to primary key
  226. *
  227. * @return void
  228. */
  229. public function testDisplayFallback()
  230. {
  231. $table = new Table([
  232. 'table' => 'users',
  233. 'schema' => [
  234. 'id' => ['type' => 'string'],
  235. 'foo' => ['type' => 'string'],
  236. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  237. ]
  238. ]);
  239. $this->assertEquals('id', $table->displayField());
  240. }
  241. /**
  242. * Tests that displayField can be changed
  243. *
  244. * @return void
  245. */
  246. public function testDisplaySet()
  247. {
  248. $table = new Table([
  249. 'table' => 'users',
  250. 'schema' => [
  251. 'id' => ['type' => 'string'],
  252. 'foo' => ['type' => 'string'],
  253. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  254. ]
  255. ]);
  256. $this->assertEquals('id', $table->displayField());
  257. $table->displayField('foo');
  258. $this->assertEquals('foo', $table->displayField());
  259. }
  260. /**
  261. * Tests schema method
  262. *
  263. * @return void
  264. */
  265. public function testSchema()
  266. {
  267. $schema = $this->connection->schemaCollection()->describe('users');
  268. $table = new Table([
  269. 'table' => 'users',
  270. 'connection' => $this->connection,
  271. ]);
  272. $this->assertEquals($schema, $table->schema());
  273. $table = new Table(['table' => 'stuff']);
  274. $table->schema($schema);
  275. $this->assertSame($schema, $table->schema());
  276. $table = new Table(['table' => 'another']);
  277. $schema = ['id' => ['type' => 'integer']];
  278. $table->schema($schema);
  279. $this->assertEquals(
  280. new \Cake\Database\Schema\Table('another', $schema),
  281. $table->schema()
  282. );
  283. }
  284. /**
  285. * Tests that _initializeSchema can be used to alter the database schema
  286. *
  287. * @return void
  288. */
  289. public function testSchemaInitialize()
  290. {
  291. $schema = $this->connection->schemaCollection()->describe('users');
  292. $table = $this->getMock('Cake\ORM\Table', ['_initializeSchema'], [
  293. ['table' => 'users', 'connection' => $this->connection]
  294. ]);
  295. $table->expects($this->once())
  296. ->method('_initializeSchema')
  297. ->with($schema)
  298. ->will($this->returnCallback(function ($schema) {
  299. $schema->columnType('username', 'integer');
  300. return $schema;
  301. }));
  302. $result = $table->schema();
  303. $schema->columnType('username', 'integer');
  304. $this->assertEquals($schema, $result);
  305. $this->assertEquals($schema, $table->schema(), '_initializeSchema should be called once');
  306. }
  307. /**
  308. * Tests that all fields for a table are added by default in a find when no
  309. * other fields are specified
  310. *
  311. * @return void
  312. */
  313. public function testFindAllNoFieldsAndNoHydration()
  314. {
  315. $table = new Table([
  316. 'table' => 'users',
  317. 'connection' => $this->connection,
  318. ]);
  319. $results = $table
  320. ->find('all')
  321. ->where(['id IN' => [1, 2]])
  322. ->order('id')
  323. ->hydrate(false)
  324. ->toArray();
  325. $expected = [
  326. [
  327. 'id' => 1,
  328. 'username' => 'mariano',
  329. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  330. 'created' => new Time('2007-03-17 01:16:23'),
  331. 'updated' => new Time('2007-03-17 01:18:31'),
  332. ],
  333. [
  334. 'id' => 2,
  335. 'username' => 'nate',
  336. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  337. 'created' => new Time('2008-03-17 01:18:23'),
  338. 'updated' => new Time('2008-03-17 01:20:31'),
  339. ],
  340. ];
  341. $this->assertEquals($expected, $results);
  342. }
  343. /**
  344. * Tests that it is possible to select only a few fields when finding over a table
  345. *
  346. * @return void
  347. */
  348. public function testFindAllSomeFieldsNoHydration()
  349. {
  350. $table = new Table([
  351. 'table' => 'users',
  352. 'connection' => $this->connection,
  353. ]);
  354. $results = $table->find('all')
  355. ->select(['username', 'password'])
  356. ->hydrate(false)
  357. ->order('username')->toArray();
  358. $expected = [
  359. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  360. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  361. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  362. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  363. ];
  364. $this->assertSame($expected, $results);
  365. $results = $table->find('all')
  366. ->select(['foo' => 'username', 'password'])
  367. ->order('username')
  368. ->hydrate(false)
  369. ->toArray();
  370. $expected = [
  371. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  372. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  373. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  374. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  375. ];
  376. $this->assertSame($expected, $results);
  377. }
  378. /**
  379. * Tests that the query will automatically casts complex conditions to the correct
  380. * types when the columns belong to the default table
  381. *
  382. * @return void
  383. */
  384. public function testFindAllConditionAutoTypes()
  385. {
  386. $table = new Table([
  387. 'table' => 'users',
  388. 'connection' => $this->connection,
  389. ]);
  390. $query = $table->find('all')
  391. ->select(['id', 'username'])
  392. ->where(['created >=' => new Time('2010-01-22 00:00')])
  393. ->hydrate(false)
  394. ->order('id');
  395. $expected = [
  396. ['id' => 3, 'username' => 'larry'],
  397. ['id' => 4, 'username' => 'garrett']
  398. ];
  399. $this->assertSame($expected, $query->toArray());
  400. $query->orWhere(['users.created' => new Time('2008-03-17 01:18:23')]);
  401. $expected = [
  402. ['id' => 2, 'username' => 'nate'],
  403. ['id' => 3, 'username' => 'larry'],
  404. ['id' => 4, 'username' => 'garrett']
  405. ];
  406. $this->assertSame($expected, $query->toArray());
  407. }
  408. /**
  409. * Test that beforeFind events can mutate the query.
  410. *
  411. * @return void
  412. */
  413. public function testFindBeforeFindEventMutateQuery()
  414. {
  415. $table = new Table([
  416. 'table' => 'users',
  417. 'connection' => $this->connection,
  418. ]);
  419. $table->eventManager()->on(
  420. 'Model.beforeFind',
  421. function ($event, $query, $options) {
  422. $query->limit(1);
  423. }
  424. );
  425. $result = $table->find('all')->all();
  426. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  427. }
  428. /**
  429. * Test that beforeFind events are fired and can stop the find and
  430. * return custom results.
  431. *
  432. * @return void
  433. */
  434. public function testFindBeforeFindEventOverrideReturn()
  435. {
  436. $table = new Table([
  437. 'table' => 'users',
  438. 'connection' => $this->connection,
  439. ]);
  440. $expected = ['One', 'Two', 'Three'];
  441. $table->eventManager()->on(
  442. 'Model.beforeFind',
  443. function ($event, $query, $options) use ($expected) {
  444. $query->setResult($expected);
  445. $event->stopPropagation();
  446. }
  447. );
  448. $query = $table->find('all');
  449. $query->limit(1);
  450. $this->assertEquals($expected, $query->all()->toArray());
  451. }
  452. /**
  453. * Tests that belongsTo() creates and configures correctly the association
  454. *
  455. * @return void
  456. */
  457. public function testBelongsTo()
  458. {
  459. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  460. $table = new Table(['table' => 'dates']);
  461. $belongsTo = $table->belongsTo('user', $options);
  462. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  463. $this->assertSame($belongsTo, $table->association('user'));
  464. $this->assertEquals('user', $belongsTo->name());
  465. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  466. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  467. $this->assertSame($table, $belongsTo->source());
  468. }
  469. /**
  470. * Tests that hasOne() creates and configures correctly the association
  471. *
  472. * @return void
  473. */
  474. public function testHasOne()
  475. {
  476. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  477. $table = new Table(['table' => 'users']);
  478. $hasOne = $table->hasOne('profile', $options);
  479. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  480. $this->assertSame($hasOne, $table->association('profile'));
  481. $this->assertEquals('profile', $hasOne->name());
  482. $this->assertEquals('user_id', $hasOne->foreignKey());
  483. $this->assertEquals(['b' => 'c'], $hasOne->conditions());
  484. $this->assertSame($table, $hasOne->source());
  485. }
  486. /**
  487. * Test has one with a plugin model
  488. *
  489. * @return void
  490. */
  491. public function testHasOnePlugin()
  492. {
  493. $options = ['className' => 'TestPlugin.Comments'];
  494. $table = new Table(['table' => 'users']);
  495. $hasOne = $table->hasOne('Comments', $options);
  496. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  497. $this->assertSame('Comments', $hasOne->name());
  498. $hasOneTable = $hasOne->target();
  499. $this->assertSame('Comments', $hasOne->alias());
  500. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  501. $options = ['className' => 'TestPlugin.Comments'];
  502. $table = new Table(['table' => 'users']);
  503. $hasOne = $table->hasOne('TestPlugin.Comments', $options);
  504. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  505. $this->assertSame('Comments', $hasOne->name());
  506. $hasOneTable = $hasOne->target();
  507. $this->assertSame('Comments', $hasOne->alias());
  508. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  509. }
  510. /**
  511. * testNoneUniqueAssociationsSameClass
  512. *
  513. * @return void
  514. */
  515. public function testNoneUniqueAssociationsSameClass()
  516. {
  517. $Users = new Table(['table' => 'users']);
  518. $options = ['className' => 'Comments'];
  519. $Users->hasMany('Comments', $options);
  520. $Articles = new Table(['table' => 'articles']);
  521. $options = ['className' => 'Comments'];
  522. $Articles->hasMany('Comments', $options);
  523. $Categories = new Table(['table' => 'categories']);
  524. $options = ['className' => 'TestPlugin.Comments'];
  525. $Categories->hasMany('Comments', $options);
  526. $this->assertInstanceOf('Cake\ORM\Table', $Users->Comments->target());
  527. $this->assertInstanceOf('Cake\ORM\Table', $Articles->Comments->target());
  528. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $Categories->Comments->target());
  529. }
  530. /**
  531. * Test associations which refer to the same table multiple times
  532. *
  533. * @return void
  534. */
  535. public function testSelfJoinAssociations()
  536. {
  537. $Categories = TableRegistry::get('Categories');
  538. $options = ['className' => 'Categories'];
  539. $Categories->hasMany('Children', ['foreignKey' => 'parent_id'] + $options);
  540. $Categories->belongsTo('Parent', $options);
  541. $this->assertSame('categories', $Categories->Children->target()->table());
  542. $this->assertSame('categories', $Categories->Parent->target()->table());
  543. $this->assertSame('Children', $Categories->Children->alias());
  544. $this->assertSame('Children', $Categories->Children->target()->alias());
  545. $this->assertSame('Parent', $Categories->Parent->alias());
  546. $this->assertSame('Parent', $Categories->Parent->target()->alias());
  547. $expected = [
  548. 'id' => 2,
  549. 'parent_id' => 1,
  550. 'name' => 'Category 1.1',
  551. 'parent' => [
  552. 'id' => 1,
  553. 'parent_id' => 0,
  554. 'name' => 'Category 1',
  555. ],
  556. 'children' => [
  557. [
  558. 'id' => 7,
  559. 'parent_id' => 2,
  560. 'name' => 'Category 1.1.1',
  561. ],
  562. [
  563. 'id' => 8,
  564. 'parent_id' => 2,
  565. 'name' => 'Category 1.1.2',
  566. ]
  567. ]
  568. ];
  569. $fields = ['id', 'parent_id', 'name'];
  570. $result = $Categories->find('all')
  571. ->select(['Categories.id', 'Categories.parent_id', 'Categories.name'])
  572. ->contain(['Children' => ['fields' => $fields], 'Parent' => ['fields' => $fields]])
  573. ->where(['Categories.id' => 2])
  574. ->first()
  575. ->toArray();
  576. $this->assertSame($expected, $result);
  577. }
  578. /**
  579. * Tests that hasMany() creates and configures correctly the association
  580. *
  581. * @return void
  582. */
  583. public function testHasMany()
  584. {
  585. $options = [
  586. 'foreignKey' => 'author_id',
  587. 'conditions' => ['b' => 'c'],
  588. 'sort' => ['foo' => 'asc']
  589. ];
  590. $table = new Table(['table' => 'authors']);
  591. $hasMany = $table->hasMany('article', $options);
  592. $this->assertInstanceOf('Cake\ORM\Association\HasMany', $hasMany);
  593. $this->assertSame($hasMany, $table->association('article'));
  594. $this->assertEquals('article', $hasMany->name());
  595. $this->assertEquals('author_id', $hasMany->foreignKey());
  596. $this->assertEquals(['b' => 'c'], $hasMany->conditions());
  597. $this->assertEquals(['foo' => 'asc'], $hasMany->sort());
  598. $this->assertSame($table, $hasMany->source());
  599. }
  600. /**
  601. * testHasManyWithClassName
  602. *
  603. * @return void
  604. */
  605. public function testHasManyWithClassName()
  606. {
  607. $table = TableRegistry::get('Articles');
  608. $table->hasMany('Comments', [
  609. 'className' => 'Comments',
  610. 'conditions' => ['published' => 'Y'],
  611. ]);
  612. $table->hasMany('UnapprovedComments', [
  613. 'className' => 'Comments',
  614. 'conditions' => ['published' => 'N'],
  615. 'propertyName' => 'unaproved_comments'
  616. ]);
  617. $expected = [
  618. 'id' => 1,
  619. 'title' => 'First Article',
  620. 'unaproved_comments' => [
  621. [
  622. 'id' => 4,
  623. 'article_id' => 1,
  624. 'comment' => 'Fourth Comment for First Article'
  625. ]
  626. ],
  627. 'comments' => [
  628. [
  629. 'id' => 1,
  630. 'article_id' => 1,
  631. 'comment' => 'First Comment for First Article'
  632. ],
  633. [
  634. 'id' => 2,
  635. 'article_id' => 1,
  636. 'comment' => 'Second Comment for First Article'
  637. ],
  638. [
  639. 'id' => 3,
  640. 'article_id' => 1,
  641. 'comment' => 'Third Comment for First Article'
  642. ]
  643. ]
  644. ];
  645. $result = $table->find()
  646. ->select(['id', 'title'])
  647. ->contain([
  648. 'Comments' => ['fields' => ['id', 'article_id', 'comment']],
  649. 'UnapprovedComments' => ['fields' => ['id', 'article_id', 'comment']]
  650. ])
  651. ->where(['id' => 1])
  652. ->first();
  653. $this->assertSame($expected, $result->toArray());
  654. }
  655. /**
  656. * Ensure associations use the plugin-prefixed model
  657. *
  658. * @return void
  659. */
  660. public function testHasManyPluginOverlap()
  661. {
  662. TableRegistry::get('Comments');
  663. Plugin::load('TestPlugin');
  664. $table = new Table(['table' => 'authors']);
  665. $table->hasMany('TestPlugin.Comments');
  666. $comments = $table->Comments->target();
  667. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  668. }
  669. /**
  670. * Ensure associations use the plugin-prefixed model
  671. * even if specified with config
  672. *
  673. * @return void
  674. */
  675. public function testHasManyPluginOverlapConfig()
  676. {
  677. TableRegistry::get('Comments');
  678. Plugin::load('TestPlugin');
  679. $table = new Table(['table' => 'authors']);
  680. $table->hasMany('Comments', ['className' => 'TestPlugin.Comments']);
  681. $comments = $table->Comments->target();
  682. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  683. }
  684. /**
  685. * Tests that BelongsToMany() creates and configures correctly the association
  686. *
  687. * @return void
  688. */
  689. public function testBelongsToMany()
  690. {
  691. $options = [
  692. 'foreignKey' => 'thing_id',
  693. 'joinTable' => 'things_tags',
  694. 'conditions' => ['b' => 'c'],
  695. 'sort' => ['foo' => 'asc']
  696. ];
  697. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  698. $belongsToMany = $table->belongsToMany('tag', $options);
  699. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  700. $this->assertSame($belongsToMany, $table->association('tag'));
  701. $this->assertEquals('tag', $belongsToMany->name());
  702. $this->assertEquals('thing_id', $belongsToMany->foreignKey());
  703. $this->assertEquals(['b' => 'c'], $belongsToMany->conditions());
  704. $this->assertEquals(['foo' => 'asc'], $belongsToMany->sort());
  705. $this->assertSame($table, $belongsToMany->source());
  706. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  707. }
  708. /**
  709. * Test addAssociations()
  710. *
  711. * @return void
  712. */
  713. public function testAddAssociations()
  714. {
  715. $params = [
  716. 'belongsTo' => [
  717. 'users' => ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']]
  718. ],
  719. 'hasOne' => ['profiles'],
  720. 'hasMany' => ['authors'],
  721. 'belongsToMany' => [
  722. 'tags' => ['joinTable' => 'things_tags']
  723. ]
  724. ];
  725. $table = new Table(['table' => 'dates']);
  726. $table->addAssociations($params);
  727. $associations = $table->associations();
  728. $belongsTo = $associations->get('users');
  729. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  730. $this->assertEquals('users', $belongsTo->name());
  731. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  732. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  733. $this->assertSame($table, $belongsTo->source());
  734. $hasOne = $associations->get('profiles');
  735. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  736. $this->assertEquals('profiles', $hasOne->name());
  737. $hasMany = $associations->get('authors');
  738. $this->assertInstanceOf('Cake\ORM\Association\hasMany', $hasMany);
  739. $this->assertEquals('authors', $hasMany->name());
  740. $belongsToMany = $associations->get('tags');
  741. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  742. $this->assertEquals('tags', $belongsToMany->name());
  743. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  744. }
  745. /**
  746. * Test basic multi row updates.
  747. *
  748. * @return void
  749. */
  750. public function testUpdateAll()
  751. {
  752. $table = new Table([
  753. 'table' => 'users',
  754. 'connection' => $this->connection,
  755. ]);
  756. $fields = ['username' => 'mark'];
  757. $result = $table->updateAll($fields, ['id <' => 4]);
  758. $this->assertSame(3, $result);
  759. $result = $table->find('all')
  760. ->select(['username'])
  761. ->order(['id' => 'asc'])
  762. ->hydrate(false)
  763. ->toArray();
  764. $expected = array_fill(0, 3, $fields);
  765. $expected[] = ['username' => 'garrett'];
  766. $this->assertEquals($expected, $result);
  767. }
  768. /**
  769. * Test that exceptions from the Query bubble up.
  770. *
  771. * @expectedException \Cake\Database\Exception
  772. */
  773. public function testUpdateAllFailure()
  774. {
  775. $table = $this->getMock(
  776. 'Cake\ORM\Table',
  777. ['query'],
  778. [['table' => 'users', 'connection' => $this->connection]]
  779. );
  780. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  781. $table->expects($this->once())
  782. ->method('query')
  783. ->will($this->returnValue($query));
  784. $query->expects($this->once())
  785. ->method('execute')
  786. ->will($this->throwException(new Exception('Not good')));
  787. $table->updateAll(['username' => 'mark'], []);
  788. }
  789. /**
  790. * Test deleting many records.
  791. *
  792. * @return void
  793. */
  794. public function testDeleteAll()
  795. {
  796. $table = new Table([
  797. 'table' => 'users',
  798. 'connection' => $this->connection,
  799. ]);
  800. $result = $table->deleteAll(['id <' => 4]);
  801. $this->assertSame(3, $result);
  802. $result = $table->find('all')->toArray();
  803. $this->assertCount(1, $result, 'Only one record should remain');
  804. $this->assertEquals(4, $result[0]['id']);
  805. }
  806. /**
  807. * Test deleting many records with conditions using the alias
  808. *
  809. * @return void
  810. */
  811. public function testDeleteAllAliasedConditions()
  812. {
  813. $table = new Table([
  814. 'table' => 'users',
  815. 'alias' => 'Managers',
  816. 'connection' => $this->connection,
  817. ]);
  818. $result = $table->deleteAll(['Managers.id <' => 4]);
  819. $this->assertSame(3, $result);
  820. $result = $table->find('all')->toArray();
  821. $this->assertCount(1, $result, 'Only one record should remain');
  822. $this->assertEquals(4, $result[0]['id']);
  823. }
  824. /**
  825. * Test that exceptions from the Query bubble up.
  826. *
  827. * @expectedException \Cake\Database\Exception
  828. */
  829. public function testDeleteAllFailure()
  830. {
  831. $table = $this->getMock(
  832. 'Cake\ORM\Table',
  833. ['query'],
  834. [['table' => 'users', 'connection' => $this->connection]]
  835. );
  836. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  837. $table->expects($this->once())
  838. ->method('query')
  839. ->will($this->returnValue($query));
  840. $query->expects($this->once())
  841. ->method('execute')
  842. ->will($this->throwException(new Exception('Not good')));
  843. $table->deleteAll(['id >' => 4]);
  844. }
  845. /**
  846. * Tests that array options are passed to the query object using applyOptions
  847. *
  848. * @return void
  849. */
  850. public function testFindApplyOptions()
  851. {
  852. $table = $this->getMock(
  853. 'Cake\ORM\Table',
  854. ['query', 'findAll'],
  855. [['table' => 'users', 'connection' => $this->connection]]
  856. );
  857. $query = $this->getMock('Cake\ORM\Query', [], [$this->connection, $table]);
  858. $table->expects($this->once())
  859. ->method('query')
  860. ->will($this->returnValue($query));
  861. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  862. $query->expects($this->any())
  863. ->method('select')
  864. ->will($this->returnSelf());
  865. $query->expects($this->once())->method('getOptions')
  866. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  867. $query->expects($this->once())
  868. ->method('applyOptions')
  869. ->with($options);
  870. $table->expects($this->once())->method('findAll')
  871. ->with($query, ['connections' => ['a >' => 1]]);
  872. $table->find('all', $options);
  873. }
  874. /**
  875. * Tests find('list')
  876. *
  877. * @return void
  878. */
  879. public function testFindListNoHydration()
  880. {
  881. $table = new Table([
  882. 'table' => 'users',
  883. 'connection' => $this->connection,
  884. ]);
  885. $table->displayField('username');
  886. $query = $table->find('list')
  887. ->hydrate(false)
  888. ->order('id');
  889. $expected = [
  890. 1 => 'mariano',
  891. 2 => 'nate',
  892. 3 => 'larry',
  893. 4 => 'garrett'
  894. ];
  895. $this->assertSame($expected, $query->toArray());
  896. $query = $table->find('list', ['fields' => ['id', 'username']])
  897. ->hydrate(false)
  898. ->order('id');
  899. $expected = [
  900. 1 => 'mariano',
  901. 2 => 'nate',
  902. 3 => 'larry',
  903. 4 => 'garrett'
  904. ];
  905. $this->assertSame($expected, $query->toArray());
  906. $query = $table->find('list', ['groupField' => 'odd'])
  907. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  908. ->hydrate(false)
  909. ->order('id');
  910. $expected = [
  911. 1 => [
  912. 1 => 'mariano',
  913. 3 => 'larry'
  914. ],
  915. 0 => [
  916. 2 => 'nate',
  917. 4 => 'garrett'
  918. ]
  919. ];
  920. $this->assertSame($expected, $query->toArray());
  921. }
  922. /**
  923. * Tests find('threaded')
  924. *
  925. * @return void
  926. */
  927. public function testFindThreadedNoHydration()
  928. {
  929. $table = new Table([
  930. 'table' => 'categories',
  931. 'connection' => $this->connection,
  932. ]);
  933. $expected = [
  934. [
  935. 'id' => 1,
  936. 'parent_id' => 0,
  937. 'name' => 'Category 1',
  938. 'children' => [
  939. [
  940. 'id' => 2,
  941. 'parent_id' => 1,
  942. 'name' => 'Category 1.1',
  943. 'children' => [
  944. [
  945. 'id' => 7,
  946. 'parent_id' => 2,
  947. 'name' => 'Category 1.1.1',
  948. 'children' => []
  949. ],
  950. [
  951. 'id' => 8,
  952. 'parent_id' => '2',
  953. 'name' => 'Category 1.1.2',
  954. 'children' => []
  955. ]
  956. ],
  957. ],
  958. [
  959. 'id' => 3,
  960. 'parent_id' => '1',
  961. 'name' => 'Category 1.2',
  962. 'children' => []
  963. ],
  964. ]
  965. ],
  966. [
  967. 'id' => 4,
  968. 'parent_id' => 0,
  969. 'name' => 'Category 2',
  970. 'children' => []
  971. ],
  972. [
  973. 'id' => 5,
  974. 'parent_id' => 0,
  975. 'name' => 'Category 3',
  976. 'children' => [
  977. [
  978. 'id' => '6',
  979. 'parent_id' => '5',
  980. 'name' => 'Category 3.1',
  981. 'children' => []
  982. ]
  983. ]
  984. ]
  985. ];
  986. $results = $table->find('all')
  987. ->select(['id', 'parent_id', 'name'])
  988. ->hydrate(false)
  989. ->find('threaded')
  990. ->toArray();
  991. $this->assertEquals($expected, $results);
  992. }
  993. /**
  994. * Tests that finders can be stacked
  995. *
  996. * @return void
  997. */
  998. public function testStackingFinders()
  999. {
  1000. $table = $this->getMock('\Cake\ORM\Table', ['find', 'findList'], [], '', false);
  1001. $params = [$this->connection, $table];
  1002. $query = $this->getMock('\Cake\ORM\Query', ['addDefaultTypes'], $params);
  1003. $table->expects($this->once())
  1004. ->method('find')
  1005. ->with('threaded', ['order' => ['name' => 'ASC']])
  1006. ->will($this->returnValue($query));
  1007. $table->expects($this->once())
  1008. ->method('findList')
  1009. ->with($query, ['keyPath' => 'id'])
  1010. ->will($this->returnValue($query));
  1011. $result = $table
  1012. ->find('threaded', ['order' => ['name' => 'ASC']])
  1013. ->find('list', ['keyPath' => 'id']);
  1014. $this->assertSame($query, $result);
  1015. }
  1016. /**
  1017. * Tests find('threaded') with hydrated results
  1018. *
  1019. * @return void
  1020. */
  1021. public function testFindThreadedHydrated()
  1022. {
  1023. $table = new Table([
  1024. 'table' => 'categories',
  1025. 'connection' => $this->connection,
  1026. ]);
  1027. $results = $table->find('all')
  1028. ->find('threaded')
  1029. ->select(['id', 'parent_id', 'name'])
  1030. ->toArray();
  1031. $this->assertEquals(1, $results[0]->id);
  1032. $expected = [
  1033. 'id' => 8,
  1034. 'parent_id' => 2,
  1035. 'name' => 'Category 1.1.2',
  1036. 'children' => []
  1037. ];
  1038. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  1039. }
  1040. /**
  1041. * Tests find('list') with hydrated records
  1042. *
  1043. * @return void
  1044. */
  1045. public function testFindListHydrated()
  1046. {
  1047. $table = new Table([
  1048. 'table' => 'users',
  1049. 'connection' => $this->connection,
  1050. ]);
  1051. $table->displayField('username');
  1052. $query = $table
  1053. ->find('list', ['fields' => ['id', 'username']])
  1054. ->order('id');
  1055. $expected = [
  1056. 1 => 'mariano',
  1057. 2 => 'nate',
  1058. 3 => 'larry',
  1059. 4 => 'garrett'
  1060. ];
  1061. $this->assertSame($expected, $query->toArray());
  1062. $query = $table->find('list', ['groupField' => 'odd'])
  1063. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  1064. ->hydrate(true)
  1065. ->order('id');
  1066. $expected = [
  1067. 1 => [
  1068. 1 => 'mariano',
  1069. 3 => 'larry'
  1070. ],
  1071. 0 => [
  1072. 2 => 'nate',
  1073. 4 => 'garrett'
  1074. ]
  1075. ];
  1076. $this->assertSame($expected, $query->toArray());
  1077. }
  1078. /**
  1079. * Test that find('list') only selects required fields.
  1080. *
  1081. * @return void
  1082. */
  1083. public function testFindListSelectedFields()
  1084. {
  1085. $table = new Table([
  1086. 'table' => 'users',
  1087. 'connection' => $this->connection,
  1088. ]);
  1089. $table->displayField('username');
  1090. $query = $table->find('list');
  1091. $expected = ['id', 'username'];
  1092. $this->assertSame($expected, $query->clause('select'));
  1093. $query = $table->find('list', ['valueField' => function ($row) {
  1094. return $row->username;
  1095. }]);
  1096. $this->assertEmpty($query->clause('select'));
  1097. $expected = ['odd' => new QueryExpression('id % 2'), 'id', 'username'];
  1098. $query = $table->find('list', [
  1099. 'fields' => $expected,
  1100. 'groupField' => 'odd',
  1101. ]);
  1102. $this->assertSame($expected, $query->clause('select'));
  1103. $articles = new Table([
  1104. 'table' => 'articles',
  1105. 'connection' => $this->connection,
  1106. ]);
  1107. $query = $articles->find('list', ['groupField' => 'author_id']);
  1108. $expected = ['id', 'title', 'author_id'];
  1109. $this->assertSame($expected, $query->clause('select'));
  1110. $query = $articles->find('list', ['valueField' => ['author_id', 'title']])
  1111. ->order('id');
  1112. $expected = ['id', 'author_id', 'title'];
  1113. $this->assertSame($expected, $query->clause('select'));
  1114. $expected = [
  1115. 1 => '1;First Article',
  1116. 2 => '3;Second Article',
  1117. 3 => '1;Third Article',
  1118. ];
  1119. $this->assertSame($expected, $query->toArray());
  1120. }
  1121. /**
  1122. * test that find('list') does not auto add fields to select if using virtual properties
  1123. *
  1124. * @return void
  1125. */
  1126. public function testFindListWithVirtualField()
  1127. {
  1128. $table = new Table([
  1129. 'table' => 'users',
  1130. 'connection' => $this->connection,
  1131. 'entityClass' => '\TestApp\Model\Entity\VirtualUser'
  1132. ]);
  1133. $table->displayField('bonus');
  1134. $query = $table
  1135. ->find('list')
  1136. ->order('id');
  1137. $this->assertEmpty($query->clause('select'));
  1138. $expected = [
  1139. 1 => 'bonus',
  1140. 2 => 'bonus',
  1141. 3 => 'bonus',
  1142. 4 => 'bonus'
  1143. ];
  1144. $this->assertSame($expected, $query->toArray());
  1145. $query = $table->find('list', ['groupField' => 'odd']);
  1146. $this->assertEmpty($query->clause('select'));
  1147. }
  1148. /**
  1149. * Test find('list') with value field from associated table
  1150. *
  1151. * @return void
  1152. */
  1153. public function testFindListWithAssociatedTable()
  1154. {
  1155. $articles = new Table([
  1156. 'table' => 'articles',
  1157. 'connection' => $this->connection,
  1158. ]);
  1159. $articles->belongsTo('Authors');
  1160. $query = $articles->find('list', ['valueField' => 'author.name'])
  1161. ->contain(['Authors'])
  1162. ->order('articles.id');
  1163. $this->assertEmpty($query->clause('select'));
  1164. $expected = [
  1165. 1 => 'mariano',
  1166. 2 => 'larry',
  1167. 3 => 'mariano',
  1168. ];
  1169. $this->assertSame($expected, $query->toArray());
  1170. }
  1171. /**
  1172. * Test the default entityClass.
  1173. *
  1174. * @return void
  1175. */
  1176. public function testEntityClassDefault()
  1177. {
  1178. $table = new Table();
  1179. $this->assertEquals('\Cake\ORM\Entity', $table->entityClass());
  1180. }
  1181. /**
  1182. * Tests that using a simple string for entityClass will try to
  1183. * load the class from the App namespace
  1184. *
  1185. * @return void
  1186. */
  1187. public function testTableClassInApp()
  1188. {
  1189. $class = $this->getMockClass('\Cake\ORM\Entity');
  1190. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  1191. class_alias($class, 'TestApp\Model\Entity\TestUser');
  1192. }
  1193. $table = new Table();
  1194. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->entityClass('TestUser'));
  1195. }
  1196. /**
  1197. * Tests that using a simple string for entityClass will try to
  1198. * load the class from the Plugin namespace when using plugin notation
  1199. *
  1200. * @return void
  1201. */
  1202. public function testTableClassInPlugin()
  1203. {
  1204. $class = $this->getMockClass('\Cake\ORM\Entity');
  1205. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  1206. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  1207. }
  1208. $table = new Table();
  1209. $this->assertEquals(
  1210. 'MyPlugin\Model\Entity\SuperUser',
  1211. $table->entityClass('MyPlugin.SuperUser')
  1212. );
  1213. }
  1214. /**
  1215. * Tests that using a simple string for entityClass will throw an exception
  1216. * when the class does not exist in the namespace
  1217. *
  1218. * @expectedException \Cake\ORM\Exception\MissingEntityException
  1219. * @expectedExceptionMessage Entity class FooUser could not be found.
  1220. * @return void
  1221. */
  1222. public function testTableClassNonExisting()
  1223. {
  1224. $table = new Table;
  1225. $this->assertFalse($table->entityClass('FooUser'));
  1226. }
  1227. /**
  1228. * Tests getting the entityClass based on conventions for the entity
  1229. * namespace
  1230. *
  1231. * @return void
  1232. */
  1233. public function testTableClassConventionForAPP()
  1234. {
  1235. $table = new \TestApp\Model\Table\ArticlesTable;
  1236. $this->assertEquals('TestApp\Model\Entity\Article', $table->entityClass());
  1237. }
  1238. /**
  1239. * Tests setting a entity class object using the setter method
  1240. *
  1241. * @return void
  1242. */
  1243. public function testSetEntityClass()
  1244. {
  1245. $table = new Table;
  1246. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  1247. $table->entityClass($class);
  1248. $this->assertEquals($class, $table->entityClass());
  1249. }
  1250. /**
  1251. * Proves that associations, even though they are lazy loaded, will fetch
  1252. * records using the correct table class and hydrate with the correct entity
  1253. *
  1254. * @return void
  1255. */
  1256. public function testReciprocalBelongsToLoading()
  1257. {
  1258. $table = new \TestApp\Model\Table\ArticlesTable([
  1259. 'connection' => $this->connection,
  1260. ]);
  1261. $result = $table->find('all')->contain(['authors'])->first();
  1262. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  1263. }
  1264. /**
  1265. * Proves that associations, even though they are lazy loaded, will fetch
  1266. * records using the correct table class and hydrate with the correct entity
  1267. *
  1268. * @return void
  1269. */
  1270. public function testReciprocalHasManyLoading()
  1271. {
  1272. $table = new \TestApp\Model\Table\ArticlesTable([
  1273. 'connection' => $this->connection,
  1274. ]);
  1275. $result = $table->find('all')->contain(['authors' => ['articles']])->first();
  1276. $this->assertCount(2, $result->author->articles);
  1277. foreach ($result->author->articles as $article) {
  1278. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  1279. }
  1280. }
  1281. /**
  1282. * Tests that the correct table and entity are loaded for the join association in
  1283. * a belongsToMany setup
  1284. *
  1285. * @return void
  1286. */
  1287. public function testReciprocalBelongsToMany()
  1288. {
  1289. $table = new \TestApp\Model\Table\ArticlesTable([
  1290. 'connection' => $this->connection,
  1291. ]);
  1292. $result = $table->find('all')->contain(['tags'])->first();
  1293. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  1294. $this->assertInstanceOf(
  1295. 'TestApp\Model\Entity\ArticlesTag',
  1296. $result->tags[0]->_joinData
  1297. );
  1298. }
  1299. /**
  1300. * Tests that recently fetched entities are always clean
  1301. *
  1302. * @return void
  1303. */
  1304. public function testFindCleanEntities()
  1305. {
  1306. $table = new \TestApp\Model\Table\ArticlesTable([
  1307. 'connection' => $this->connection,
  1308. ]);
  1309. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1310. $this->assertCount(3, $results);
  1311. foreach ($results as $article) {
  1312. $this->assertFalse($article->dirty('id'));
  1313. $this->assertFalse($article->dirty('title'));
  1314. $this->assertFalse($article->dirty('author_id'));
  1315. $this->assertFalse($article->dirty('body'));
  1316. $this->assertFalse($article->dirty('published'));
  1317. $this->assertFalse($article->dirty('author'));
  1318. $this->assertFalse($article->author->dirty('id'));
  1319. $this->assertFalse($article->author->dirty('name'));
  1320. $this->assertFalse($article->dirty('tag'));
  1321. if ($article->tag) {
  1322. $this->assertFalse($article->tag[0]->_joinData->dirty('tag_id'));
  1323. }
  1324. }
  1325. }
  1326. /**
  1327. * Tests that recently fetched entities are marked as not new
  1328. *
  1329. * @return void
  1330. */
  1331. public function testFindPersistedEntities()
  1332. {
  1333. $table = new \TestApp\Model\Table\ArticlesTable([
  1334. 'connection' => $this->connection,
  1335. ]);
  1336. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1337. $this->assertCount(3, $results);
  1338. foreach ($results as $article) {
  1339. $this->assertFalse($article->isNew());
  1340. foreach ((array)$article->tag as $tag) {
  1341. $this->assertFalse($tag->isNew());
  1342. $this->assertFalse($tag->_joinData->isNew());
  1343. }
  1344. }
  1345. }
  1346. /**
  1347. * Tests the exists function
  1348. *
  1349. * @return void
  1350. */
  1351. public function testExists()
  1352. {
  1353. $table = TableRegistry::get('users');
  1354. $this->assertTrue($table->exists(['id' => 1]));
  1355. $this->assertFalse($table->exists(['id' => 501]));
  1356. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  1357. }
  1358. /**
  1359. * Test adding a behavior to a table.
  1360. *
  1361. * @return void
  1362. */
  1363. public function testAddBehavior()
  1364. {
  1365. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1366. $mock->expects($this->once())
  1367. ->method('load')
  1368. ->with('Sluggable');
  1369. $table = new Table([
  1370. 'table' => 'articles',
  1371. 'behaviors' => $mock
  1372. ]);
  1373. $table->addBehavior('Sluggable');
  1374. }
  1375. /**
  1376. * Test adding a behavior that is a duplicate.
  1377. *
  1378. * @return void
  1379. */
  1380. public function testAddBehaviorDuplicate()
  1381. {
  1382. $table = new Table(['table' => 'articles']);
  1383. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1384. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1385. try {
  1386. $table->addBehavior('Sluggable', ['thing' => 'thing']);
  1387. $this->fail('No exception raised');
  1388. } catch (\RuntimeException $e) {
  1389. $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage());
  1390. }
  1391. }
  1392. /**
  1393. * Test removing a behavior from a table.
  1394. *
  1395. * @return void
  1396. */
  1397. public function testRemoveBehavior()
  1398. {
  1399. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1400. $mock->expects($this->once())
  1401. ->method('unload')
  1402. ->with('Sluggable');
  1403. $table = new Table([
  1404. 'table' => 'articles',
  1405. 'behaviors' => $mock
  1406. ]);
  1407. $table->removeBehavior('Sluggable');
  1408. }
  1409. /**
  1410. * Test getting a behavior instance from a table.
  1411. *
  1412. * @return void
  1413. */
  1414. public function testBehaviors()
  1415. {
  1416. $table = TableRegistry::get('article');
  1417. $result = $table->behaviors();
  1418. $this->assertInstanceOf('Cake\ORM\BehaviorRegistry', $result);
  1419. }
  1420. /**
  1421. * Ensure exceptions are raised on missing behaviors.
  1422. *
  1423. * @expectedException \Cake\ORM\Exception\MissingBehaviorException
  1424. */
  1425. public function testAddBehaviorMissing()
  1426. {
  1427. $table = TableRegistry::get('article');
  1428. $this->assertNull($table->addBehavior('NopeNotThere'));
  1429. }
  1430. /**
  1431. * Test mixin methods from behaviors.
  1432. *
  1433. * @return void
  1434. */
  1435. public function testCallBehaviorMethod()
  1436. {
  1437. $table = TableRegistry::get('article');
  1438. $table->addBehavior('Sluggable');
  1439. $this->assertEquals('some-value', $table->slugify('some value'));
  1440. }
  1441. /**
  1442. * Test you can alias a behavior method
  1443. *
  1444. * @return void
  1445. */
  1446. public function testCallBehaviorAliasedMethod()
  1447. {
  1448. $table = TableRegistry::get('article');
  1449. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  1450. $this->assertEquals('some-value', $table->wednesday('some value'));
  1451. }
  1452. /**
  1453. * Test finder methods from behaviors.
  1454. *
  1455. * @return void
  1456. */
  1457. public function testCallBehaviorFinder()
  1458. {
  1459. $table = TableRegistry::get('articles');
  1460. $table->addBehavior('Sluggable');
  1461. $query = $table->find('noSlug');
  1462. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1463. $this->assertNotEmpty($query->clause('where'));
  1464. }
  1465. /**
  1466. * testCallBehaviorAliasedFinder
  1467. *
  1468. * @return void
  1469. */
  1470. public function testCallBehaviorAliasedFinder()
  1471. {
  1472. $table = TableRegistry::get('articles');
  1473. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  1474. $query = $table->find('special');
  1475. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1476. $this->assertNotEmpty($query->clause('where'));
  1477. }
  1478. /**
  1479. * Test implementedEvents
  1480. *
  1481. * @return void
  1482. */
  1483. public function testImplementedEvents()
  1484. {
  1485. $table = $this->getMock(
  1486. 'Cake\ORM\Table',
  1487. ['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete']
  1488. );
  1489. $result = $table->implementedEvents();
  1490. $expected = [
  1491. 'Model.beforeFind' => 'beforeFind',
  1492. 'Model.beforeSave' => 'beforeSave',
  1493. 'Model.afterSave' => 'afterSave',
  1494. 'Model.beforeDelete' => 'beforeDelete',
  1495. 'Model.afterDelete' => 'afterDelete',
  1496. ];
  1497. $this->assertEquals($expected, $result, 'Events do not match.');
  1498. }
  1499. /**
  1500. * Tests that it is possible to insert a new row using the save method
  1501. *
  1502. * @group save
  1503. * @return void
  1504. */
  1505. public function testSaveNewEntity()
  1506. {
  1507. $entity = new \Cake\ORM\Entity([
  1508. 'username' => 'superuser',
  1509. 'password' => 'root',
  1510. 'created' => new Time('2013-10-10 00:00'),
  1511. 'updated' => new Time('2013-10-10 00:00')
  1512. ]);
  1513. $table = TableRegistry::get('users');
  1514. $this->assertSame($entity, $table->save($entity));
  1515. $this->assertEquals($entity->id, self::$nextUserId);
  1516. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1517. $this->assertEquals($entity->toArray(), $row->toArray());
  1518. }
  1519. /**
  1520. * Test that saving a new empty entity does nothing.
  1521. *
  1522. * @group save
  1523. * @return void
  1524. */
  1525. public function testSaveNewEmptyEntity()
  1526. {
  1527. $entity = new \Cake\ORM\Entity();
  1528. $table = TableRegistry::get('users');
  1529. $this->assertFalse($table->save($entity));
  1530. }
  1531. /**
  1532. * Test that saving a new empty entity does not call exists.
  1533. *
  1534. * @group save
  1535. * @return void
  1536. */
  1537. public function testSaveNewEntityNoExists()
  1538. {
  1539. $table = $this->getMock(
  1540. 'Cake\ORM\Table',
  1541. ['exists'],
  1542. [[
  1543. 'connection' => $this->connection,
  1544. 'alias' => 'Users',
  1545. 'table' => 'users',
  1546. ]]
  1547. );
  1548. $entity = $table->newEntity(['username' => 'mark']);
  1549. $this->assertTrue($entity->isNew());
  1550. $table->expects($this->never())
  1551. ->method('exists');
  1552. $this->assertSame($entity, $table->save($entity));
  1553. }
  1554. /**
  1555. * Test that saving a new entity with a Primary Key set does call exists.
  1556. *
  1557. * @group save
  1558. * @return void
  1559. */
  1560. public function testSavePrimaryKeyEntityExists()
  1561. {
  1562. $this->skipIfSqlServer();
  1563. $table = $this->getMock(
  1564. 'Cake\ORM\Table',
  1565. ['exists'],
  1566. [
  1567. [
  1568. 'connection' => $this->connection,
  1569. 'alias' => 'Users',
  1570. 'table' => 'users',
  1571. ]
  1572. ]
  1573. );
  1574. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1575. $this->assertTrue($entity->isNew());
  1576. $table->expects($this->once())->method('exists');
  1577. $this->assertSame($entity, $table->save($entity));
  1578. }
  1579. /**
  1580. * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false.
  1581. *
  1582. * @group save
  1583. * @return void
  1584. */
  1585. public function testSavePrimaryKeyEntityNoExists()
  1586. {
  1587. $this->skipIfSqlServer();
  1588. $table = $this->getMock(
  1589. 'Cake\ORM\Table',
  1590. ['exists'],
  1591. [
  1592. [
  1593. 'connection' => $this->connection,
  1594. 'alias' => 'Users',
  1595. 'table' => 'users',
  1596. ]
  1597. ]
  1598. );
  1599. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1600. $this->assertTrue($entity->isNew());
  1601. $table->expects($this->never())->method('exists');
  1602. $this->assertSame($entity, $table->save($entity, ['checkExisting' => false]));
  1603. }
  1604. /**
  1605. * Tests that saving an entity will filter out properties that
  1606. * are not present in the table schema when saving
  1607. *
  1608. * @group save
  1609. * @return void
  1610. */
  1611. public function testSaveEntityOnlySchemaFields()
  1612. {
  1613. $entity = new \Cake\ORM\Entity([
  1614. 'username' => 'superuser',
  1615. 'password' => 'root',
  1616. 'crazyness' => 'super crazy value',
  1617. 'created' => new Time('2013-10-10 00:00'),
  1618. 'updated' => new Time('2013-10-10 00:00'),
  1619. ]);
  1620. $table = TableRegistry::get('users');
  1621. $this->assertSame($entity, $table->save($entity));
  1622. $this->assertEquals($entity->id, self::$nextUserId);
  1623. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1624. $entity->unsetProperty('crazyness');
  1625. $this->assertEquals($entity->toArray(), $row->toArray());
  1626. }
  1627. /**
  1628. * Tests that it is possible to modify data from the beforeSave callback
  1629. *
  1630. * @group save
  1631. * @return void
  1632. */
  1633. public function testBeforeSaveModifyData()
  1634. {
  1635. $table = TableRegistry::get('users');
  1636. $data = new \Cake\ORM\Entity([
  1637. 'username' => 'superuser',
  1638. 'created' => new Time('2013-10-10 00:00'),
  1639. 'updated' => new Time('2013-10-10 00:00')
  1640. ]);
  1641. $listener = function ($e, $entity, $options) use ($data) {
  1642. $this->assertSame($data, $entity);
  1643. $entity->set('password', 'foo');
  1644. };
  1645. $table->eventManager()->on('Model.beforeSave', $listener);
  1646. $this->assertSame($data, $table->save($data));
  1647. $this->assertEquals($data->id, self::$nextUserId);
  1648. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1649. $this->assertEquals('foo', $row->get('password'));
  1650. }
  1651. /**
  1652. * Tests that it is possible to modify the options array in beforeSave
  1653. *
  1654. * @group save
  1655. * @return void
  1656. */
  1657. public function testBeforeSaveModifyOptions()
  1658. {
  1659. $table = TableRegistry::get('users');
  1660. $data = new \Cake\ORM\Entity([
  1661. 'username' => 'superuser',
  1662. 'password' => 'foo',
  1663. 'created' => new Time('2013-10-10 00:00'),
  1664. 'updated' => new Time('2013-10-10 00:00')
  1665. ]);
  1666. $listener1 = function ($e, $entity, $options) {
  1667. $options['crazy'] = true;
  1668. };
  1669. $listener2 = function ($e, $entity, $options) {
  1670. $this->assertTrue($options['crazy']);
  1671. };
  1672. $table->eventManager()->on('Model.beforeSave', $listener1);
  1673. $table->eventManager()->on('Model.beforeSave', $listener2);
  1674. $this->assertSame($data, $table->save($data));
  1675. $this->assertEquals($data->id, self::$nextUserId);
  1676. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1677. $this->assertEquals($data->toArray(), $row->toArray());
  1678. }
  1679. /**
  1680. * Tests that it is possible to stop the saving altogether, without implying
  1681. * the save operation failed
  1682. *
  1683. * @group save
  1684. * @return void
  1685. */
  1686. public function testBeforeSaveStopEvent()
  1687. {
  1688. $table = TableRegistry::get('users');
  1689. $data = new \Cake\ORM\Entity([
  1690. 'username' => 'superuser',
  1691. 'created' => new Time('2013-10-10 00:00'),
  1692. 'updated' => new Time('2013-10-10 00:00')
  1693. ]);
  1694. $listener = function ($e, $entity) {
  1695. $e->stopPropagation();
  1696. return $entity;
  1697. };
  1698. $table->eventManager()->on('Model.beforeSave', $listener);
  1699. $this->assertSame($data, $table->save($data));
  1700. $this->assertNull($data->id);
  1701. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1702. $this->assertNull($row);
  1703. }
  1704. /**
  1705. * Asserts that afterSave callback is called on successful save
  1706. *
  1707. * @group save
  1708. * @return void
  1709. */
  1710. public function testAfterSave()
  1711. {
  1712. $table = TableRegistry::get('users');
  1713. $data = new \Cake\ORM\Entity([
  1714. 'username' => 'superuser',
  1715. 'created' => new Time('2013-10-10 00:00'),
  1716. 'updated' => new Time('2013-10-10 00:00')
  1717. ]);
  1718. $called = false;
  1719. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1720. $this->assertSame($data, $entity);
  1721. $this->assertTrue($entity->dirty());
  1722. $called = true;
  1723. };
  1724. $table->eventManager()->on('Model.afterSave', $listener);
  1725. $calledAfterCommit = false;
  1726. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1727. $this->assertSame($data, $entity);
  1728. $this->assertFalse($entity->dirty());
  1729. $calledAfterCommit = true;
  1730. };
  1731. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1732. $this->assertSame($data, $table->save($data));
  1733. $this->assertEquals($data->id, self::$nextUserId);
  1734. $this->assertTrue($called);
  1735. $this->assertTrue($calledAfterCommit);
  1736. }
  1737. /**
  1738. * Asserts that afterSaveCommit is also triggered for non-atomic saves
  1739. *
  1740. * @return void
  1741. */
  1742. public function testAfterSaveCommitForNonAtomic()
  1743. {
  1744. $table = TableRegistry::get('users');
  1745. $data = new \Cake\ORM\Entity([
  1746. 'username' => 'superuser',
  1747. 'created' => new Time('2013-10-10 00:00'),
  1748. 'updated' => new Time('2013-10-10 00:00')
  1749. ]);
  1750. $called = false;
  1751. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1752. $this->assertSame($data, $entity);
  1753. $called = true;
  1754. };
  1755. $table->eventManager()->on('Model.afterSave', $listener);
  1756. $calledAfterCommit = false;
  1757. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1758. $calledAfterCommit = true;
  1759. };
  1760. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1761. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  1762. $this->assertEquals($data->id, self::$nextUserId);
  1763. $this->assertTrue($called);
  1764. $this->assertTrue($calledAfterCommit);
  1765. }
  1766. /**
  1767. * Asserts the afterSaveCommit is not triggered if transaction is running.
  1768. *
  1769. * @return void
  1770. */
  1771. public function testAfterSaveCommitWithTransactionRunning()
  1772. {
  1773. $table = TableRegistry::get('users');
  1774. $data = new \Cake\ORM\Entity([
  1775. 'username' => 'superuser',
  1776. 'created' => new Time('2013-10-10 00:00'),
  1777. 'updated' => new Time('2013-10-10 00:00')
  1778. ]);
  1779. $called = false;
  1780. $listener = function ($e, $entity, $options) use (&$called) {
  1781. $called = true;
  1782. };
  1783. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  1784. $this->connection->begin();
  1785. $this->assertSame($data, $table->save($data));
  1786. $this->assertFalse($called);
  1787. $this->connection->commit();
  1788. }
  1789. /**
  1790. * Asserts the afterSaveCommit is not triggered if transaction is running.
  1791. *
  1792. * @return void
  1793. */
  1794. public function testAfterSaveCommitWithNonAtomicAndTransactionRunning()
  1795. {
  1796. $table = TableRegistry::get('users');
  1797. $data = new \Cake\ORM\Entity([
  1798. 'username' => 'superuser',
  1799. 'created' => new Time('2013-10-10 00:00'),
  1800. 'updated' => new Time('2013-10-10 00:00')
  1801. ]);
  1802. $called = false;
  1803. $listener = function ($e, $entity, $options) use (&$called) {
  1804. $called = true;
  1805. };
  1806. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  1807. $this->connection->begin();
  1808. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  1809. $this->assertFalse($called);
  1810. $this->connection->commit();
  1811. }
  1812. /**
  1813. * Asserts that afterSave callback not is called on unsuccessful save
  1814. *
  1815. * @group save
  1816. * @return void
  1817. */
  1818. public function testAfterSaveNotCalled()
  1819. {
  1820. $table = $this->getMock(
  1821. '\Cake\ORM\Table',
  1822. ['query'],
  1823. [['table' => 'users', 'connection' => $this->connection]]
  1824. );
  1825. $query = $this->getMock(
  1826. '\Cake\ORM\Query',
  1827. ['execute', 'addDefaultTypes'],
  1828. [null, $table]
  1829. );
  1830. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1831. $data = new \Cake\ORM\Entity([
  1832. 'username' => 'superuser',
  1833. 'created' => new Time('2013-10-10 00:00'),
  1834. 'updated' => new Time('2013-10-10 00:00')
  1835. ]);
  1836. $table->expects($this->once())->method('query')
  1837. ->will($this->returnValue($query));
  1838. $query->expects($this->once())->method('execute')
  1839. ->will($this->returnValue($statement));
  1840. $statement->expects($this->once())->method('rowCount')
  1841. ->will($this->returnValue(0));
  1842. $called = false;
  1843. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1844. $called = true;
  1845. };
  1846. $table->eventManager()->on('Model.afterSave', $listener);
  1847. $calledAfterCommit = false;
  1848. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1849. $calledAfterCommit = true;
  1850. };
  1851. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1852. $this->assertFalse($table->save($data));
  1853. $this->assertFalse($called);
  1854. $this->assertFalse($calledAfterCommit);
  1855. }
  1856. /**
  1857. * Asserts that afterSaveCommit callback is triggered only for primary table
  1858. *
  1859. * @group save
  1860. * @return void
  1861. */
  1862. public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
  1863. {
  1864. $entity = new \Cake\ORM\Entity([
  1865. 'title' => 'A Title',
  1866. 'body' => 'A body'
  1867. ]);
  1868. $entity->author = new \Cake\ORM\Entity([
  1869. 'name' => 'Jose'
  1870. ]);
  1871. $table = TableRegistry::get('articles');
  1872. $table->belongsTo('authors');
  1873. $calledForArticle = false;
  1874. $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) {
  1875. $calledForArticle = true;
  1876. };
  1877. $table->eventManager()->on('Model.afterSaveCommit', $listenerForArticle);
  1878. $calledForAuthor = false;
  1879. $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) {
  1880. $calledForAuthor = true;
  1881. };
  1882. $table->authors->eventManager()->on('Model.afterSaveCommit', $listenerForAuthor);
  1883. $this->assertSame($entity, $table->save($entity));
  1884. $this->assertFalse($entity->isNew());
  1885. $this->assertFalse($entity->author->isNew());
  1886. $this->assertTrue($calledForArticle);
  1887. $this->assertFalse($calledForAuthor);
  1888. }
  1889. /**
  1890. * Test that you cannot save rows without a primary key.
  1891. *
  1892. * @group save
  1893. * @expectedException \RuntimeException
  1894. * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
  1895. * @return void
  1896. */
  1897. public function testSaveNewErrorOnNoPrimaryKey()
  1898. {
  1899. $entity = new \Cake\ORM\Entity(['username' => 'superuser']);
  1900. $table = TableRegistry::get('users', [
  1901. 'schema' => [
  1902. 'id' => ['type' => 'integer'],
  1903. 'username' => ['type' => 'string'],
  1904. ]
  1905. ]);
  1906. $table->save($entity);
  1907. }
  1908. /**
  1909. * Tests that save is wrapped around a transaction
  1910. *
  1911. * @group save
  1912. * @return void
  1913. */
  1914. public function testAtomicSave()
  1915. {
  1916. $config = ConnectionManager::config('test');
  1917. $connection = $this->getMock(
  1918. '\Cake\Database\Connection',
  1919. ['begin', 'commit'],
  1920. [$config]
  1921. );
  1922. $connection->driver($this->connection->driver());
  1923. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  1924. $table->expects($this->any())->method('connection')
  1925. ->will($this->returnValue($connection));
  1926. $connection->expects($this->once())->method('begin');
  1927. $connection->expects($this->once())->method('commit');
  1928. $data = new \Cake\ORM\Entity([
  1929. 'username' => 'superuser',
  1930. 'created' => new Time('2013-10-10 00:00'),
  1931. 'updated' => new Time('2013-10-10 00:00')
  1932. ]);
  1933. $this->assertSame($data, $table->save($data));
  1934. }
  1935. /**
  1936. * Tests that save will rollback the transaction in the case of an exception
  1937. *
  1938. * @group save
  1939. * @expectedException \PDOException
  1940. * @return void
  1941. */
  1942. public function testAtomicSaveRollback()
  1943. {
  1944. $connection = $this->getMock(
  1945. '\Cake\Database\Connection',
  1946. ['begin', 'rollback'],
  1947. [ConnectionManager::config('test')]
  1948. );
  1949. $connection->driver(ConnectionManager::get('test')->driver());
  1950. $table = $this->getMock(
  1951. '\Cake\ORM\Table',
  1952. ['query', 'connection'],
  1953. [['table' => 'users']]
  1954. );
  1955. $query = $this->getMock(
  1956. '\Cake\ORM\Query',
  1957. ['execute', 'addDefaultTypes'],
  1958. [null, $table]
  1959. );
  1960. $table->expects($this->any())->method('connection')
  1961. ->will($this->returnValue($connection));
  1962. $table->expects($this->once())->method('query')
  1963. ->will($this->returnValue($query));
  1964. $connection->expects($this->once())->method('begin');
  1965. $connection->expects($this->once())->method('rollback');
  1966. $query->expects($this->once())->method('execute')
  1967. ->will($this->throwException(new \PDOException));
  1968. $data = new \Cake\ORM\Entity([
  1969. 'username' => 'superuser',
  1970. 'created' => new Time('2013-10-10 00:00'),
  1971. 'updated' => new Time('2013-10-10 00:00')
  1972. ]);
  1973. $table->save($data);
  1974. }
  1975. /**
  1976. * Tests that save will rollback the transaction in the case of an exception
  1977. *
  1978. * @group save
  1979. * @return void
  1980. */
  1981. public function testAtomicSaveRollbackOnFailure()
  1982. {
  1983. $connection = $this->getMock(
  1984. '\Cake\Database\Connection',
  1985. ['begin', 'rollback'],
  1986. [ConnectionManager::config('test')]
  1987. );
  1988. $connection->driver(ConnectionManager::get('test')->driver());
  1989. $table = $this->getMock(
  1990. '\Cake\ORM\Table',
  1991. ['query', 'connection', 'exists'],
  1992. [['table' => 'users']]
  1993. );
  1994. $query = $this->getMock(
  1995. '\Cake\ORM\Query',
  1996. ['execute', 'addDefaultTypes'],
  1997. [null, $table]
  1998. );
  1999. $table->expects($this->any())->method('connection')
  2000. ->will($this->returnValue($connection));
  2001. $table->expects($this->once())->method('query')
  2002. ->will($this->returnValue($query));
  2003. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2004. $statement->expects($this->once())
  2005. ->method('rowCount')
  2006. ->will($this->returnValue(0));
  2007. $connection->expects($this->once())->method('begin');
  2008. $connection->expects($this->once())->method('rollback');
  2009. $query->expects($this->once())
  2010. ->method('execute')
  2011. ->will($this->returnValue($statement));
  2012. $data = new \Cake\ORM\Entity([
  2013. 'username' => 'superuser',
  2014. 'created' => new Time('2013-10-10 00:00'),
  2015. 'updated' => new Time('2013-10-10 00:00')
  2016. ]);
  2017. $table->save($data);
  2018. }
  2019. /**
  2020. * Tests that only the properties marked as dirty are actually saved
  2021. * to the database
  2022. *
  2023. * @group save
  2024. * @return void
  2025. */
  2026. public function testSaveOnlyDirtyProperties()
  2027. {
  2028. $entity = new \Cake\ORM\Entity([
  2029. 'username' => 'superuser',
  2030. 'password' => 'root',
  2031. 'created' => new Time('2013-10-10 00:00'),
  2032. 'updated' => new Time('2013-10-10 00:00')
  2033. ]);
  2034. $entity->clean();
  2035. $entity->dirty('username', true);
  2036. $entity->dirty('created', true);
  2037. $entity->dirty('updated', true);
  2038. $table = TableRegistry::get('users');
  2039. $this->assertSame($entity, $table->save($entity));
  2040. $this->assertEquals($entity->id, self::$nextUserId);
  2041. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  2042. $entity->set('password', null);
  2043. $this->assertEquals($entity->toArray(), $row->toArray());
  2044. }
  2045. /**
  2046. * Tests that a recently saved entity is marked as clean
  2047. *
  2048. * @group save
  2049. * @return void
  2050. */
  2051. public function testASavedEntityIsClean()
  2052. {
  2053. $entity = new \Cake\ORM\Entity([
  2054. 'username' => 'superuser',
  2055. 'password' => 'root',
  2056. 'created' => new Time('2013-10-10 00:00'),
  2057. 'updated' => new Time('2013-10-10 00:00')
  2058. ]);
  2059. $table = TableRegistry::get('users');
  2060. $this->assertSame($entity, $table->save($entity));
  2061. $this->assertFalse($entity->dirty('usermane'));
  2062. $this->assertFalse($entity->dirty('password'));
  2063. $this->assertFalse($entity->dirty('created'));
  2064. $this->assertFalse($entity->dirty('updated'));
  2065. }
  2066. /**
  2067. * Tests that a recently saved entity is marked as not new
  2068. *
  2069. * @group save
  2070. * @return void
  2071. */
  2072. public function testASavedEntityIsNotNew()
  2073. {
  2074. $entity = new \Cake\ORM\Entity([
  2075. 'username' => 'superuser',
  2076. 'password' => 'root',
  2077. 'created' => new Time('2013-10-10 00:00'),
  2078. 'updated' => new Time('2013-10-10 00:00')
  2079. ]);
  2080. $table = TableRegistry::get('users');
  2081. $this->assertSame($entity, $table->save($entity));
  2082. $this->assertFalse($entity->isNew());
  2083. }
  2084. /**
  2085. * Tests that save can detect automatically if it needs to insert
  2086. * or update a row
  2087. *
  2088. * @group save
  2089. * @return void
  2090. */
  2091. public function testSaveUpdateAuto()
  2092. {
  2093. $entity = new \Cake\ORM\Entity([
  2094. 'id' => 2,
  2095. 'username' => 'baggins'
  2096. ]);
  2097. $table = TableRegistry::get('users');
  2098. $original = $table->find('all')->where(['id' => 2])->first();
  2099. $this->assertSame($entity, $table->save($entity));
  2100. $row = $table->find('all')->where(['id' => 2])->first();
  2101. $this->assertEquals('baggins', $row->username);
  2102. $this->assertEquals($original->password, $row->password);
  2103. $this->assertEquals($original->created, $row->created);
  2104. $this->assertEquals($original->updated, $row->updated);
  2105. $this->assertFalse($entity->isNew());
  2106. $this->assertFalse($entity->dirty('id'));
  2107. $this->assertFalse($entity->dirty('username'));
  2108. }
  2109. /**
  2110. * Tests that beforeFind gets the correct isNew() state for the entity
  2111. *
  2112. * @return void
  2113. */
  2114. public function testBeforeSaveGetsCorrectPersistance()
  2115. {
  2116. $entity = new \Cake\ORM\Entity([
  2117. 'id' => 2,
  2118. 'username' => 'baggins'
  2119. ]);
  2120. $table = TableRegistry::get('users');
  2121. $called = false;
  2122. $listener = function ($event, $entity) use (&$called) {
  2123. $this->assertFalse($entity->isNew());
  2124. $called = true;
  2125. };
  2126. $table->eventManager()->on('Model.beforeSave', $listener);
  2127. $this->assertSame($entity, $table->save($entity));
  2128. $this->assertTrue($called);
  2129. }
  2130. /**
  2131. * Tests that marking an entity as already persisted will prevent the save
  2132. * method from trying to infer the entity's actual status.
  2133. *
  2134. * @group save
  2135. * @return void
  2136. */
  2137. public function testSaveUpdateWithHint()
  2138. {
  2139. $table = $this->getMock(
  2140. '\Cake\ORM\Table',
  2141. ['exists'],
  2142. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  2143. );
  2144. $entity = new \Cake\ORM\Entity([
  2145. 'id' => 2,
  2146. 'username' => 'baggins'
  2147. ], ['markNew' => false]);
  2148. $this->assertFalse($entity->isNew());
  2149. $table->expects($this->never())->method('exists');
  2150. $this->assertSame($entity, $table->save($entity));
  2151. }
  2152. /**
  2153. * Tests that when updating the primary key is not passed to the list of
  2154. * attributes to change
  2155. *
  2156. * @group save
  2157. * @return void
  2158. */
  2159. public function testSaveUpdatePrimaryKeyNotModified()
  2160. {
  2161. $table = $this->getMock(
  2162. '\Cake\ORM\Table',
  2163. ['query'],
  2164. [['table' => 'users', 'connection' => $this->connection]]
  2165. );
  2166. $query = $this->getMock(
  2167. '\Cake\ORM\Query',
  2168. ['execute', 'addDefaultTypes', 'set'],
  2169. [null, $table]
  2170. );
  2171. $table->expects($this->once())->method('query')
  2172. ->will($this->returnValue($query));
  2173. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2174. $statement->expects($this->once())
  2175. ->method('errorCode')
  2176. ->will($this->returnValue('00000'));
  2177. $query->expects($this->once())
  2178. ->method('execute')
  2179. ->will($this->returnValue($statement));
  2180. $query->expects($this->once())->method('set')
  2181. ->with(['username' => 'baggins'])
  2182. ->will($this->returnValue($query));
  2183. $entity = new \Cake\ORM\Entity([
  2184. 'id' => 2,
  2185. 'username' => 'baggins'
  2186. ], ['markNew' => false]);
  2187. $this->assertSame($entity, $table->save($entity));
  2188. }
  2189. /**
  2190. * Tests that passing only the primary key to save will not execute any queries
  2191. * but still return success
  2192. *
  2193. * @group save
  2194. * @return void
  2195. */
  2196. public function testUpdateNoChange()
  2197. {
  2198. $table = $this->getMock(
  2199. '\Cake\ORM\Table',
  2200. ['query'],
  2201. [['table' => 'users', 'connection' => $this->connection]]
  2202. );
  2203. $table->expects($this->never())->method('query');
  2204. $entity = new \Cake\ORM\Entity([
  2205. 'id' => 2,
  2206. ], ['markNew' => false]);
  2207. $this->assertSame($entity, $table->save($entity));
  2208. }
  2209. /**
  2210. * Tests that passing only the primary key to save will not execute any queries
  2211. * but still return success
  2212. *
  2213. * @group save
  2214. * @group integration
  2215. * @return void
  2216. */
  2217. public function testUpdateDirtyNoActualChanges()
  2218. {
  2219. $table = TableRegistry::get('Articles');
  2220. $entity = $table->get(1);
  2221. $entity->accessible('*', true);
  2222. $entity->set($entity->toArray());
  2223. $this->assertSame($entity, $table->save($entity));
  2224. }
  2225. /**
  2226. * Tests that failing to pass a primary key to save will result in exception
  2227. *
  2228. * @group save
  2229. * @expectedException \InvalidArgumentException
  2230. * @return void
  2231. */
  2232. public function testUpdateNoPrimaryButOtherKeys()
  2233. {
  2234. $table = $this->getMock(
  2235. '\Cake\ORM\Table',
  2236. ['query'],
  2237. [['table' => 'users', 'connection' => $this->connection]]
  2238. );
  2239. $table->expects($this->never())->method('query');
  2240. $entity = new \Cake\ORM\Entity([
  2241. 'username' => 'mariano',
  2242. ], ['markNew' => false]);
  2243. $this->assertSame($entity, $table->save($entity));
  2244. }
  2245. /**
  2246. * Test simple delete.
  2247. *
  2248. * @return void
  2249. */
  2250. public function testDelete()
  2251. {
  2252. $table = TableRegistry::get('users');
  2253. $conditions = [
  2254. 'limit' => 1,
  2255. 'conditions' => [
  2256. 'username' => 'nate'
  2257. ]
  2258. ];
  2259. $query = $table->find('all', $conditions);
  2260. $entity = $query->first();
  2261. $result = $table->delete($entity);
  2262. $this->assertTrue($result);
  2263. $query = $table->find('all', $conditions);
  2264. $results = $query->execute();
  2265. $this->assertCount(0, $results, 'Find should fail.');
  2266. }
  2267. /**
  2268. * Test delete with dependent records
  2269. *
  2270. * @return void
  2271. */
  2272. public function testDeleteDependent()
  2273. {
  2274. $table = TableRegistry::get('authors');
  2275. $table->hasOne('articles', [
  2276. 'foreignKey' => 'author_id',
  2277. 'dependent' => true,
  2278. ]);
  2279. $entity = $table->get(1);
  2280. $result = $table->delete($entity);
  2281. $articles = $table->association('articles')->target();
  2282. $query = $articles->find('all', [
  2283. 'conditions' => [
  2284. 'author_id' => $entity->id
  2285. ]
  2286. ]);
  2287. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2288. }
  2289. /**
  2290. * Test delete with dependent records
  2291. *
  2292. * @return void
  2293. */
  2294. public function testDeleteDependentHasMany()
  2295. {
  2296. $table = TableRegistry::get('authors');
  2297. $table->hasMany('articles', [
  2298. 'foreignKey' => 'author_id',
  2299. 'dependent' => true,
  2300. 'cascadeCallbacks' => true,
  2301. ]);
  2302. $entity = $table->get(1);
  2303. $result = $table->delete($entity);
  2304. $this->assertTrue($result);
  2305. }
  2306. /**
  2307. * Test delete with dependent = false does not cascade.
  2308. *
  2309. * @return void
  2310. */
  2311. public function testDeleteNoDependentNoCascade()
  2312. {
  2313. $table = TableRegistry::get('authors');
  2314. $table->hasMany('article', [
  2315. 'foreignKey' => 'author_id',
  2316. 'dependent' => false,
  2317. ]);
  2318. $query = $table->find('all')->where(['id' => 1]);
  2319. $entity = $query->first();
  2320. $result = $table->delete($entity);
  2321. $articles = $table->association('articles')->target();
  2322. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  2323. $this->assertCount(2, $query->execute(), 'Should find rows.');
  2324. }
  2325. /**
  2326. * Test delete with BelongsToMany
  2327. *
  2328. * @return void
  2329. */
  2330. public function testDeleteBelongsToMany()
  2331. {
  2332. $table = TableRegistry::get('articles');
  2333. $table->belongsToMany('tag', [
  2334. 'foreignKey' => 'article_id',
  2335. 'joinTable' => 'articles_tags'
  2336. ]);
  2337. $query = $table->find('all')->where(['id' => 1]);
  2338. $entity = $query->first();
  2339. $table->delete($entity);
  2340. $junction = $table->association('tags')->junction();
  2341. $query = $junction->find('all')->where(['article_id' => 1]);
  2342. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2343. }
  2344. /**
  2345. * Test delete with dependent records belonging to an aliased
  2346. * belongsToMany association.
  2347. *
  2348. * @return void
  2349. */
  2350. public function testDeleteDependentAliased()
  2351. {
  2352. $Authors = TableRegistry::get('authors');
  2353. $Authors->associations()->removeAll();
  2354. $Articles = TableRegistry::get('articles');
  2355. $Articles->associations()->removeAll();
  2356. $Authors->hasMany('AliasedArticles', [
  2357. 'className' => 'articles',
  2358. 'dependent' => true,
  2359. 'cascadeCallbacks' => true
  2360. ]);
  2361. $Articles->belongsToMany('Tags');
  2362. $author = $Authors->get(1);
  2363. $result = $Authors->delete($author);
  2364. $this->assertTrue($result);
  2365. }
  2366. /**
  2367. * Test that cascading associations are deleted first.
  2368. *
  2369. * @return void
  2370. */
  2371. public function testDeleteAssociationsCascadingCallbacksOrder()
  2372. {
  2373. $groups = TableRegistry::get('Groups');
  2374. $members = TableRegistry::get('Members');
  2375. $groupsMembers = TableRegistry::get('GroupsMembers');
  2376. $groups->belongsToMany('Members');
  2377. $groups->hasMany('GroupsMembers', [
  2378. 'dependent' => true,
  2379. 'cascadeCallbacks' => true,
  2380. ]);
  2381. $groupsMembers->belongsTo('Members');
  2382. $groupsMembers->addBehavior('CounterCache', [
  2383. 'Members' => ['group_count']
  2384. ]);
  2385. $member = $members->get(1);
  2386. $this->assertEquals(2, $member->group_count);
  2387. $group = $groups->get(1);
  2388. $groups->delete($group);
  2389. $member = $members->get(1);
  2390. $this->assertEquals(1, $member->group_count);
  2391. }
  2392. /**
  2393. * Test delete callbacks
  2394. *
  2395. * @return void
  2396. */
  2397. public function testDeleteCallbacks()
  2398. {
  2399. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2400. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]);
  2401. $mock = $this->getMock('Cake\Event\EventManager');
  2402. $mock->expects($this->at(0))
  2403. ->method('on');
  2404. $mock->expects($this->at(1))
  2405. ->method('dispatch');
  2406. $mock->expects($this->at(2))
  2407. ->method('dispatch')
  2408. ->with($this->logicalAnd(
  2409. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  2410. $this->attributeEqualTo(
  2411. 'data',
  2412. ['entity' => $entity, 'options' => $options]
  2413. )
  2414. ));
  2415. $mock->expects($this->at(3))
  2416. ->method('dispatch')
  2417. ->with($this->logicalAnd(
  2418. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  2419. $this->attributeEqualTo(
  2420. 'data',
  2421. ['entity' => $entity, 'options' => $options]
  2422. )
  2423. ));
  2424. $mock->expects($this->at(4))
  2425. ->method('dispatch')
  2426. ->with($this->logicalAnd(
  2427. $this->attributeEqualTo('_name', 'Model.afterDeleteCommit'),
  2428. $this->attributeEqualTo(
  2429. 'data',
  2430. ['entity' => $entity, 'options' => $options]
  2431. )
  2432. ));
  2433. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2434. $entity->isNew(false);
  2435. $table->delete($entity, ['checkRules' => false]);
  2436. }
  2437. /**
  2438. * Test afterDeleteCommit is also called for non-atomic delete
  2439. *
  2440. * @return void
  2441. */
  2442. public function testDeleteCallbacksNonAtomic()
  2443. {
  2444. $table = TableRegistry::get('users');
  2445. $data = $table->get(1);
  2446. $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]);
  2447. $called = false;
  2448. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2449. $this->assertSame($data, $entity);
  2450. $called = true;
  2451. };
  2452. $table->eventManager()->on('Model.afterDelete', $listener);
  2453. $calledAfterCommit = false;
  2454. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2455. $calledAfterCommit = true;
  2456. };
  2457. $table->eventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit);
  2458. $table->delete($data, ['atomic' => false]);
  2459. $this->assertTrue($called);
  2460. $this->assertTrue($calledAfterCommit);
  2461. }
  2462. /**
  2463. * Test that afterDeleteCommit is only triggered for primary table
  2464. *
  2465. * @return void
  2466. */
  2467. public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable()
  2468. {
  2469. $table = TableRegistry::get('authors');
  2470. $table->hasOne('articles', [
  2471. 'foreignKey' => 'author_id',
  2472. 'dependent' => true,
  2473. ]);
  2474. $called = false;
  2475. $listener = function ($e, $entity, $options) use (&$called) {
  2476. $called = true;
  2477. };
  2478. $table->eventManager()->on('Model.afterDeleteCommit', $listener);
  2479. $called2 = false;
  2480. $listener = function ($e, $entity, $options) use (&$called2) {
  2481. $called2 = true;
  2482. };
  2483. $table->articles->eventManager()->on('Model.afterDeleteCommit', $listener);
  2484. $entity = $table->get(1);
  2485. $this->assertTrue($table->delete($entity));
  2486. $this->assertTrue($called);
  2487. $this->assertFalse($called2);
  2488. }
  2489. /**
  2490. * Test delete beforeDelete can abort the delete.
  2491. *
  2492. * @return void
  2493. */
  2494. public function testDeleteBeforeDeleteAbort()
  2495. {
  2496. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2497. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2498. $mock = $this->getMock('Cake\Event\EventManager');
  2499. $mock->expects($this->at(2))
  2500. ->method('dispatch')
  2501. ->will($this->returnCallback(function ($event) {
  2502. $event->stopPropagation();
  2503. }));
  2504. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2505. $entity->isNew(false);
  2506. $result = $table->delete($entity, ['checkRules' => false]);
  2507. $this->assertNull($result);
  2508. }
  2509. /**
  2510. * Test delete beforeDelete return result
  2511. *
  2512. * @return void
  2513. */
  2514. public function testDeleteBeforeDeleteReturnResult()
  2515. {
  2516. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2517. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2518. $mock = $this->getMock('Cake\Event\EventManager');
  2519. $mock->expects($this->at(2))
  2520. ->method('dispatch')
  2521. ->will($this->returnCallback(function ($event) {
  2522. $event->stopPropagation();
  2523. $event->result = 'got stopped';
  2524. }));
  2525. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2526. $entity->isNew(false);
  2527. $result = $table->delete($entity, ['checkRules' => false]);
  2528. $this->assertEquals('got stopped', $result);
  2529. }
  2530. /**
  2531. * Test deleting new entities does nothing.
  2532. *
  2533. * @return void
  2534. */
  2535. public function testDeleteIsNew()
  2536. {
  2537. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2538. $table = $this->getMock(
  2539. 'Cake\ORM\Table',
  2540. ['query'],
  2541. [['connection' => $this->connection]]
  2542. );
  2543. $table->expects($this->never())
  2544. ->method('query');
  2545. $entity->isNew(true);
  2546. $result = $table->delete($entity);
  2547. $this->assertFalse($result);
  2548. }
  2549. /**
  2550. * test hasField()
  2551. *
  2552. * @return void
  2553. */
  2554. public function testHasField()
  2555. {
  2556. $table = TableRegistry::get('articles');
  2557. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  2558. $this->assertTrue($table->hasField('title'), 'Should be there.');
  2559. $this->assertTrue($table->hasField('body'), 'Should be there.');
  2560. }
  2561. /**
  2562. * Tests that there exists a default validator
  2563. *
  2564. * @return void
  2565. */
  2566. public function testValidatorDefault()
  2567. {
  2568. $table = new Table();
  2569. $validator = $table->validator();
  2570. $this->assertSame($table, $validator->provider('table'));
  2571. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  2572. $default = $table->validator('default');
  2573. $this->assertSame($validator, $default);
  2574. }
  2575. /**
  2576. * Tests that it is possible to define custom validator methods
  2577. *
  2578. * @return void
  2579. */
  2580. public function functionTestValidationWithDefiner()
  2581. {
  2582. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  2583. $table->expects($this->once())->method('validationForOtherStuff')
  2584. ->will($this->returnArgument(0));
  2585. $other = $table->validator('forOtherStuff');
  2586. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  2587. $this->assertNotSame($other, $table->validator());
  2588. $this->assertSame($table, $other->provider('table'));
  2589. }
  2590. /**
  2591. * Tests that it is possible to set a custom validator under a name
  2592. *
  2593. * @return void
  2594. */
  2595. public function testValidatorSetter()
  2596. {
  2597. $table = new Table;
  2598. $validator = new \Cake\Validation\Validator;
  2599. $table->validator('other', $validator);
  2600. $this->assertSame($validator, $table->validator('other'));
  2601. $this->assertSame($table, $validator->provider('table'));
  2602. }
  2603. /**
  2604. * Tests that the source of an existing Entity is the same as a new one
  2605. *
  2606. * @return void
  2607. */
  2608. public function testEntitySourceExistingAndNew()
  2609. {
  2610. Plugin::load('TestPlugin');
  2611. $table = TableRegistry::get('TestPlugin.Authors');
  2612. $existingAuthor = $table->find()->first();
  2613. $newAuthor = $table->newEntity();
  2614. $this->assertEquals('TestPlugin.Authors', $existingAuthor->source());
  2615. $this->assertEquals('TestPlugin.Authors', $newAuthor->source());
  2616. }
  2617. /**
  2618. * Tests that calling an entity with an empty array will run validation
  2619. * whereas calling it with no parameters will not run any validation.
  2620. *
  2621. * @return void
  2622. */
  2623. public function testNewEntityAndValidation()
  2624. {
  2625. $table = TableRegistry::get('Articles');
  2626. $validator = $table->validator()->requirePresence('title');
  2627. $entity = $table->newEntity([]);
  2628. $errors = $entity->errors();
  2629. $this->assertNotEmpty($errors['title']);
  2630. $entity = $table->newEntity();
  2631. $this->assertEmpty($entity->errors());
  2632. }
  2633. /**
  2634. * Test magic findByXX method.
  2635. *
  2636. * @return void
  2637. */
  2638. public function testMagicFindDefaultToAll()
  2639. {
  2640. $table = TableRegistry::get('Users');
  2641. $result = $table->findByUsername('garrett');
  2642. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2643. $expected = new QueryExpression(['Users.username' => 'garrett'], $this->usersTypeMap);
  2644. $this->assertEquals($expected, $result->clause('where'));
  2645. }
  2646. /**
  2647. * Test magic findByXX errors on missing arguments.
  2648. *
  2649. * @expectedException \BadMethodCallException
  2650. * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
  2651. * @return void
  2652. */
  2653. public function testMagicFindError()
  2654. {
  2655. $table = TableRegistry::get('Users');
  2656. $table->findByUsername();
  2657. }
  2658. /**
  2659. * Test magic findByXX errors on missing arguments.
  2660. *
  2661. * @expectedException \BadMethodCallException
  2662. * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
  2663. * @return void
  2664. */
  2665. public function testMagicFindErrorMissingField()
  2666. {
  2667. $table = TableRegistry::get('Users');
  2668. $table->findByUsernameAndId('garrett');
  2669. }
  2670. /**
  2671. * Test magic findByXX errors when there is a mix of or & and.
  2672. *
  2673. * @expectedException \BadMethodCallException
  2674. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  2675. * @return void
  2676. */
  2677. public function testMagicFindErrorMixOfOperators()
  2678. {
  2679. $table = TableRegistry::get('Users');
  2680. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  2681. }
  2682. /**
  2683. * Test magic findByXX method.
  2684. *
  2685. * @return void
  2686. */
  2687. public function testMagicFindFirstAnd()
  2688. {
  2689. $table = TableRegistry::get('Users');
  2690. $result = $table->findByUsernameAndId('garrett', 4);
  2691. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2692. $expected = new QueryExpression(['Users.username' => 'garrett', 'Users.id' => 4], $this->usersTypeMap);
  2693. $this->assertEquals($expected, $result->clause('where'));
  2694. }
  2695. /**
  2696. * Test magic findByXX method.
  2697. *
  2698. * @return void
  2699. */
  2700. public function testMagicFindFirstOr()
  2701. {
  2702. $table = TableRegistry::get('Users');
  2703. $result = $table->findByUsernameOrId('garrett', 4);
  2704. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2705. $expected = new QueryExpression([], $this->usersTypeMap);
  2706. $expected->add(
  2707. [
  2708. 'OR' => [
  2709. 'Users.username' => 'garrett',
  2710. 'Users.id' => 4
  2711. ]]
  2712. );
  2713. $this->assertEquals($expected, $result->clause('where'));
  2714. }
  2715. /**
  2716. * Test magic findAllByXX method.
  2717. *
  2718. * @return void
  2719. */
  2720. public function testMagicFindAll()
  2721. {
  2722. $table = TableRegistry::get('Articles');
  2723. $result = $table->findAllByAuthorId(1);
  2724. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2725. $this->assertNull($result->clause('limit'));
  2726. $expected = new QueryExpression(['Articles.author_id' => 1], $this->articlesTypeMap);
  2727. $this->assertEquals($expected, $result->clause('where'));
  2728. }
  2729. /**
  2730. * Test magic findAllByXX method.
  2731. *
  2732. * @return void
  2733. */
  2734. public function testMagicFindAllAnd()
  2735. {
  2736. $table = TableRegistry::get('Users');
  2737. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  2738. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2739. $this->assertNull($result->clause('limit'));
  2740. $expected = new QueryExpression(
  2741. ['Users.author_id' => 1, 'Users.published' => 'Y'],
  2742. $this->usersTypeMap
  2743. );
  2744. $this->assertEquals($expected, $result->clause('where'));
  2745. }
  2746. /**
  2747. * Test magic findAllByXX method.
  2748. *
  2749. * @return void
  2750. */
  2751. public function testMagicFindAllOr()
  2752. {
  2753. $table = TableRegistry::get('Users');
  2754. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  2755. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2756. $this->assertNull($result->clause('limit'));
  2757. $expected = new QueryExpression();
  2758. $expected->typeMap()->defaults([
  2759. 'Users.id' => 'integer',
  2760. 'id' => 'integer',
  2761. 'Users.username' => 'string',
  2762. 'username' => 'string',
  2763. 'Users.password' => 'string',
  2764. 'password' => 'string',
  2765. 'Users.created' => 'timestamp',
  2766. 'created' => 'timestamp',
  2767. 'Users.updated' => 'timestamp',
  2768. 'updated' => 'timestamp',
  2769. ]);
  2770. $expected->add(
  2771. ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']]
  2772. );
  2773. $this->assertEquals($expected, $result->clause('where'));
  2774. $this->assertNull($result->clause('order'));
  2775. }
  2776. /**
  2777. * Test the behavior method.
  2778. *
  2779. * @return void
  2780. */
  2781. public function testBehaviorIntrospection()
  2782. {
  2783. $table = TableRegistry::get('users');
  2784. $table->addBehavior('Timestamp');
  2785. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  2786. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  2787. }
  2788. /**
  2789. * Tests saving belongsTo association
  2790. *
  2791. * @group save
  2792. * @return void
  2793. */
  2794. public function testSaveBelongsTo()
  2795. {
  2796. $entity = new \Cake\ORM\Entity([
  2797. 'title' => 'A Title',
  2798. 'body' => 'A body'
  2799. ]);
  2800. $entity->author = new \Cake\ORM\Entity([
  2801. 'name' => 'Jose'
  2802. ]);
  2803. $table = TableRegistry::get('articles');
  2804. $table->belongsTo('authors');
  2805. $this->assertSame($entity, $table->save($entity));
  2806. $this->assertFalse($entity->isNew());
  2807. $this->assertFalse($entity->author->isNew());
  2808. $this->assertEquals(5, $entity->author->id);
  2809. $this->assertEquals(5, $entity->get('author_id'));
  2810. }
  2811. /**
  2812. * Tests saving hasOne association
  2813. *
  2814. * @group save
  2815. * @return void
  2816. */
  2817. public function testSaveHasOne()
  2818. {
  2819. $entity = new \Cake\ORM\Entity([
  2820. 'name' => 'Jose'
  2821. ]);
  2822. $entity->article = new \Cake\ORM\Entity([
  2823. 'title' => 'A Title',
  2824. 'body' => 'A body'
  2825. ]);
  2826. $table = TableRegistry::get('authors');
  2827. $table->hasOne('articles');
  2828. $this->assertSame($entity, $table->save($entity));
  2829. $this->assertFalse($entity->isNew());
  2830. $this->assertFalse($entity->article->isNew());
  2831. $this->assertEquals(4, $entity->article->id);
  2832. $this->assertEquals(5, $entity->article->get('author_id'));
  2833. $this->assertFalse($entity->article->dirty('author_id'));
  2834. }
  2835. /**
  2836. * Tests saving associations only saves associations
  2837. * if they are entities.
  2838. *
  2839. * @group save
  2840. * @return void
  2841. */
  2842. public function testSaveOnlySaveAssociatedEntities()
  2843. {
  2844. $entity = new \Cake\ORM\Entity([
  2845. 'name' => 'Jose'
  2846. ]);
  2847. // Not an entity.
  2848. $entity->article = [
  2849. 'title' => 'A Title',
  2850. 'body' => 'A body'
  2851. ];
  2852. $table = TableRegistry::get('authors');
  2853. $table->hasOne('articles');
  2854. $table->save($entity);
  2855. $this->assertFalse($entity->isNew());
  2856. $this->assertInternalType('array', $entity->article);
  2857. }
  2858. /**
  2859. * Tests saving multiple entities in a hasMany association
  2860. *
  2861. * @return void
  2862. */
  2863. public function testSaveHasMany()
  2864. {
  2865. $entity = new \Cake\ORM\Entity([
  2866. 'name' => 'Jose'
  2867. ]);
  2868. $entity->articles = [
  2869. new \Cake\ORM\Entity([
  2870. 'title' => 'A Title',
  2871. 'body' => 'A body'
  2872. ]),
  2873. new \Cake\ORM\Entity([
  2874. 'title' => 'Another Title',
  2875. 'body' => 'Another body'
  2876. ])
  2877. ];
  2878. $table = TableRegistry::get('authors');
  2879. $table->hasMany('articles');
  2880. $this->assertSame($entity, $table->save($entity));
  2881. $this->assertFalse($entity->isNew());
  2882. $this->assertFalse($entity->articles[0]->isNew());
  2883. $this->assertFalse($entity->articles[1]->isNew());
  2884. $this->assertEquals(4, $entity->articles[0]->id);
  2885. $this->assertEquals(5, $entity->articles[1]->id);
  2886. $this->assertEquals(5, $entity->articles[0]->author_id);
  2887. $this->assertEquals(5, $entity->articles[1]->author_id);
  2888. }
  2889. /**
  2890. * Tests saving belongsToMany records
  2891. *
  2892. * @group save
  2893. * @return void
  2894. */
  2895. public function testSaveBelongsToMany()
  2896. {
  2897. $entity = new \Cake\ORM\Entity([
  2898. 'title' => 'A Title',
  2899. 'body' => 'A body'
  2900. ]);
  2901. $entity->tags = [
  2902. new \Cake\ORM\Entity([
  2903. 'name' => 'Something New'
  2904. ]),
  2905. new \Cake\ORM\Entity([
  2906. 'name' => 'Another Something'
  2907. ])
  2908. ];
  2909. $table = TableRegistry::get('articles');
  2910. $table->belongsToMany('tags');
  2911. $this->assertSame($entity, $table->save($entity));
  2912. $this->assertFalse($entity->isNew());
  2913. $this->assertFalse($entity->tags[0]->isNew());
  2914. $this->assertFalse($entity->tags[1]->isNew());
  2915. $this->assertEquals(4, $entity->tags[0]->id);
  2916. $this->assertEquals(5, $entity->tags[1]->id);
  2917. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2918. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2919. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2920. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2921. }
  2922. /**
  2923. * Tests saving belongsToMany records when record exists.
  2924. *
  2925. * @group save
  2926. * @return void
  2927. */
  2928. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  2929. {
  2930. $tags = TableRegistry::get('Tags');
  2931. $table = TableRegistry::get('Articles');
  2932. $table->belongsToMany('Tags');
  2933. $entity = $table->find()->contain('Tags')->first();
  2934. // not associated to the article already.
  2935. $entity->tags[] = $tags->get(3);
  2936. $entity->dirty('tags', true);
  2937. $this->assertSame($entity, $table->save($entity));
  2938. $this->assertFalse($entity->isNew());
  2939. $this->assertFalse($entity->tags[0]->isNew());
  2940. $this->assertFalse($entity->tags[1]->isNew());
  2941. $this->assertFalse($entity->tags[2]->isNew());
  2942. $this->assertNotEmpty($entity->tags[0]->_joinData);
  2943. $this->assertNotEmpty($entity->tags[1]->_joinData);
  2944. $this->assertNotEmpty($entity->tags[2]->_joinData);
  2945. }
  2946. /**
  2947. * Test that belongsToMany can be saved with _joinData data.
  2948. *
  2949. * @return void
  2950. */
  2951. public function testSaveBelongsToManyJoinData()
  2952. {
  2953. $articles = TableRegistry::get('Articles');
  2954. $article = $articles->get(1, ['contain' => ['tags']]);
  2955. $data = [
  2956. 'tags' => [
  2957. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  2958. ['id' => 3]
  2959. ]
  2960. ];
  2961. $article = $articles->patchEntity($article, $data);
  2962. $result = $articles->save($article);
  2963. $this->assertSame($result, $article);
  2964. }
  2965. /**
  2966. * Test to check that association condition are used when fetching existing
  2967. * records to decide which records to unlink.
  2968. *
  2969. * @return void
  2970. */
  2971. public function testPolymorphicBelongsToManySave()
  2972. {
  2973. $articles = TableRegistry::get('Articles');
  2974. $articles->belongsToMany('Tags', [
  2975. 'through' => 'PolymorphicTagged',
  2976. 'foreignKey' => 'foreign_key',
  2977. 'conditions' => [
  2978. 'PolymorphicTagged.foreign_model' => 'Articles'
  2979. ],
  2980. 'sort' => ['PolymorphicTagged.position' => 'ASC']
  2981. ]);
  2982. $articles->Tags->junction()->belongsTo('Tags');
  2983. $entity = $articles->get(1, ['contain' => ['Tags']]);
  2984. $data = [
  2985. 'id' => 1,
  2986. 'tags' => [
  2987. [
  2988. 'id' => 1,
  2989. '_joinData' => [
  2990. 'id' => 2,
  2991. 'foreign_model' => 'Articles',
  2992. 'position' => 2
  2993. ]
  2994. ],
  2995. [
  2996. 'id' => 2,
  2997. '_joinData' => [
  2998. 'foreign_model' => 'Articles',
  2999. 'position' => 1
  3000. ]
  3001. ]
  3002. ]
  3003. ];
  3004. $entity = $articles->patchEntity($entity, $data, ['associated' => ['Tags._joinData']]);
  3005. $entity = $articles->save($entity);
  3006. $expected = [
  3007. [
  3008. 'id' => 1,
  3009. 'tag_id' => 1,
  3010. 'foreign_key' => 1,
  3011. 'foreign_model' => 'Posts',
  3012. 'position' => 1
  3013. ],
  3014. [
  3015. 'id' => 2,
  3016. 'tag_id' => 1,
  3017. 'foreign_key' => 1,
  3018. 'foreign_model' => 'Articles',
  3019. 'position' => 2
  3020. ],
  3021. [
  3022. 'id' => 3,
  3023. 'tag_id' => 2,
  3024. 'foreign_key' => 1,
  3025. 'foreign_model' => 'Articles',
  3026. 'position' => 1
  3027. ]
  3028. ];
  3029. $result = TableRegistry::get('PolymorphicTagged')
  3030. ->find('all', ['sort' => ['id' => 'DESC']])
  3031. ->hydrate(false)
  3032. ->toArray();
  3033. $this->assertEquals($expected, $result);
  3034. }
  3035. /**
  3036. * Tests saving belongsToMany records can delete all links.
  3037. *
  3038. * @group save
  3039. * @return void
  3040. */
  3041. public function testSaveBelongsToManyDeleteAllLinks()
  3042. {
  3043. $table = TableRegistry::get('articles');
  3044. $table->belongsToMany('tags', [
  3045. 'saveStrategy' => 'replace',
  3046. ]);
  3047. $entity = $table->get(1, ['contain' => 'tags']);
  3048. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3049. $entity->tags = [];
  3050. $result = $table->save($entity);
  3051. $this->assertSame($result, $entity);
  3052. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  3053. $entity = $table->get(1, ['contain' => 'tags']);
  3054. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  3055. }
  3056. /**
  3057. * Tests saving belongsToMany records can delete some links.
  3058. *
  3059. * @group save
  3060. * @return void
  3061. */
  3062. public function testSaveBelongsToManyDeleteSomeLinks()
  3063. {
  3064. $table = TableRegistry::get('articles');
  3065. $table->belongsToMany('tags', [
  3066. 'saveStrategy' => 'replace',
  3067. ]);
  3068. $entity = $table->get(1, ['contain' => 'tags']);
  3069. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3070. $tag = new \Cake\ORM\Entity([
  3071. 'id' => 2,
  3072. ]);
  3073. $entity->tags = [$tag];
  3074. $result = $table->save($entity);
  3075. $this->assertSame($result, $entity);
  3076. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  3077. $this->assertEquals($tag, $entity->tags[0]);
  3078. $entity = $table->get(1, ['contain' => 'tags']);
  3079. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  3080. $this->assertEquals($tag->id, $entity->tags[0]->id);
  3081. }
  3082. /**
  3083. * Test that belongsToMany ignores non-entity data.
  3084. *
  3085. * @return void
  3086. */
  3087. public function testSaveBelongsToManyIgnoreNonEntityData()
  3088. {
  3089. $articles = TableRegistry::get('articles');
  3090. $article = $articles->get(1, ['contain' => ['tags']]);
  3091. $article->tags = [
  3092. '_ids' => [2, 1]
  3093. ];
  3094. $result = $articles->save($article);
  3095. $this->assertSame($result, $article);
  3096. }
  3097. /**
  3098. * Tests that saving a persisted and clean entity will is a no-op
  3099. *
  3100. * @group save
  3101. * @return void
  3102. */
  3103. public function testSaveCleanEntity()
  3104. {
  3105. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  3106. $entity = new \Cake\ORM\Entity(
  3107. ['id' => 'foo'],
  3108. ['markNew' => false, 'markClean' => true]
  3109. );
  3110. $table->expects($this->never())->method('_processSave');
  3111. $this->assertSame($entity, $table->save($entity));
  3112. }
  3113. /**
  3114. * Integration test to show how to append a new tag to an article
  3115. *
  3116. * @group save
  3117. * @return void
  3118. */
  3119. public function testBelongsToManyIntegration()
  3120. {
  3121. $table = TableRegistry::get('articles');
  3122. $table->belongsToMany('tags');
  3123. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3124. $tags = $article->tags;
  3125. $this->assertNotEmpty($tags);
  3126. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  3127. $article->tags = $tags;
  3128. $this->assertSame($article, $table->save($article));
  3129. $tags = $article->tags;
  3130. $this->assertCount(3, $tags);
  3131. $this->assertFalse($tags[2]->isNew());
  3132. $this->assertEquals(4, $tags[2]->id);
  3133. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  3134. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  3135. }
  3136. /**
  3137. * Tests that it is possible to do a deep save and control what associations get saved,
  3138. * while having control of the options passed to each level of the save
  3139. *
  3140. * @group save
  3141. * @return void
  3142. */
  3143. public function testSaveDeepAssociationOptions()
  3144. {
  3145. $articles = $this->getMock(
  3146. '\Cake\ORM\Table',
  3147. ['_insert'],
  3148. [['table' => 'articles', 'connection' => $this->connection]]
  3149. );
  3150. $authors = $this->getMock(
  3151. '\Cake\ORM\Table',
  3152. ['_insert'],
  3153. [['table' => 'authors', 'connection' => $this->connection]]
  3154. );
  3155. $supervisors = $this->getMock(
  3156. '\Cake\ORM\Table',
  3157. ['_insert', 'validate'],
  3158. [[
  3159. 'table' => 'authors',
  3160. 'alias' => 'supervisors',
  3161. 'connection' => $this->connection
  3162. ]]
  3163. );
  3164. $tags = $this->getMock(
  3165. '\Cake\ORM\Table',
  3166. ['_insert'],
  3167. [['table' => 'tags', 'connection' => $this->connection]]
  3168. );
  3169. $articles->belongsTo('authors', ['targetTable' => $authors]);
  3170. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  3171. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  3172. $entity = new \Cake\ORM\Entity([
  3173. 'title' => 'bar',
  3174. 'author' => new \Cake\ORM\Entity([
  3175. 'name' => 'Juan',
  3176. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  3177. 'tags' => [
  3178. new \Cake\ORM\Entity(['name' => 'foo'])
  3179. ]
  3180. ]),
  3181. ]);
  3182. $entity->isNew(true);
  3183. $entity->author->isNew(true);
  3184. $entity->author->supervisor->isNew(true);
  3185. $entity->author->tags[0]->isNew(true);
  3186. $articles->expects($this->once())
  3187. ->method('_insert')
  3188. ->with($entity, ['title' => 'bar'])
  3189. ->will($this->returnValue($entity));
  3190. $authors->expects($this->once())
  3191. ->method('_insert')
  3192. ->with($entity->author, ['name' => 'Juan'])
  3193. ->will($this->returnValue($entity->author));
  3194. $supervisors->expects($this->once())
  3195. ->method('_insert')
  3196. ->with($entity->author->supervisor, ['name' => 'Marc'])
  3197. ->will($this->returnValue($entity->author->supervisor));
  3198. $tags->expects($this->never())->method('_insert');
  3199. $this->assertSame($entity, $articles->save($entity, [
  3200. 'associated' => [
  3201. 'authors' => [],
  3202. 'authors.supervisors' => [
  3203. 'atomic' => false,
  3204. 'associated' => false
  3205. ]
  3206. ]
  3207. ]));
  3208. }
  3209. /**
  3210. * Integration test for linking entities with belongsToMany
  3211. *
  3212. * @return void
  3213. */
  3214. public function testLinkBelongsToMany()
  3215. {
  3216. $table = TableRegistry::get('articles');
  3217. $table->belongsToMany('tags');
  3218. $tagsTable = TableRegistry::get('tags');
  3219. $source = ['source' => 'tags'];
  3220. $options = ['markNew' => false];
  3221. $article = new \Cake\ORM\Entity([
  3222. 'id' => 1,
  3223. ], $options);
  3224. $newTag = new \TestApp\Model\Entity\Tag([
  3225. 'name' => 'Foo'
  3226. ], $source);
  3227. $tags[] = new \TestApp\Model\Entity\Tag([
  3228. 'id' => 3
  3229. ], $options + $source);
  3230. $tags[] = $newTag;
  3231. $tagsTable->save($newTag);
  3232. $table->association('tags')->link($article, $tags);
  3233. $this->assertEquals($article->tags, $tags);
  3234. foreach ($tags as $tag) {
  3235. $this->assertFalse($tag->isNew());
  3236. }
  3237. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3238. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  3239. $this->assertEquals($article->tags[3], $tags[1]);
  3240. }
  3241. /**
  3242. * Integration test to show how to unlink a single record from a belongsToMany
  3243. *
  3244. * @return void
  3245. */
  3246. public function testUnlinkBelongsToMany()
  3247. {
  3248. $table = TableRegistry::get('articles');
  3249. $table->belongsToMany('tags');
  3250. $tagsTable = TableRegistry::get('tags');
  3251. $options = ['markNew' => false];
  3252. $article = $table->find('all')
  3253. ->where(['id' => 1])
  3254. ->contain(['tags'])->first();
  3255. $table->association('tags')->unlink($article, [$article->tags[0]]);
  3256. $this->assertCount(1, $article->tags);
  3257. $this->assertEquals(2, $article->tags[0]->get('id'));
  3258. $this->assertFalse($article->dirty('tags'));
  3259. }
  3260. /**
  3261. * Integration test to show how to unlink multiple records from a belongsToMany
  3262. *
  3263. * @return void
  3264. */
  3265. public function testUnlinkBelongsToManyMultiple()
  3266. {
  3267. $table = TableRegistry::get('articles');
  3268. $table->belongsToMany('tags');
  3269. $tagsTable = TableRegistry::get('tags');
  3270. $options = ['markNew' => false];
  3271. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3272. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3273. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3274. $table->association('tags')->unlink($article, $tags);
  3275. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3276. $this->assertEmpty($left->tags);
  3277. }
  3278. /**
  3279. * Integration test to show how to unlink multiple records from a belongsToMany
  3280. * providing some of the joint
  3281. *
  3282. * @return void
  3283. */
  3284. public function testUnlinkBelongsToManyPassingJoint()
  3285. {
  3286. $table = TableRegistry::get('articles');
  3287. $table->belongsToMany('tags');
  3288. $tagsTable = TableRegistry::get('tags');
  3289. $options = ['markNew' => false];
  3290. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3291. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3292. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3293. $tags[1]->_joinData = new \Cake\ORM\Entity([
  3294. 'article_id' => 1,
  3295. 'tag_id' => 2
  3296. ], $options);
  3297. $table->association('tags')->unlink($article, $tags);
  3298. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3299. $this->assertEmpty($left->tags);
  3300. }
  3301. /**
  3302. * Integration test to show how to replace records from a belongsToMany
  3303. *
  3304. * @return void
  3305. */
  3306. public function testReplacelinksBelongsToMany()
  3307. {
  3308. $table = TableRegistry::get('articles');
  3309. $table->belongsToMany('tags');
  3310. $tagsTable = TableRegistry::get('tags');
  3311. $options = ['markNew' => false];
  3312. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3313. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3314. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  3315. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  3316. $table->association('tags')->replaceLinks($article, $tags);
  3317. $this->assertEquals(2, $article->tags[0]->id);
  3318. $this->assertEquals(3, $article->tags[1]->id);
  3319. $this->assertEquals(4, $article->tags[2]->id);
  3320. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3321. $this->assertCount(3, $article->tags);
  3322. $this->assertEquals(2, $article->tags[0]->id);
  3323. $this->assertEquals(3, $article->tags[1]->id);
  3324. $this->assertEquals(4, $article->tags[2]->id);
  3325. $this->assertEquals('foo', $article->tags[2]->name);
  3326. }
  3327. /**
  3328. * Integration test to show how remove all links from a belongsToMany
  3329. *
  3330. * @return void
  3331. */
  3332. public function testReplacelinksBelongsToManyWithEmpty()
  3333. {
  3334. $table = TableRegistry::get('articles');
  3335. $table->belongsToMany('tags');
  3336. $tagsTable = TableRegistry::get('tags');
  3337. $options = ['markNew' => false];
  3338. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3339. $tags = [];
  3340. $table->association('tags')->replaceLinks($article, $tags);
  3341. $this->assertSame($tags, $article->tags);
  3342. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3343. $this->assertEmpty($article->tags);
  3344. }
  3345. /**
  3346. * Integration test to show how to replace records from a belongsToMany
  3347. * passing the joint property along in the target entity
  3348. *
  3349. * @return void
  3350. */
  3351. public function testReplacelinksBelongsToManyWithJoint()
  3352. {
  3353. $table = TableRegistry::get('articles');
  3354. $table->belongsToMany('tags');
  3355. $tagsTable = TableRegistry::get('tags');
  3356. $options = ['markNew' => false];
  3357. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3358. $tags[] = new \TestApp\Model\Entity\Tag([
  3359. 'id' => 2,
  3360. '_joinData' => new \Cake\ORM\Entity([
  3361. 'article_id' => 1,
  3362. 'tag_id' => 2,
  3363. ])
  3364. ], $options);
  3365. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  3366. $table->association('tags')->replaceLinks($article, $tags);
  3367. $this->assertSame($tags, $article->tags);
  3368. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3369. $this->assertCount(2, $article->tags);
  3370. $this->assertEquals(2, $article->tags[0]->id);
  3371. $this->assertEquals(3, $article->tags[1]->id);
  3372. }
  3373. /**
  3374. * Tests that it is possible to call find with no arguments
  3375. *
  3376. * @return void
  3377. */
  3378. public function testSimplifiedFind()
  3379. {
  3380. $table = $this->getMock(
  3381. '\Cake\ORM\Table',
  3382. ['callFinder'],
  3383. [[
  3384. 'connection' => $this->connection,
  3385. 'schema' => ['id' => ['type' => 'integer']]
  3386. ]]
  3387. );
  3388. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  3389. $table->expects($this->once())->method('callFinder')
  3390. ->with('all', $query, []);
  3391. $table->find();
  3392. }
  3393. public function providerForTestGet()
  3394. {
  3395. return [
  3396. [ ['fields' => ['id']] ],
  3397. [ ['fields' => ['id'], 'cache' => false] ]
  3398. ];
  3399. }
  3400. /**
  3401. * Test that get() will use the primary key for searching and return the first
  3402. * entity found
  3403. *
  3404. * @dataProvider providerForTestGet
  3405. * @param array $options
  3406. * @return void
  3407. */
  3408. public function testGet($options)
  3409. {
  3410. $table = $this->getMock(
  3411. '\Cake\ORM\Table',
  3412. ['callFinder', 'query'],
  3413. [[
  3414. 'connection' => $this->connection,
  3415. 'schema' => [
  3416. 'id' => ['type' => 'integer'],
  3417. 'bar' => ['type' => 'integer'],
  3418. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3419. ]
  3420. ]]
  3421. );
  3422. $query = $this->getMock(
  3423. '\Cake\ORM\Query',
  3424. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3425. [$this->connection, $table]
  3426. );
  3427. $entity = new \Cake\ORM\Entity;
  3428. $table->expects($this->once())->method('query')
  3429. ->will($this->returnValue($query));
  3430. $table->expects($this->once())->method('callFinder')
  3431. ->with('all', $query, ['fields' => ['id']])
  3432. ->will($this->returnValue($query));
  3433. $query->expects($this->once())->method('where')
  3434. ->with([$table->alias() . '.bar' => 10])
  3435. ->will($this->returnSelf());
  3436. $query->expects($this->never())->method('cache');
  3437. $query->expects($this->once())->method('firstOrFail')
  3438. ->will($this->returnValue($entity));
  3439. $result = $table->get(10, $options);
  3440. $this->assertSame($entity, $result);
  3441. }
  3442. public function providerForTestGetWithCustomFinder()
  3443. {
  3444. return [
  3445. [ ['fields' => ['id'], 'finder' => 'custom'] ]
  3446. ];
  3447. }
  3448. /**
  3449. * Test that get() will call a custom finder.
  3450. *
  3451. * @dataProvider providerForTestGetWithCustomFinder
  3452. * @param array $options
  3453. * @return void
  3454. */
  3455. public function testGetWithCustomFinder($options)
  3456. {
  3457. $table = $this->getMock(
  3458. '\Cake\ORM\Table',
  3459. ['callFinder', 'query'],
  3460. [[
  3461. 'connection' => $this->connection,
  3462. 'schema' => [
  3463. 'id' => ['type' => 'integer'],
  3464. 'bar' => ['type' => 'integer'],
  3465. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3466. ]
  3467. ]]
  3468. );
  3469. $query = $this->getMock(
  3470. '\Cake\ORM\Query',
  3471. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3472. [$this->connection, $table]
  3473. );
  3474. $entity = new \Cake\ORM\Entity;
  3475. $table->expects($this->once())->method('query')
  3476. ->will($this->returnValue($query));
  3477. $table->expects($this->once())->method('callFinder')
  3478. ->with('custom', $query, ['fields' => ['id']])
  3479. ->will($this->returnValue($query));
  3480. $query->expects($this->once())->method('where')
  3481. ->with([$table->alias() . '.bar' => 10])
  3482. ->will($this->returnSelf());
  3483. $query->expects($this->never())->method('cache');
  3484. $query->expects($this->once())->method('firstOrFail')
  3485. ->will($this->returnValue($entity));
  3486. $result = $table->get(10, $options);
  3487. $this->assertSame($entity, $result);
  3488. }
  3489. public function providerForTestGetWithCache()
  3490. {
  3491. return [
  3492. [
  3493. ['fields' => ['id'], 'cache' => 'default'],
  3494. 'get:test.table_name[10]', 'default'
  3495. ],
  3496. [
  3497. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  3498. 'custom_key', 'default'
  3499. ]
  3500. ];
  3501. }
  3502. /**
  3503. * Test that get() will use the cache.
  3504. *
  3505. * @dataProvider providerForTestGetWithCache
  3506. * @param array $options
  3507. * @param string $cacheKey
  3508. * @param string $cacheConfig
  3509. * @return void
  3510. */
  3511. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  3512. {
  3513. $table = $this->getMock(
  3514. '\Cake\ORM\Table',
  3515. ['callFinder', 'query'],
  3516. [[
  3517. 'connection' => $this->connection,
  3518. 'schema' => [
  3519. 'id' => ['type' => 'integer'],
  3520. 'bar' => ['type' => 'integer'],
  3521. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3522. ]
  3523. ]]
  3524. );
  3525. $table->table('table_name');
  3526. $query = $this->getMock(
  3527. '\Cake\ORM\Query',
  3528. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3529. [$this->connection, $table]
  3530. );
  3531. $entity = new \Cake\ORM\Entity;
  3532. $table->expects($this->once())->method('query')
  3533. ->will($this->returnValue($query));
  3534. $table->expects($this->once())->method('callFinder')
  3535. ->with('all', $query, ['fields' => ['id']])
  3536. ->will($this->returnValue($query));
  3537. $query->expects($this->once())->method('where')
  3538. ->with([$table->alias() . '.bar' => 10])
  3539. ->will($this->returnSelf());
  3540. $query->expects($this->once())->method('cache')
  3541. ->with($cacheKey, $cacheConfig)
  3542. ->will($this->returnSelf());
  3543. $query->expects($this->once())->method('firstOrFail')
  3544. ->will($this->returnValue($entity));
  3545. $result = $table->get(10, $options);
  3546. $this->assertSame($entity, $result);
  3547. }
  3548. /**
  3549. * Tests that get() will throw an exception if the record was not found
  3550. *
  3551. * @expectedException Cake\Datasource\Exception\RecordNotFoundException
  3552. * @expectedExceptionMessage Record not found in table "articles"
  3553. * @return void
  3554. */
  3555. public function testGetNotFoundException()
  3556. {
  3557. $table = new Table([
  3558. 'name' => 'Articles',
  3559. 'connection' => $this->connection,
  3560. 'table' => 'articles',
  3561. ]);
  3562. $table->get(10);
  3563. }
  3564. /**
  3565. * Test that an exception is raised when there are not enough keys.
  3566. *
  3567. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  3568. * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
  3569. * @return void
  3570. */
  3571. public function testGetExceptionOnNoData()
  3572. {
  3573. $table = new Table([
  3574. 'name' => 'Articles',
  3575. 'connection' => $this->connection,
  3576. 'table' => 'articles',
  3577. ]);
  3578. $table->get(null);
  3579. }
  3580. /**
  3581. * Test that an exception is raised when there are too many keys.
  3582. *
  3583. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  3584. * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
  3585. * @return void
  3586. */
  3587. public function testGetExceptionOnTooMuchData()
  3588. {
  3589. $table = new Table([
  3590. 'name' => 'Articles',
  3591. 'connection' => $this->connection,
  3592. 'table' => 'articles',
  3593. ]);
  3594. $table->get([1, 'two']);
  3595. }
  3596. /**
  3597. * Tests that patchEntity delegates the task to the marshaller and passed
  3598. * all associations
  3599. *
  3600. * @return void
  3601. */
  3602. public function testPatchEntity()
  3603. {
  3604. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3605. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3606. $table->belongsTo('users');
  3607. $table->hasMany('articles');
  3608. $table->expects($this->once())->method('marshaller')
  3609. ->will($this->returnValue($marshaller));
  3610. $entity = new \Cake\ORM\Entity;
  3611. $data = ['foo' => 'bar'];
  3612. $marshaller->expects($this->once())
  3613. ->method('merge')
  3614. ->with($entity, $data, ['associated' => ['users', 'articles']])
  3615. ->will($this->returnValue($entity));
  3616. $table->patchEntity($entity, $data);
  3617. }
  3618. /**
  3619. * Tests that patchEntities delegates the task to the marshaller and passed
  3620. * all associations
  3621. *
  3622. * @return void
  3623. */
  3624. public function testPatchEntities()
  3625. {
  3626. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3627. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3628. $table->belongsTo('users');
  3629. $table->hasMany('articles');
  3630. $table->expects($this->once())->method('marshaller')
  3631. ->will($this->returnValue($marshaller));
  3632. $entities = [new \Cake\ORM\Entity];
  3633. $data = [['foo' => 'bar']];
  3634. $marshaller->expects($this->once())
  3635. ->method('mergeMany')
  3636. ->with($entities, $data, ['associated' => ['users', 'articles']])
  3637. ->will($this->returnValue($entities));
  3638. $table->patchEntities($entities, $data);
  3639. }
  3640. /**
  3641. * Tests __debugInfo
  3642. *
  3643. * @return void
  3644. */
  3645. public function testDebugInfo()
  3646. {
  3647. $articles = TableRegistry::get('articles');
  3648. $articles->addBehavior('Timestamp');
  3649. $result = $articles->__debugInfo();
  3650. $expected = [
  3651. 'registryAlias' => 'articles',
  3652. 'table' => 'articles',
  3653. 'alias' => 'articles',
  3654. 'entityClass' => 'TestApp\Model\Entity\Article',
  3655. 'associations' => ['authors', 'tags', 'articlestags'],
  3656. 'behaviors' => ['Timestamp'],
  3657. 'defaultConnection' => 'default',
  3658. 'connectionName' => 'test'
  3659. ];
  3660. $this->assertEquals($expected, $result);
  3661. $articles = TableRegistry::get('Foo.Articles');
  3662. $result = $articles->__debugInfo();
  3663. $expected = [
  3664. 'registryAlias' => 'Foo.Articles',
  3665. 'table' => 'articles',
  3666. 'alias' => 'Articles',
  3667. 'entityClass' => '\Cake\ORM\Entity',
  3668. 'associations' => [],
  3669. 'behaviors' => [],
  3670. 'defaultConnection' => 'default',
  3671. 'connectionName' => 'test'
  3672. ];
  3673. $this->assertEquals($expected, $result);
  3674. }
  3675. /**
  3676. * Test the findOrCreate method.
  3677. *
  3678. * @return void
  3679. */
  3680. public function testFindOrCreate()
  3681. {
  3682. $articles = TableRegistry::get('Articles');
  3683. $article = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  3684. $article->body = 'New body';
  3685. });
  3686. $this->assertFalse($article->isNew());
  3687. $this->assertNotNull($article->id);
  3688. $this->assertEquals('Not there', $article->title);
  3689. $this->assertEquals('New body', $article->body);
  3690. $article = $articles->findOrCreate(['title' => 'Not there']);
  3691. $this->assertFalse($article->isNew());
  3692. $this->assertNotNull($article->id);
  3693. $this->assertEquals('Not there', $article->title);
  3694. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  3695. $this->fail('Should not be called for existing entities.');
  3696. });
  3697. $this->assertFalse($article->isNew());
  3698. $this->assertNotNull($article->id);
  3699. $this->assertEquals('First Article', $article->title);
  3700. $article = $articles->findOrCreate(
  3701. ['author_id' => 2, 'title' => 'First Article'],
  3702. function ($article) {
  3703. $article->set(['published' => 'N', 'body' => 'New body']);
  3704. }
  3705. );
  3706. $this->assertFalse($article->isNew());
  3707. $this->assertNotNull($article->id);
  3708. $this->assertEquals('First Article', $article->title);
  3709. $this->assertEquals('New body', $article->body);
  3710. $this->assertEquals('N', $article->published);
  3711. $this->assertEquals(2, $article->author_id);
  3712. }
  3713. /**
  3714. * Test that creating a table fires the initialize event.
  3715. *
  3716. * @return void
  3717. */
  3718. public function testInitializeEvent()
  3719. {
  3720. $count = 0;
  3721. $cb = function ($event) use (&$count) {
  3722. $count++;
  3723. };
  3724. EventManager::instance()->on('Model.initialize', $cb);
  3725. $articles = TableRegistry::get('Articles');
  3726. $this->assertEquals(1, $count, 'Callback should be called');
  3727. EventManager::instance()->detach($cb, 'Model.initialize');
  3728. }
  3729. /**
  3730. * Tests the hasFinder method
  3731. *
  3732. * @return void
  3733. */
  3734. public function testHasFinder()
  3735. {
  3736. $table = TableRegistry::get('articles');
  3737. $table->addBehavior('Sluggable');
  3738. $this->assertTrue($table->hasFinder('list'));
  3739. $this->assertTrue($table->hasFinder('noSlug'));
  3740. $this->assertFalse($table->hasFinder('noFind'));
  3741. }
  3742. /**
  3743. * Tests that calling validator() trigger the buildValidator event
  3744. *
  3745. * @return void
  3746. */
  3747. public function testBuildValidatorEvent()
  3748. {
  3749. $count = 0;
  3750. $cb = function ($event) use (&$count) {
  3751. $count++;
  3752. };
  3753. EventManager::instance()->on('Model.buildValidator', $cb);
  3754. $articles = TableRegistry::get('Articles');
  3755. $articles->validator();
  3756. $this->assertEquals(1, $count, 'Callback should be called');
  3757. $articles->validator();
  3758. $this->assertEquals(1, $count, 'Callback should be called only once');
  3759. }
  3760. /**
  3761. * Tests the validateUnique method with different combinations
  3762. *
  3763. * @return void
  3764. */
  3765. public function testValidateUnique()
  3766. {
  3767. $table = TableRegistry::get('Users');
  3768. $validator = new Validator;
  3769. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  3770. $validator->provider('table', $table);
  3771. $data = ['username' => 'larry'];
  3772. $this->assertNotEmpty($validator->errors($data));
  3773. $data = ['username' => 'jose'];
  3774. $this->assertEmpty($validator->errors($data));
  3775. $data = ['username' => 'larry', 'id' => 3];
  3776. $this->assertEmpty($validator->errors($data, false));
  3777. $data = ['username' => 'larry', 'id' => 3];
  3778. $this->assertNotEmpty($validator->errors($data));
  3779. $data = ['username' => 'larry'];
  3780. $this->assertNotEmpty($validator->errors($data, false));
  3781. $validator->add('username', 'unique', [
  3782. 'rule' => 'validateUnique', 'provider' => 'table'
  3783. ]);
  3784. $data = ['username' => 'larry'];
  3785. $this->assertNotEmpty($validator->errors($data, false));
  3786. }
  3787. /**
  3788. * Tests the validateUnique method with scope
  3789. *
  3790. * @return void
  3791. */
  3792. public function testValidateUniqueScope()
  3793. {
  3794. $table = TableRegistry::get('Users');
  3795. $validator = new Validator;
  3796. $validator->add('username', 'unique', [
  3797. 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']],
  3798. 'provider' => 'table'
  3799. ]);
  3800. $validator->provider('table', $table);
  3801. $data = ['username' => 'larry', 'id' => 3];
  3802. $this->assertNotEmpty($validator->errors($data));
  3803. $data = ['username' => 'larry', 'id' => 1];
  3804. $this->assertEmpty($validator->errors($data));
  3805. $data = ['username' => 'jose'];
  3806. $this->assertEmpty($validator->errors($data));
  3807. }
  3808. /**
  3809. * Tests that the callbacks receive the expected types of arguments.
  3810. *
  3811. * @return void
  3812. */
  3813. public function testCallbackArgumentTypes()
  3814. {
  3815. $table = TableRegistry::get('articles');
  3816. $table->belongsTo('authors');
  3817. $eventManager = $table->eventManager();
  3818. $associationBeforeFindCount = 0;
  3819. $table->association('authors')->target()->eventManager()->on(
  3820. 'Model.beforeFind',
  3821. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
  3822. $this->assertTrue(is_bool($primary));
  3823. $associationBeforeFindCount ++;
  3824. }
  3825. );
  3826. $beforeFindCount = 0;
  3827. $eventManager->on(
  3828. 'Model.beforeFind',
  3829. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
  3830. $this->assertTrue(is_bool($primary));
  3831. $beforeFindCount ++;
  3832. }
  3833. );
  3834. $table->find()->contain('authors')->first();
  3835. $this->assertEquals(1, $associationBeforeFindCount);
  3836. $this->assertEquals(1, $beforeFindCount);
  3837. $buildValidatorCount = 0;
  3838. $eventManager->on(
  3839. 'Model.buildValidator',
  3840. $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) {
  3841. $this->assertTrue(is_string($name));
  3842. $buildValidatorCount ++;
  3843. }
  3844. );
  3845. $table->validator();
  3846. $this->assertEquals(1, $buildValidatorCount);
  3847. $buildRulesCount =
  3848. $beforeRulesCount =
  3849. $afterRulesCount =
  3850. $beforeSaveCount =
  3851. $afterSaveCount = 0;
  3852. $eventManager->on(
  3853. 'Model.buildRules',
  3854. function (Event $event, RulesChecker $rules) use (&$buildRulesCount) {
  3855. $buildRulesCount ++;
  3856. }
  3857. );
  3858. $eventManager->on(
  3859. 'Model.beforeRules',
  3860. function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
  3861. $this->assertTrue(is_string($operation));
  3862. $beforeRulesCount ++;
  3863. }
  3864. );
  3865. $eventManager->on(
  3866. 'Model.afterRules',
  3867. function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
  3868. $this->assertTrue(is_bool($result));
  3869. $this->assertTrue(is_string($operation));
  3870. $afterRulesCount ++;
  3871. }
  3872. );
  3873. $eventManager->on(
  3874. 'Model.beforeSave',
  3875. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) {
  3876. $beforeSaveCount ++;
  3877. }
  3878. );
  3879. $eventManager->on(
  3880. 'Model.afterSave',
  3881. $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) {
  3882. $afterSaveCount ++;
  3883. }
  3884. );
  3885. $entity = new Entity(['title' => 'Title']);
  3886. $this->assertNotFalse($table->save($entity));
  3887. $this->assertEquals(1, $buildRulesCount);
  3888. $this->assertEquals(1, $beforeRulesCount);
  3889. $this->assertEquals(1, $afterRulesCount);
  3890. $this->assertEquals(1, $beforeSaveCount);
  3891. $this->assertEquals(1, $afterSaveCount);
  3892. $beforeDeleteCount =
  3893. $afterDeleteCount = 0;
  3894. $eventManager->on(
  3895. 'Model.beforeDelete',
  3896. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) {
  3897. $beforeDeleteCount ++;
  3898. }
  3899. );
  3900. $eventManager->on(
  3901. 'Model.afterDelete',
  3902. function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) {
  3903. $afterDeleteCount ++;
  3904. }
  3905. );
  3906. $this->assertTrue($table->delete($entity, ['checkRules' => false]));
  3907. $this->assertEquals(1, $beforeDeleteCount);
  3908. $this->assertEquals(1, $afterDeleteCount);
  3909. }
  3910. /**
  3911. * Tests that calling newEntity() on a table sets the right source alias
  3912. *
  3913. * @return void
  3914. */
  3915. public function testEntitySource()
  3916. {
  3917. $table = TableRegistry::get('Articles');
  3918. $this->assertEquals('Articles', $table->newEntity()->source());
  3919. Plugin::load('TestPlugin');
  3920. $table = TableRegistry::get('TestPlugin.Comments');
  3921. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source());
  3922. }
  3923. /**
  3924. * Tests that passing a coned entity that was marked as new to save() will
  3925. * actaully save it as a new entity
  3926. *
  3927. * @group save
  3928. * @return void
  3929. */
  3930. public function testSaveWithClonedEntity()
  3931. {
  3932. $table = TableRegistry::get('Articles');
  3933. $article = $table->get(1);
  3934. $cloned = clone $article;
  3935. $cloned->unsetProperty('id');
  3936. $cloned->isNew(true);
  3937. $this->assertSame($cloned, $table->save($cloned));
  3938. $this->assertEquals(
  3939. $article->extract(['title', 'author_id']),
  3940. $cloned->extract(['title', 'author_id'])
  3941. );
  3942. $this->assertEquals(4, $cloned->id);
  3943. }
  3944. /**
  3945. * Tests that the _ids notation can be used for HasMany
  3946. *
  3947. * @return void
  3948. */
  3949. public function testSaveHasManyWithIds()
  3950. {
  3951. $data = [
  3952. 'username' => 'lux',
  3953. 'password' => 'passphrase',
  3954. 'comments' => [
  3955. '_ids' => [1, 2]
  3956. ]
  3957. ];
  3958. $userTable = TableRegistry::get('Users');
  3959. $userTable->hasMany('Comments');
  3960. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  3961. $retrievedUser = $userTable->find('all')->where(['id' => $savedUser->id])->contain(['Comments'])->first();
  3962. $this->assertEquals($savedUser->comments[0]->user_id, $retrievedUser->comments[0]->user_id);
  3963. $this->assertEquals($savedUser->comments[1]->user_id, $retrievedUser->comments[1]->user_id);
  3964. }
  3965. /**
  3966. * Tests that on second save, entities for the has many relation are not marked
  3967. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  3968. * for a cleaner transaction log
  3969. *
  3970. * @return void
  3971. */
  3972. public function testSaveHasManyNoWasteSave()
  3973. {
  3974. $data = [
  3975. 'username' => 'lux',
  3976. 'password' => 'passphrase',
  3977. 'comments' => [
  3978. '_ids' => [1, 2]
  3979. ]
  3980. ];
  3981. $userTable = TableRegistry::get('Users');
  3982. $userTable->hasMany('Comments');
  3983. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  3984. $counter = 0;
  3985. $userTable->Comments
  3986. ->eventManager()
  3987. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  3988. if ($entity->dirty()) {
  3989. $counter++;
  3990. }
  3991. });
  3992. $savedUser->comments[] = $userTable->Comments->get(5);
  3993. $this->assertCount(3, $savedUser->comments);
  3994. $savedUser->dirty('comments', true);
  3995. $userTable->save($savedUser);
  3996. $this->assertEquals(1, $counter);
  3997. }
  3998. /**
  3999. * Tests that on second save, entities for the belongsToMany relation are not marked
  4000. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  4001. * for a cleaner transaction log
  4002. *
  4003. * @return void
  4004. */
  4005. public function testSaveBelongsToManyNoWasteSave()
  4006. {
  4007. $data = [
  4008. 'title' => 'foo',
  4009. 'body' => 'bar',
  4010. 'tags' => [
  4011. '_ids' => [1, 2]
  4012. ]
  4013. ];
  4014. $table = TableRegistry::get('Articles');
  4015. $table->belongsToMany('Tags');
  4016. $article = $table->save($table->newEntity($data, ['associated' => ['Tags']]));
  4017. $counter = 0;
  4018. $table->Tags->junction()
  4019. ->eventManager()
  4020. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  4021. if ($entity->dirty()) {
  4022. $counter++;
  4023. }
  4024. });
  4025. $article->tags[] = $table->Tags->get(3);
  4026. $this->assertCount(3, $article->tags);
  4027. $article->dirty('tags', true);
  4028. $table->save($article);
  4029. $this->assertEquals(1, $counter);
  4030. }
  4031. /**
  4032. * Tests that after saving then entity contains the right primary
  4033. * key casted to the right type
  4034. *
  4035. * @group save
  4036. * @return void
  4037. */
  4038. public function testSaveCorrectPrimaryKeyType()
  4039. {
  4040. $entity = new Entity([
  4041. 'username' => 'superuser',
  4042. 'created' => new Time('2013-10-10 00:00'),
  4043. 'updated' => new Time('2013-10-10 00:00')
  4044. ], ['markNew' => true]);
  4045. $table = TableRegistry::get('Users');
  4046. $this->assertSame($entity, $table->save($entity));
  4047. $this->assertSame(self::$nextUserId, $entity->id);
  4048. }
  4049. /**
  4050. * Helper method to skip tests when connection is SQLServer.
  4051. *
  4052. * @return void
  4053. */
  4054. public function skipIfSqlServer()
  4055. {
  4056. $this->skipIf(
  4057. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  4058. 'SQLServer does not support the requirements of this test.'
  4059. );
  4060. }
  4061. }