TableTest.php 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Core\Configure;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\ORM\Table;
  22. use Cake\ORM\TableRegistry;
  23. use Cake\Validation\Validator;
  24. use Cake\Utility\Time;
  25. /**
  26. * Used to test correct class is instantiated when using TableRegistry::get();
  27. */
  28. class UsersTable extends Table {
  29. }
  30. /**
  31. * Tests Table class
  32. *
  33. */
  34. class TableTest extends \Cake\TestSuite\TestCase {
  35. public $fixtures = [
  36. 'core.user', 'core.category', 'core.article', 'core.author',
  37. 'core.tag', 'core.articles_tag'
  38. ];
  39. /**
  40. * Handy variable containing the next primary key that will be inserted in the
  41. * users table
  42. *
  43. * @var int
  44. */
  45. public static $nextUserId = 5;
  46. public function setUp() {
  47. parent::setUp();
  48. $this->connection = ConnectionManager::get('test');
  49. Configure::write('App.namespace', 'TestApp');
  50. $this->usersTypeMap = new TypeMap([
  51. 'Users.id' => 'integer',
  52. 'id' => 'integer',
  53. 'Users.username' => 'string',
  54. 'username' => 'string',
  55. 'Users.password' => 'string',
  56. 'password' => 'string',
  57. 'Users.created' => 'timestamp',
  58. 'created' => 'timestamp',
  59. 'Users.updated' => 'timestamp',
  60. 'updated' => 'timestamp',
  61. ]);
  62. $this->articlesTypeMap = new TypeMap([
  63. 'Articles.id' => 'integer',
  64. 'id' => 'integer',
  65. 'Articles.title' => 'string',
  66. 'title' => 'string',
  67. 'Articles.author_id' => 'integer',
  68. 'author_id' => 'integer',
  69. 'Articles.body' => 'text',
  70. 'body' => 'text',
  71. 'Articles.published' => 'string',
  72. 'published' => 'string',
  73. ]);
  74. }
  75. public function tearDown() {
  76. parent::tearDown();
  77. TableRegistry::clear();
  78. }
  79. /**
  80. * Tests the table method
  81. *
  82. * @return void
  83. */
  84. public function testTableMethod() {
  85. $table = new Table(['table' => 'users']);
  86. $this->assertEquals('users', $table->table());
  87. $table = new UsersTable;
  88. $this->assertEquals('users', $table->table());
  89. $table = $this->getMockBuilder('\Cake\ORM\Table')
  90. ->setMethods(['find'])
  91. ->setMockClassName('SpecialThingsTable')
  92. ->getMock();
  93. $this->assertEquals('special_things', $table->table());
  94. $table = new Table(['alias' => 'LoveBoats']);
  95. $this->assertEquals('love_boats', $table->table());
  96. $table->table('other');
  97. $this->assertEquals('other', $table->table());
  98. }
  99. /**
  100. * Tests the alias method
  101. *
  102. * @return void
  103. */
  104. public function testAliasMethod() {
  105. $table = new Table(['alias' => 'users']);
  106. $this->assertEquals('users', $table->alias());
  107. $table = new Table(['table' => 'stuffs']);
  108. $this->assertEquals('stuffs', $table->alias());
  109. $table = new UsersTable;
  110. $this->assertEquals('Users', $table->alias());
  111. $table = $this->getMockBuilder('\Cake\ORM\Table')
  112. ->setMethods(['find'])
  113. ->setMockClassName('SpecialThingTable')
  114. ->getMock();
  115. $this->assertEquals('SpecialThing', $table->alias());
  116. $table->alias('AnotherOne');
  117. $this->assertEquals('AnotherOne', $table->alias());
  118. }
  119. /**
  120. * Tests connection method
  121. *
  122. * @return void
  123. */
  124. public function testConnection() {
  125. $table = new Table(['table' => 'users']);
  126. $this->assertNull($table->connection());
  127. $table->connection($this->connection);
  128. $this->assertSame($this->connection, $table->connection());
  129. }
  130. /**
  131. * Tests primaryKey method
  132. *
  133. * @return void
  134. */
  135. public function testPrimaryKey() {
  136. $table = new Table([
  137. 'table' => 'users',
  138. 'schema' => [
  139. 'id' => ['type' => 'integer'],
  140. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  141. ]
  142. ]);
  143. $this->assertEquals('id', $table->primaryKey());
  144. $table->primaryKey('thingID');
  145. $this->assertEquals('thingID', $table->primaryKey());
  146. $table->primaryKey(['thingID', 'user_id']);
  147. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  148. }
  149. /**
  150. * Tests that name will be selected as a displayField
  151. *
  152. * @return void
  153. */
  154. public function testDisplayFieldName() {
  155. $table = new Table([
  156. 'table' => 'users',
  157. 'schema' => [
  158. 'foo' => ['type' => 'string'],
  159. 'name' => ['type' => 'string']
  160. ]
  161. ]);
  162. $this->assertEquals('name', $table->displayField());
  163. }
  164. /**
  165. * Tests that title will be selected as a displayField
  166. *
  167. * @return void
  168. */
  169. public function testDisplayFieldTitle() {
  170. $table = new Table([
  171. 'table' => 'users',
  172. 'schema' => [
  173. 'foo' => ['type' => 'string'],
  174. 'title' => ['type' => 'string']
  175. ]
  176. ]);
  177. $this->assertEquals('title', $table->displayField());
  178. }
  179. /**
  180. * Tests that no displayField will fallback to primary key
  181. *
  182. * @return void
  183. */
  184. public function testDisplayFallback() {
  185. $table = new Table([
  186. 'table' => 'users',
  187. 'schema' => [
  188. 'id' => ['type' => 'string'],
  189. 'foo' => ['type' => 'string'],
  190. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  191. ]
  192. ]);
  193. $this->assertEquals('id', $table->displayField());
  194. }
  195. /**
  196. * Tests that displayField can be changed
  197. *
  198. * @return void
  199. */
  200. public function testDisplaySet() {
  201. $table = new Table([
  202. 'table' => 'users',
  203. 'schema' => [
  204. 'id' => ['type' => 'string'],
  205. 'foo' => ['type' => 'string'],
  206. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  207. ]
  208. ]);
  209. $this->assertEquals('id', $table->displayField());
  210. $table->displayField('foo');
  211. $this->assertEquals('foo', $table->displayField());
  212. }
  213. /**
  214. * Tests schema method
  215. *
  216. * @return void
  217. */
  218. public function testSchema() {
  219. $schema = $this->connection->schemaCollection()->describe('users');
  220. $table = new Table([
  221. 'table' => 'users',
  222. 'connection' => $this->connection,
  223. ]);
  224. $this->assertEquals($schema, $table->schema());
  225. $table = new Table(['table' => 'stuff']);
  226. $table->schema($schema);
  227. $this->assertSame($schema, $table->schema());
  228. $table = new Table(['table' => 'another']);
  229. $schema = ['id' => ['type' => 'integer']];
  230. $table->schema($schema);
  231. $this->assertEquals(
  232. new \Cake\Database\Schema\Table('another', $schema),
  233. $table->schema()
  234. );
  235. }
  236. /**
  237. * Tests that all fields for a table are added by default in a find when no
  238. * other fields are specified
  239. *
  240. * @return void
  241. */
  242. public function testFindAllNoFieldsAndNoHydration() {
  243. $table = new Table([
  244. 'table' => 'users',
  245. 'connection' => $this->connection,
  246. ]);
  247. $results = $table
  248. ->find('all')
  249. ->where(['id IN' => [1, 2]])
  250. ->order('id')
  251. ->hydrate(false)
  252. ->toArray();
  253. $expected = [
  254. [
  255. 'id' => 1,
  256. 'username' => 'mariano',
  257. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  258. 'created' => new Time('2007-03-17 01:16:23'),
  259. 'updated' => new Time('2007-03-17 01:18:31'),
  260. ],
  261. [
  262. 'id' => 2,
  263. 'username' => 'nate',
  264. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  265. 'created' => new Time('2008-03-17 01:18:23'),
  266. 'updated' => new Time('2008-03-17 01:20:31'),
  267. ],
  268. ];
  269. $this->assertEquals($expected, $results);
  270. }
  271. /**
  272. * Tests that it is possible to select only a few fields when finding over a table
  273. *
  274. * @return void
  275. */
  276. public function testFindAllSomeFieldsNoHydration() {
  277. $table = new Table([
  278. 'table' => 'users',
  279. 'connection' => $this->connection,
  280. ]);
  281. $results = $table->find('all')
  282. ->select(['username', 'password'])
  283. ->hydrate(false)
  284. ->order('username')->toArray();
  285. $expected = [
  286. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  287. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  288. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  289. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  290. ];
  291. $this->assertSame($expected, $results);
  292. $results = $table->find('all')
  293. ->select(['foo' => 'username', 'password'])
  294. ->order('username')
  295. ->hydrate(false)
  296. ->toArray();
  297. $expected = [
  298. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  299. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  300. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  301. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  302. ];
  303. $this->assertSame($expected, $results);
  304. }
  305. /**
  306. * Tests that the query will automatically casts complex conditions to the correct
  307. * types when the columns belong to the default table
  308. *
  309. * @return void
  310. */
  311. public function testFindAllConditionAutoTypes() {
  312. $table = new Table([
  313. 'table' => 'users',
  314. 'connection' => $this->connection,
  315. ]);
  316. $query = $table->find('all')
  317. ->select(['id', 'username'])
  318. ->where(['created >=' => new Time('2010-01-22 00:00')])
  319. ->hydrate(false)
  320. ->order('id');
  321. $expected = [
  322. ['id' => 3, 'username' => 'larry'],
  323. ['id' => 4, 'username' => 'garrett']
  324. ];
  325. $this->assertSame($expected, $query->toArray());
  326. $query->orWhere(['users.created' => new Time('2008-03-17 01:18:23')]);
  327. $expected = [
  328. ['id' => 2, 'username' => 'nate'],
  329. ['id' => 3, 'username' => 'larry'],
  330. ['id' => 4, 'username' => 'garrett']
  331. ];
  332. $this->assertSame($expected, $query->toArray());
  333. }
  334. /**
  335. * Test that beforeFind events can mutate the query.
  336. *
  337. * @return void
  338. */
  339. public function testFindBeforeFindEventMutateQuery() {
  340. $table = new Table([
  341. 'table' => 'users',
  342. 'connection' => $this->connection,
  343. ]);
  344. $table->getEventManager()->attach(function ($event, $query, $options) {
  345. $query->limit(1);
  346. }, 'Model.beforeFind');
  347. $result = $table->find('all')->all();
  348. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  349. }
  350. /**
  351. * Test that beforeFind events are fired and can stop the find and
  352. * return custom results.
  353. *
  354. * @return void
  355. */
  356. public function testFindBeforeFindEventOverrideReturn() {
  357. $table = new Table([
  358. 'table' => 'users',
  359. 'connection' => $this->connection,
  360. ]);
  361. $expected = ['One', 'Two', 'Three'];
  362. $table->getEventManager()->attach(function ($event, $query, $options) use ($expected) {
  363. $query->setResult($expected);
  364. $event->stopPropagation();
  365. }, 'Model.beforeFind');
  366. $query = $table->find('all');
  367. $query->limit(1);
  368. $this->assertEquals($expected, $query->all());
  369. }
  370. /**
  371. * Tests that belongsTo() creates and configures correctly the association
  372. *
  373. * @return void
  374. */
  375. public function testBelongsTo() {
  376. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  377. $table = new Table(['table' => 'dates']);
  378. $belongsTo = $table->belongsTo('user', $options);
  379. $this->assertInstanceOf('\Cake\ORM\Association\BelongsTo', $belongsTo);
  380. $this->assertSame($belongsTo, $table->association('user'));
  381. $this->assertEquals('user', $belongsTo->name());
  382. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  383. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  384. $this->assertSame($table, $belongsTo->source());
  385. }
  386. /**
  387. * Tests that hasOne() creates and configures correctly the association
  388. *
  389. * @return void
  390. */
  391. public function testHasOne() {
  392. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  393. $table = new Table(['table' => 'users']);
  394. $hasOne = $table->hasOne('profile', $options);
  395. $this->assertInstanceOf('\Cake\ORM\Association\HasOne', $hasOne);
  396. $this->assertSame($hasOne, $table->association('profile'));
  397. $this->assertEquals('profile', $hasOne->name());
  398. $this->assertEquals('user_id', $hasOne->foreignKey());
  399. $this->assertEquals(['b' => 'c'], $hasOne->conditions());
  400. $this->assertSame($table, $hasOne->source());
  401. }
  402. /**
  403. * Tests that hasMany() creates and configures correctly the association
  404. *
  405. * @return void
  406. */
  407. public function testHasMany() {
  408. $options = [
  409. 'foreignKey' => 'author_id',
  410. 'conditions' => ['b' => 'c'],
  411. 'sort' => ['foo' => 'asc']
  412. ];
  413. $table = new Table(['table' => 'authors']);
  414. $hasMany = $table->hasMany('article', $options);
  415. $this->assertInstanceOf('\Cake\ORM\Association\HasMany', $hasMany);
  416. $this->assertSame($hasMany, $table->association('article'));
  417. $this->assertEquals('article', $hasMany->name());
  418. $this->assertEquals('author_id', $hasMany->foreignKey());
  419. $this->assertEquals(['b' => 'c'], $hasMany->conditions());
  420. $this->assertEquals(['foo' => 'asc'], $hasMany->sort());
  421. $this->assertSame($table, $hasMany->source());
  422. }
  423. /**
  424. * Tests that BelongsToMany() creates and configures correctly the association
  425. *
  426. * @return void
  427. */
  428. public function testBelongsToMany() {
  429. $options = [
  430. 'foreignKey' => 'thing_id',
  431. 'joinTable' => 'things_tags',
  432. 'conditions' => ['b' => 'c'],
  433. 'sort' => ['foo' => 'asc']
  434. ];
  435. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  436. $belongsToMany = $table->belongsToMany('tag', $options);
  437. $this->assertInstanceOf('\Cake\ORM\Association\BelongsToMany', $belongsToMany);
  438. $this->assertSame($belongsToMany, $table->association('tag'));
  439. $this->assertEquals('tag', $belongsToMany->name());
  440. $this->assertEquals('thing_id', $belongsToMany->foreignKey());
  441. $this->assertEquals(['b' => 'c'], $belongsToMany->conditions());
  442. $this->assertEquals(['foo' => 'asc'], $belongsToMany->sort());
  443. $this->assertSame($table, $belongsToMany->source());
  444. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  445. }
  446. /**
  447. * Test basic multi row updates.
  448. *
  449. * @return void
  450. */
  451. public function testUpdateAll() {
  452. $table = new Table([
  453. 'table' => 'users',
  454. 'connection' => $this->connection,
  455. ]);
  456. $fields = ['username' => 'mark'];
  457. $result = $table->updateAll($fields, ['id <' => 4]);
  458. $this->assertTrue($result);
  459. $result = $table->find('all')
  460. ->select(['username'])
  461. ->order(['id' => 'asc'])
  462. ->hydrate(false)
  463. ->toArray();
  464. $expected = array_fill(0, 3, $fields);
  465. $expected[] = ['username' => 'garrett'];
  466. $this->assertEquals($expected, $result);
  467. }
  468. /**
  469. * Test that exceptions from the Query bubble up.
  470. *
  471. * @expectedException \Cake\Database\Exception
  472. */
  473. public function testUpdateAllFailure() {
  474. $table = $this->getMock(
  475. 'Cake\ORM\Table',
  476. ['query'],
  477. [['table' => 'users', 'connection' => $this->connection]]
  478. );
  479. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  480. $table->expects($this->once())
  481. ->method('query')
  482. ->will($this->returnValue($query));
  483. $query->expects($this->once())
  484. ->method('execute')
  485. ->will($this->throwException(new \Cake\Database\Exception('Not good')));
  486. $table->updateAll(['username' => 'mark'], []);
  487. }
  488. /**
  489. * Test deleting many records.
  490. *
  491. * @return void
  492. */
  493. public function testDeleteAll() {
  494. $table = new Table([
  495. 'table' => 'users',
  496. 'connection' => $this->connection,
  497. ]);
  498. $result = $table->deleteAll(['id <' => 4]);
  499. $this->assertTrue($result);
  500. $result = $table->find('all')->toArray();
  501. $this->assertCount(1, $result, 'Only one record should remain');
  502. $this->assertEquals(4, $result[0]['id']);
  503. }
  504. /**
  505. * Test that exceptions from the Query bubble up.
  506. *
  507. * @expectedException \Cake\Database\Exception
  508. */
  509. public function testDeleteAllFailure() {
  510. $table = $this->getMock(
  511. 'Cake\ORM\Table',
  512. ['query'],
  513. [['table' => 'users', 'connection' => $this->connection]]
  514. );
  515. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  516. $table->expects($this->once())
  517. ->method('query')
  518. ->will($this->returnValue($query));
  519. $query->expects($this->once())
  520. ->method('execute')
  521. ->will($this->throwException(new \Cake\Database\Exception('Not good')));
  522. $table->deleteAll(['id >' => 4]);
  523. }
  524. /**
  525. * Tests that array options are passed to the query object using applyOptions
  526. *
  527. * @return void
  528. */
  529. public function testFindApplyOptions() {
  530. $table = $this->getMock(
  531. 'Cake\ORM\Table',
  532. ['query', 'findAll'],
  533. [['table' => 'users', 'connection' => $this->connection]]
  534. );
  535. $query = $this->getMock('Cake\ORM\Query', [], [$this->connection, $table]);
  536. $table->expects($this->once())
  537. ->method('query')
  538. ->will($this->returnValue($query));
  539. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  540. $query->expects($this->any())
  541. ->method('select')
  542. ->will($this->returnSelf());
  543. $query->expects($this->once())->method('getOptions')
  544. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  545. $query->expects($this->once())
  546. ->method('applyOptions')
  547. ->with($options);
  548. $table->expects($this->once())->method('findAll')
  549. ->with($query, ['connections' => ['a >' => 1]]);
  550. $table->find('all', $options);
  551. }
  552. /**
  553. * Tests find('list')
  554. *
  555. * @return void
  556. */
  557. public function testFindListNoHydration() {
  558. $table = new Table([
  559. 'table' => 'users',
  560. 'connection' => $this->connection,
  561. ]);
  562. $table->displayField('username');
  563. $query = $table->find('list')
  564. ->hydrate(false)
  565. ->order('id');
  566. $expected = [
  567. 1 => 'mariano',
  568. 2 => 'nate',
  569. 3 => 'larry',
  570. 4 => 'garrett'
  571. ];
  572. $this->assertSame($expected, $query->toArray());
  573. $query = $table->find('list', ['fields' => ['id', 'username']])
  574. ->hydrate(false)
  575. ->order('id');
  576. $expected = [
  577. 1 => 'mariano',
  578. 2 => 'nate',
  579. 3 => 'larry',
  580. 4 => 'garrett'
  581. ];
  582. $this->assertSame($expected, $query->toArray());
  583. $query = $table->find('list', ['groupField' => 'odd'])
  584. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  585. ->hydrate(false)
  586. ->order('id');
  587. $expected = [
  588. 1 => [
  589. 1 => 'mariano',
  590. 3 => 'larry'
  591. ],
  592. 0 => [
  593. 2 => 'nate',
  594. 4 => 'garrett'
  595. ]
  596. ];
  597. $this->assertSame($expected, $query->toArray());
  598. }
  599. /**
  600. * Tests find('threaded')
  601. *
  602. * @return void
  603. */
  604. public function testFindThreadedNoHydration() {
  605. $table = new Table([
  606. 'table' => 'categories',
  607. 'connection' => $this->connection,
  608. ]);
  609. $expected = [
  610. [
  611. 'id' => 1,
  612. 'parent_id' => 0,
  613. 'name' => 'Category 1',
  614. 'children' => [
  615. [
  616. 'id' => 2,
  617. 'parent_id' => 1,
  618. 'name' => 'Category 1.1',
  619. 'children' => [
  620. [
  621. 'id' => 7,
  622. 'parent_id' => 2,
  623. 'name' => 'Category 1.1.1',
  624. 'children' => []
  625. ],
  626. [
  627. 'id' => 8,
  628. 'parent_id' => '2',
  629. 'name' => 'Category 1.1.2',
  630. 'children' => []
  631. ]
  632. ],
  633. ],
  634. [
  635. 'id' => 3,
  636. 'parent_id' => '1',
  637. 'name' => 'Category 1.2',
  638. 'children' => []
  639. ],
  640. ]
  641. ],
  642. [
  643. 'id' => 4,
  644. 'parent_id' => 0,
  645. 'name' => 'Category 2',
  646. 'children' => []
  647. ],
  648. [
  649. 'id' => 5,
  650. 'parent_id' => 0,
  651. 'name' => 'Category 3',
  652. 'children' => [
  653. [
  654. 'id' => '6',
  655. 'parent_id' => '5',
  656. 'name' => 'Category 3.1',
  657. 'children' => []
  658. ]
  659. ]
  660. ]
  661. ];
  662. $results = $table->find('all')
  663. ->select(['id', 'parent_id', 'name'])
  664. ->hydrate(false)
  665. ->find('threaded')
  666. ->toArray();
  667. $this->assertEquals($expected, $results);
  668. }
  669. /**
  670. * Tests that finders can be stacked
  671. *
  672. * @return void
  673. */
  674. public function testStackingFinders() {
  675. $table = $this->getMock('\Cake\ORM\Table', ['find', 'findList'], [], '', false);
  676. $params = [$this->connection, $table];
  677. $query = $this->getMock('\Cake\ORM\Query', ['addDefaultTypes'], $params);
  678. $table->expects($this->once())
  679. ->method('find')
  680. ->with('threaded', ['order' => ['name' => 'ASC']])
  681. ->will($this->returnValue($query));
  682. $table->expects($this->once())
  683. ->method('findList')
  684. ->with($query, ['keyPath' => 'id'])
  685. ->will($this->returnValue($query));
  686. $result = $table
  687. ->find('threaded', ['order' => ['name' => 'ASC']])
  688. ->find('list', ['keyPath' => 'id']);
  689. $this->assertSame($query, $result);
  690. }
  691. /**
  692. * Tests find('threaded') with hydrated results
  693. *
  694. * @return void
  695. */
  696. public function testFindThreadedHydrated() {
  697. $table = new Table([
  698. 'table' => 'categories',
  699. 'connection' => $this->connection,
  700. ]);
  701. $results = $table->find('all')
  702. ->find('threaded')
  703. ->select(['id', 'parent_id', 'name'])
  704. ->toArray();
  705. $this->assertEquals(1, $results[0]->id);
  706. $expected = [
  707. 'id' => 8,
  708. 'parent_id' => 2,
  709. 'name' => 'Category 1.1.2',
  710. 'children' => []
  711. ];
  712. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  713. }
  714. /**
  715. * Tests find('list') with hydrated records
  716. *
  717. * @return void
  718. */
  719. public function testFindListHydrated() {
  720. $table = new Table([
  721. 'table' => 'users',
  722. 'connection' => $this->connection,
  723. ]);
  724. $table->displayField('username');
  725. $query = $table
  726. ->find('list', ['fields' => ['id', 'username']])
  727. ->order('id');
  728. $expected = [
  729. 1 => 'mariano',
  730. 2 => 'nate',
  731. 3 => 'larry',
  732. 4 => 'garrett'
  733. ];
  734. $this->assertSame($expected, $query->toArray());
  735. $query = $table->find('list', ['groupField' => 'odd'])
  736. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  737. ->hydrate(true)
  738. ->order('id');
  739. $expected = [
  740. 1 => [
  741. 1 => 'mariano',
  742. 3 => 'larry'
  743. ],
  744. 0 => [
  745. 2 => 'nate',
  746. 4 => 'garrett'
  747. ]
  748. ];
  749. $this->assertSame($expected, $query->toArray());
  750. }
  751. /**
  752. * Test the default entityClass.
  753. *
  754. * @return void
  755. */
  756. public function testEntityClassDefault() {
  757. $table = new Table();
  758. $this->assertEquals('\Cake\ORM\Entity', $table->entityClass());
  759. }
  760. /**
  761. * Tests that using a simple string for entityClass will try to
  762. * load the class from the App namespace
  763. *
  764. * @return void
  765. */
  766. public function testTableClassInApp() {
  767. $class = $this->getMockClass('\Cake\ORM\Entity');
  768. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  769. class_alias($class, 'TestApp\Model\Entity\TestUser');
  770. }
  771. $table = new Table();
  772. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->entityClass('TestUser'));
  773. }
  774. /**
  775. * Tests that using a simple string for entityClass will try to
  776. * load the class from the Plugin namespace when using plugin notation
  777. *
  778. * @return void
  779. */
  780. public function testTableClassInPlugin() {
  781. $class = $this->getMockClass('\Cake\ORM\Entity');
  782. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  783. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  784. }
  785. $table = new Table();
  786. $this->assertEquals(
  787. 'MyPlugin\Model\Entity\SuperUser',
  788. $table->entityClass('MyPlugin.SuperUser')
  789. );
  790. }
  791. /**
  792. * Tests that using a simple string for entityClass will throw an exception
  793. * when the class does not exist in the namespace
  794. *
  795. * @expectedException \Cake\ORM\Error\MissingEntityException
  796. * @expectedExceptionMessage Entity class FooUser could not be found.
  797. * @return void
  798. */
  799. public function testTableClassNonExisting() {
  800. $table = new Table;
  801. $this->assertFalse($table->entityClass('FooUser'));
  802. }
  803. /**
  804. * Tests getting the entityClass based on conventions for the entity
  805. * namespace
  806. *
  807. * @return void
  808. */
  809. public function testTableClassConventionForAPP() {
  810. $table = new \TestApp\Model\Table\ArticlesTable;
  811. $this->assertEquals('TestApp\Model\Entity\Article', $table->entityClass());
  812. }
  813. /**
  814. * Tests setting a entity class object using the setter method
  815. *
  816. * @return void
  817. */
  818. public function testSetEntityClass() {
  819. $table = new Table;
  820. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  821. $table->entityClass($class);
  822. $this->assertEquals($class, $table->entityClass());
  823. }
  824. /**
  825. * Proves that associations, even though they are lazy loaded, will fetch
  826. * records using the correct table class and hydrate with the correct entity
  827. *
  828. * @return void
  829. */
  830. public function testReciprocalBelongsToLoading() {
  831. $table = new \TestApp\Model\Table\ArticlesTable([
  832. 'connection' => $this->connection,
  833. ]);
  834. $result = $table->find('all')->contain(['authors'])->first();
  835. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  836. }
  837. /**
  838. * Proves that associations, even though they are lazy loaded, will fetch
  839. * records using the correct table class and hydrate with the correct entity
  840. *
  841. * @return void
  842. */
  843. public function testReciprocalHasManyLoading() {
  844. $table = new \TestApp\Model\Table\ArticlesTable([
  845. 'connection' => $this->connection,
  846. ]);
  847. $result = $table->find('all')->contain(['authors' => ['articles']])->first();
  848. $this->assertCount(2, $result->author->articles);
  849. foreach ($result->author->articles as $article) {
  850. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  851. }
  852. }
  853. /**
  854. * Tests that the correct table and entity are loaded for the join association in
  855. * a belongsToMany setup
  856. *
  857. * @return void
  858. */
  859. public function testReciprocalBelongsToMany() {
  860. $table = new \TestApp\Model\Table\ArticlesTable([
  861. 'connection' => $this->connection,
  862. ]);
  863. $result = $table->find('all')->contain(['tags'])->first();
  864. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  865. $this->assertInstanceOf(
  866. 'TestApp\Model\Entity\ArticlesTag',
  867. $result->tags[0]->_joinData
  868. );
  869. }
  870. /**
  871. * Tests that recently fetched entities are always clean
  872. *
  873. * @return void
  874. */
  875. public function testFindCleanEntities() {
  876. $table = new \TestApp\Model\Table\ArticlesTable([
  877. 'connection' => $this->connection,
  878. ]);
  879. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  880. $this->assertCount(3, $results);
  881. foreach ($results as $article) {
  882. $this->assertFalse($article->dirty('id'));
  883. $this->assertFalse($article->dirty('title'));
  884. $this->assertFalse($article->dirty('author_id'));
  885. $this->assertFalse($article->dirty('body'));
  886. $this->assertFalse($article->dirty('published'));
  887. $this->assertFalse($article->dirty('author'));
  888. $this->assertFalse($article->author->dirty('id'));
  889. $this->assertFalse($article->author->dirty('name'));
  890. $this->assertFalse($article->dirty('tag'));
  891. if ($article->tag) {
  892. $this->assertFalse($article->tag[0]->_joinData->dirty('tag_id'));
  893. }
  894. }
  895. }
  896. /**
  897. * Tests that recently fetched entities are marked as not new
  898. *
  899. * @return void
  900. */
  901. public function testFindPersistedEntities() {
  902. $table = new \TestApp\Model\Table\ArticlesTable([
  903. 'connection' => $this->connection,
  904. ]);
  905. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  906. $this->assertCount(3, $results);
  907. foreach ($results as $article) {
  908. $this->assertFalse($article->isNew());
  909. foreach ((array)$article->tag as $tag) {
  910. $this->assertFalse($tag->isNew());
  911. $this->assertFalse($tag->_joinData->isNew());
  912. }
  913. }
  914. }
  915. /**
  916. * Tests the exists function
  917. *
  918. * @return void
  919. */
  920. public function testExists() {
  921. $table = TableRegistry::get('users');
  922. $this->assertTrue($table->exists(['id' => 1]));
  923. $this->assertFalse($table->exists(['id' => 501]));
  924. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  925. }
  926. /**
  927. * Test adding a behavior to a table.
  928. *
  929. * @return void
  930. */
  931. public function testAddBehavior() {
  932. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  933. $mock->expects($this->once())
  934. ->method('load')
  935. ->with('Sluggable');
  936. $table = new Table([
  937. 'table' => 'articles',
  938. 'behaviors' => $mock
  939. ]);
  940. $table->addBehavior('Sluggable');
  941. }
  942. /**
  943. * Ensure exceptions are raised on missing behaviors.
  944. *
  945. * @expectedException \Cake\ORM\Error\MissingBehaviorException
  946. */
  947. public function testAddBehaviorMissing() {
  948. $table = TableRegistry::get('article');
  949. $this->assertNull($table->addBehavior('NopeNotThere'));
  950. }
  951. /**
  952. * Test mixin methods from behaviors.
  953. *
  954. * @return void
  955. */
  956. public function testCallBehaviorMethod() {
  957. $table = TableRegistry::get('article');
  958. $table->addBehavior('Sluggable');
  959. $this->assertEquals('some_value', $table->slugify('some value'));
  960. }
  961. /**
  962. * Test you can alias a behavior method
  963. *
  964. * @return void
  965. */
  966. public function testCallBehaviorAliasedMethod() {
  967. $table = TableRegistry::get('article');
  968. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  969. $this->assertEquals('some_value', $table->wednesday('some value'));
  970. }
  971. /**
  972. * Test finder methods from behaviors.
  973. *
  974. * @return void
  975. */
  976. public function testCallBehaviorFinder() {
  977. $table = TableRegistry::get('articles');
  978. $table->addBehavior('Sluggable');
  979. $query = $table->find('noSlug');
  980. $this->assertInstanceOf('Cake\ORM\Query', $query);
  981. $this->assertNotEmpty($query->clause('where'));
  982. }
  983. /**
  984. * testCallBehaviorAliasedFinder
  985. *
  986. * @return void
  987. */
  988. public function testCallBehaviorAliasedFinder() {
  989. $table = TableRegistry::get('articles');
  990. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  991. $query = $table->find('special');
  992. $this->assertInstanceOf('Cake\ORM\Query', $query);
  993. $this->assertNotEmpty($query->clause('where'));
  994. }
  995. /**
  996. * Test implementedEvents
  997. *
  998. * @return void
  999. */
  1000. public function testImplementedEvents() {
  1001. $table = $this->getMock(
  1002. 'Cake\ORM\Table',
  1003. ['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete']
  1004. );
  1005. $result = $table->implementedEvents();
  1006. $expected = [
  1007. 'Model.beforeFind' => 'beforeFind',
  1008. 'Model.beforeSave' => 'beforeSave',
  1009. 'Model.afterSave' => 'afterSave',
  1010. 'Model.beforeDelete' => 'beforeDelete',
  1011. 'Model.afterDelete' => 'afterDelete',
  1012. ];
  1013. $this->assertEquals($expected, $result, 'Events do not match.');
  1014. }
  1015. /**
  1016. * Tests that it is possible to insert a new row using the save method
  1017. *
  1018. * @group save
  1019. * @return void
  1020. */
  1021. public function testSaveNewEntity() {
  1022. $entity = new \Cake\ORM\Entity([
  1023. 'username' => 'superuser',
  1024. 'password' => 'root',
  1025. 'created' => new Time('2013-10-10 00:00'),
  1026. 'updated' => new Time('2013-10-10 00:00')
  1027. ]);
  1028. $table = TableRegistry::get('users');
  1029. $this->assertSame($entity, $table->save($entity));
  1030. $this->assertEquals($entity->id, self::$nextUserId);
  1031. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1032. $this->assertEquals($entity->toArray(), $row->toArray());
  1033. }
  1034. /**
  1035. * Test that saving a new empty entity does nothing.
  1036. *
  1037. * @group save
  1038. * @return void
  1039. */
  1040. public function testSaveNewEmptyEntity() {
  1041. $entity = new \Cake\ORM\Entity();
  1042. $table = TableRegistry::get('users');
  1043. $this->assertFalse($table->save($entity));
  1044. }
  1045. /**
  1046. * Tests that saving an entity will filter out properties that
  1047. * are not present in the table schema when saving
  1048. *
  1049. * @group save
  1050. * @return void
  1051. */
  1052. public function testSaveEntityOnlySchemaFields() {
  1053. $entity = new \Cake\ORM\Entity([
  1054. 'username' => 'superuser',
  1055. 'password' => 'root',
  1056. 'crazyness' => 'super crazy value',
  1057. 'created' => new Time('2013-10-10 00:00'),
  1058. 'updated' => new Time('2013-10-10 00:00'),
  1059. ]);
  1060. $table = TableRegistry::get('users');
  1061. $this->assertSame($entity, $table->save($entity));
  1062. $this->assertEquals($entity->id, self::$nextUserId);
  1063. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1064. $entity->unsetProperty('crazyness');
  1065. $this->assertEquals($entity->toArray(), $row->toArray());
  1066. }
  1067. /**
  1068. * Tests that it is possible to modify data from the beforeSave callback
  1069. *
  1070. * @group save
  1071. * @return void
  1072. */
  1073. public function testBeforeSaveModifyData() {
  1074. $table = TableRegistry::get('users');
  1075. $data = new \Cake\ORM\Entity([
  1076. 'username' => 'superuser',
  1077. 'created' => new Time('2013-10-10 00:00'),
  1078. 'updated' => new Time('2013-10-10 00:00')
  1079. ]);
  1080. $listener = function($e, $entity, $options) use ($data) {
  1081. $this->assertSame($data, $entity);
  1082. $entity->set('password', 'foo');
  1083. };
  1084. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1085. $this->assertSame($data, $table->save($data));
  1086. $this->assertEquals($data->id, self::$nextUserId);
  1087. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1088. $this->assertEquals('foo', $row->get('password'));
  1089. }
  1090. /**
  1091. * Tests that it is possible to modify the options array in beforeSave
  1092. *
  1093. * @group save
  1094. * @return void
  1095. */
  1096. public function testBeforeSaveModifyOptions() {
  1097. $table = TableRegistry::get('users');
  1098. $data = new \Cake\ORM\Entity([
  1099. 'username' => 'superuser',
  1100. 'password' => 'foo',
  1101. 'created' => new Time('2013-10-10 00:00'),
  1102. 'updated' => new Time('2013-10-10 00:00')
  1103. ]);
  1104. $listener1 = function($e, $entity, $options) {
  1105. $options['crazy'] = true;
  1106. };
  1107. $listener2 = function($e, $entity, $options) {
  1108. $this->assertTrue($options['crazy']);
  1109. };
  1110. $table->getEventManager()->attach($listener1, 'Model.beforeSave');
  1111. $table->getEventManager()->attach($listener2, 'Model.beforeSave');
  1112. $this->assertSame($data, $table->save($data));
  1113. $this->assertEquals($data->id, self::$nextUserId);
  1114. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1115. $this->assertEquals($data->toArray(), $row->toArray());
  1116. }
  1117. /**
  1118. * Tests that it is possible to stop the saving altogether, without implying
  1119. * the save operation failed
  1120. *
  1121. * @group save
  1122. * @return void
  1123. */
  1124. public function testBeforeSaveStopEvent() {
  1125. $table = TableRegistry::get('users');
  1126. $data = new \Cake\ORM\Entity([
  1127. 'username' => 'superuser',
  1128. 'created' => new Time('2013-10-10 00:00'),
  1129. 'updated' => new Time('2013-10-10 00:00')
  1130. ]);
  1131. $listener = function($e, $entity) {
  1132. $e->stopPropagation();
  1133. return $entity;
  1134. };
  1135. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1136. $this->assertSame($data, $table->save($data));
  1137. $this->assertNull($data->id);
  1138. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1139. $this->assertNull($row);
  1140. }
  1141. /**
  1142. * Asserts that afterSave callback is called on successful save
  1143. *
  1144. * @group save
  1145. * @return void
  1146. */
  1147. public function testAfterSave() {
  1148. $table = TableRegistry::get('users');
  1149. $data = new \Cake\ORM\Entity([
  1150. 'username' => 'superuser',
  1151. 'created' => new Time('2013-10-10 00:00'),
  1152. 'updated' => new Time('2013-10-10 00:00')
  1153. ]);
  1154. $called = false;
  1155. $listener = function($e, $entity, $options) use ($data, &$called) {
  1156. $this->assertSame($data, $entity);
  1157. $called = true;
  1158. };
  1159. $table->getEventManager()->attach($listener, 'Model.afterSave');
  1160. $this->assertSame($data, $table->save($data));
  1161. $this->assertEquals($data->id, self::$nextUserId);
  1162. $this->assertTrue($called);
  1163. }
  1164. /**
  1165. * Asserts that afterSave callback not is called on unsuccessful save
  1166. *
  1167. * @group save
  1168. * @return void
  1169. */
  1170. public function testAfterSaveNotCalled() {
  1171. $table = $this->getMock(
  1172. '\Cake\ORM\Table',
  1173. ['query', 'exists'],
  1174. [['table' => 'users', 'connection' => $this->connection]]
  1175. );
  1176. $query = $this->getMock(
  1177. '\Cake\ORM\Query',
  1178. ['execute', 'addDefaultTypes'],
  1179. [null, $table]
  1180. );
  1181. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1182. $data = new \Cake\ORM\Entity([
  1183. 'username' => 'superuser',
  1184. 'created' => new Time('2013-10-10 00:00'),
  1185. 'updated' => new Time('2013-10-10 00:00')
  1186. ]);
  1187. $table->expects($this->once())->method('exists')
  1188. ->will($this->returnValue(false));
  1189. $table->expects($this->once())->method('query')
  1190. ->will($this->returnValue($query));
  1191. $query->expects($this->once())->method('execute')
  1192. ->will($this->returnValue($statement));
  1193. $statement->expects($this->once())->method('rowCount')
  1194. ->will($this->returnValue(0));
  1195. $called = false;
  1196. $listener = function($e, $entity, $options) use ($data, &$called) {
  1197. $called = true;
  1198. };
  1199. $table->getEventManager()->attach($listener, 'Model.afterSave');
  1200. $this->assertFalse($table->save($data));
  1201. $this->assertFalse($called);
  1202. }
  1203. /**
  1204. * Tests that save is wrapped around a transaction
  1205. *
  1206. * @group save
  1207. * @return void
  1208. */
  1209. public function testAtomicSave() {
  1210. $config = ConnectionManager::config('test');
  1211. $connection = $this->getMock(
  1212. '\Cake\Database\Connection',
  1213. ['begin', 'commit'],
  1214. [$config]
  1215. );
  1216. $connection->driver($this->connection->driver());
  1217. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  1218. $table->expects($this->any())->method('connection')
  1219. ->will($this->returnValue($connection));
  1220. $connection->expects($this->once())->method('begin');
  1221. $connection->expects($this->once())->method('commit');
  1222. $data = new \Cake\ORM\Entity([
  1223. 'username' => 'superuser',
  1224. 'created' => new Time('2013-10-10 00:00'),
  1225. 'updated' => new Time('2013-10-10 00:00')
  1226. ]);
  1227. $this->assertSame($data, $table->save($data));
  1228. }
  1229. /**
  1230. * Tests that save will rollback the transaction in the case of an exception
  1231. *
  1232. * @group save
  1233. * @expectedException \PDOException
  1234. * @return void
  1235. */
  1236. public function testAtomicSaveRollback() {
  1237. $connection = $this->getMock(
  1238. '\Cake\Database\Connection',
  1239. ['begin', 'rollback'],
  1240. [ConnectionManager::config('test')]
  1241. );
  1242. $connection->driver(ConnectionManager::get('test')->driver());
  1243. $table = $this->getMock(
  1244. '\Cake\ORM\Table',
  1245. ['query', 'connection', 'exists'],
  1246. [['table' => 'users']]
  1247. );
  1248. $query = $this->getMock(
  1249. '\Cake\ORM\Query',
  1250. ['execute', 'addDefaultTypes'],
  1251. [null, $table]
  1252. );
  1253. $table->expects($this->once())->method('exists')
  1254. ->will($this->returnValue(false));
  1255. $table->expects($this->any())->method('connection')
  1256. ->will($this->returnValue($connection));
  1257. $table->expects($this->once())->method('query')
  1258. ->will($this->returnValue($query));
  1259. $connection->expects($this->once())->method('begin');
  1260. $connection->expects($this->once())->method('rollback');
  1261. $query->expects($this->once())->method('execute')
  1262. ->will($this->throwException(new \PDOException));
  1263. $data = new \Cake\ORM\Entity([
  1264. 'username' => 'superuser',
  1265. 'created' => new Time('2013-10-10 00:00'),
  1266. 'updated' => new Time('2013-10-10 00:00')
  1267. ]);
  1268. $table->save($data);
  1269. }
  1270. /**
  1271. * Tests that save will rollback the transaction in the case of an exception
  1272. *
  1273. * @group save
  1274. * @return void
  1275. */
  1276. public function testAtomicSaveRollbackOnFailure() {
  1277. $connection = $this->getMock(
  1278. '\Cake\Database\Connection',
  1279. ['begin', 'rollback'],
  1280. [ConnectionManager::config('test')]
  1281. );
  1282. $connection->driver(ConnectionManager::get('test')->driver());
  1283. $table = $this->getMock(
  1284. '\Cake\ORM\Table',
  1285. ['query', 'connection', 'exists'],
  1286. [['table' => 'users']]
  1287. );
  1288. $query = $this->getMock(
  1289. '\Cake\ORM\Query',
  1290. ['execute', 'addDefaultTypes'],
  1291. [null, $table]
  1292. );
  1293. $table->expects($this->once())->method('exists')
  1294. ->will($this->returnValue(false));
  1295. $table->expects($this->any())->method('connection')
  1296. ->will($this->returnValue($connection));
  1297. $table->expects($this->once())->method('query')
  1298. ->will($this->returnValue($query));
  1299. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1300. $statement->expects($this->once())
  1301. ->method('rowCount')
  1302. ->will($this->returnValue(0));
  1303. $connection->expects($this->once())->method('begin');
  1304. $connection->expects($this->once())->method('rollback');
  1305. $query->expects($this->once())
  1306. ->method('execute')
  1307. ->will($this->returnValue($statement));
  1308. $data = new \Cake\ORM\Entity([
  1309. 'username' => 'superuser',
  1310. 'created' => new Time('2013-10-10 00:00'),
  1311. 'updated' => new Time('2013-10-10 00:00')
  1312. ]);
  1313. $table->save($data);
  1314. }
  1315. /**
  1316. * Tests that only the properties marked as dirty are actually saved
  1317. * to the database
  1318. *
  1319. * @group save
  1320. * @return void
  1321. */
  1322. public function testSaveOnlyDirtyProperties() {
  1323. $entity = new \Cake\ORM\Entity([
  1324. 'username' => 'superuser',
  1325. 'password' => 'root',
  1326. 'created' => new Time('2013-10-10 00:00'),
  1327. 'updated' => new Time('2013-10-10 00:00')
  1328. ]);
  1329. $entity->clean();
  1330. $entity->dirty('username', true);
  1331. $entity->dirty('created', true);
  1332. $entity->dirty('updated', true);
  1333. $table = TableRegistry::get('users');
  1334. $this->assertSame($entity, $table->save($entity));
  1335. $this->assertEquals($entity->id, self::$nextUserId);
  1336. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1337. $entity->set('password', null);
  1338. $this->assertEquals($entity->toArray(), $row->toArray());
  1339. }
  1340. /**
  1341. * Tests that a recently saved entity is marked as clean
  1342. *
  1343. * @group save
  1344. * @return void
  1345. */
  1346. public function testsASavedEntityIsClean() {
  1347. $entity = new \Cake\ORM\Entity([
  1348. 'username' => 'superuser',
  1349. 'password' => 'root',
  1350. 'created' => new Time('2013-10-10 00:00'),
  1351. 'updated' => new Time('2013-10-10 00:00')
  1352. ]);
  1353. $table = TableRegistry::get('users');
  1354. $this->assertSame($entity, $table->save($entity));
  1355. $this->assertFalse($entity->dirty('usermane'));
  1356. $this->assertFalse($entity->dirty('password'));
  1357. $this->assertFalse($entity->dirty('created'));
  1358. $this->assertFalse($entity->dirty('updated'));
  1359. }
  1360. /**
  1361. * Tests that a recently saved entity is marked as not new
  1362. *
  1363. * @group save
  1364. * @return void
  1365. */
  1366. public function testsASavedEntityIsNotNew() {
  1367. $entity = new \Cake\ORM\Entity([
  1368. 'username' => 'superuser',
  1369. 'password' => 'root',
  1370. 'created' => new Time('2013-10-10 00:00'),
  1371. 'updated' => new Time('2013-10-10 00:00')
  1372. ]);
  1373. $table = TableRegistry::get('users');
  1374. $this->assertSame($entity, $table->save($entity));
  1375. $this->assertFalse($entity->isNew());
  1376. }
  1377. /**
  1378. * Tests that save can detect automatically if it needs to insert
  1379. * or update a row
  1380. *
  1381. * @group save
  1382. * @return void
  1383. */
  1384. public function testSaveUpdateAuto() {
  1385. $entity = new \Cake\ORM\Entity([
  1386. 'id' => 2,
  1387. 'username' => 'baggins'
  1388. ]);
  1389. $table = TableRegistry::get('users');
  1390. $original = $table->find('all')->where(['id' => 2])->first();
  1391. $this->assertSame($entity, $table->save($entity));
  1392. $row = $table->find('all')->where(['id' => 2])->first();
  1393. $this->assertEquals('baggins', $row->username);
  1394. $this->assertEquals($original->password, $row->password);
  1395. $this->assertEquals($original->created, $row->created);
  1396. $this->assertEquals($original->updated, $row->updated);
  1397. $this->assertFalse($entity->isNew());
  1398. $this->assertFalse($entity->dirty('id'));
  1399. $this->assertFalse($entity->dirty('username'));
  1400. }
  1401. /**
  1402. * Tests that beforeFind gets the correct isNew() state for the entity
  1403. *
  1404. * @return void
  1405. */
  1406. public function testBeforeSaveGetsCorrectPersistance() {
  1407. $entity = new \Cake\ORM\Entity([
  1408. 'id' => 2,
  1409. 'username' => 'baggins'
  1410. ]);
  1411. $table = TableRegistry::get('users');
  1412. $called = false;
  1413. $listener = function($event, $entity) use (&$called) {
  1414. $this->assertFalse($entity->isNew());
  1415. $called = true;
  1416. };
  1417. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1418. $this->assertSame($entity, $table->save($entity));
  1419. $this->assertTrue($called);
  1420. }
  1421. /**
  1422. * Tests that marking an entity as already persisted will prevent the save
  1423. * method from trying to infer the entity's actual status.
  1424. *
  1425. * @group save
  1426. * @return void
  1427. */
  1428. public function testSaveUpdateWithHint() {
  1429. $table = $this->getMock(
  1430. '\Cake\ORM\Table',
  1431. ['exists'],
  1432. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  1433. );
  1434. $entity = new \Cake\ORM\Entity([
  1435. 'id' => 2,
  1436. 'username' => 'baggins'
  1437. ], ['markNew' => false]);
  1438. $this->assertFalse($entity->isNew());
  1439. $table->expects($this->never())->method('exists');
  1440. $this->assertSame($entity, $table->save($entity));
  1441. }
  1442. /**
  1443. * Tests that when updating the primary key is not passed to the list of
  1444. * attributes to change
  1445. *
  1446. * @group save
  1447. * @return void
  1448. */
  1449. public function testSaveUpdatePrimaryKeyNotModified() {
  1450. $table = $this->getMock(
  1451. '\Cake\ORM\Table',
  1452. ['query'],
  1453. [['table' => 'users', 'connection' => $this->connection]]
  1454. );
  1455. $query = $this->getMock(
  1456. '\Cake\ORM\Query',
  1457. ['execute', 'addDefaultTypes', 'set'],
  1458. [null, $table]
  1459. );
  1460. $table->expects($this->once())->method('query')
  1461. ->will($this->returnValue($query));
  1462. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1463. $statement->expects($this->once())
  1464. ->method('errorCode')
  1465. ->will($this->returnValue('00000'));
  1466. $query->expects($this->once())
  1467. ->method('execute')
  1468. ->will($this->returnValue($statement));
  1469. $query->expects($this->once())->method('set')
  1470. ->with(['username' => 'baggins'])
  1471. ->will($this->returnValue($query));
  1472. $entity = new \Cake\ORM\Entity([
  1473. 'id' => 2,
  1474. 'username' => 'baggins'
  1475. ], ['markNew' => false]);
  1476. $this->assertSame($entity, $table->save($entity));
  1477. }
  1478. /**
  1479. * Tests that passing only the primary key to save will not execute any queries
  1480. * but still return success
  1481. *
  1482. * @group save
  1483. * @return void
  1484. */
  1485. public function testUpdateNoChange() {
  1486. $table = $this->getMock(
  1487. '\Cake\ORM\Table',
  1488. ['query'],
  1489. [['table' => 'users', 'connection' => $this->connection]]
  1490. );
  1491. $table->expects($this->never())->method('query');
  1492. $entity = new \Cake\ORM\Entity([
  1493. 'id' => 2,
  1494. ], ['markNew' => false]);
  1495. $this->assertSame($entity, $table->save($entity));
  1496. }
  1497. /**
  1498. * Tests that passing only the primary key to save will not execute any queries
  1499. * but still return success
  1500. *
  1501. * @group save
  1502. * @group integration
  1503. * @return void
  1504. */
  1505. public function testUpdateDirtyNoActualChanges() {
  1506. $table = TableRegistry::get('Articles');
  1507. $entity = $table->get(1);
  1508. $entity->accessible('*', true);
  1509. $entity->set($entity->toArray());
  1510. $this->assertSame($entity, $table->save($entity));
  1511. }
  1512. /**
  1513. * Tests that failing to pass a primary key to save will result in exception
  1514. *
  1515. * @group save
  1516. * @expectedException \InvalidArgumentException
  1517. * @return void
  1518. */
  1519. public function testUpdateNoPrimaryButOtherKeys() {
  1520. $table = $this->getMock(
  1521. '\Cake\ORM\Table',
  1522. ['query'],
  1523. [['table' => 'users', 'connection' => $this->connection]]
  1524. );
  1525. $table->expects($this->never())->method('query');
  1526. $entity = new \Cake\ORM\Entity([
  1527. 'username' => 'mariano',
  1528. ], ['markNew' => false]);
  1529. $this->assertSame($entity, $table->save($entity));
  1530. }
  1531. /**
  1532. * Test simple delete.
  1533. *
  1534. * @return void
  1535. */
  1536. public function testDelete() {
  1537. $table = TableRegistry::get('users');
  1538. $conditions = [
  1539. 'limit' => 1,
  1540. 'conditions' => [
  1541. 'username' => 'nate'
  1542. ]
  1543. ];
  1544. $query = $table->find('all', $conditions);
  1545. $entity = $query->first();
  1546. $result = $table->delete($entity);
  1547. $this->assertTrue($result);
  1548. $query = $table->find('all', $conditions);
  1549. $results = $query->execute();
  1550. $this->assertCount(0, $results, 'Find should fail.');
  1551. }
  1552. /**
  1553. * Test delete with dependent records
  1554. *
  1555. * @return void
  1556. */
  1557. public function testDeleteDependent() {
  1558. $table = TableRegistry::get('authors');
  1559. $table->hasOne('articles', [
  1560. 'foreignKey' => 'author_id',
  1561. 'dependent' => true,
  1562. ]);
  1563. $query = $table->find('all')->where(['id' => 1]);
  1564. $entity = $query->first();
  1565. $result = $table->delete($entity);
  1566. $articles = $table->association('articles')->target();
  1567. $query = $articles->find('all', [
  1568. 'conditions' => [
  1569. 'author_id' => $entity->id
  1570. ]
  1571. ]);
  1572. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1573. }
  1574. /**
  1575. * Test delete with dependent = false does not cascade.
  1576. *
  1577. * @return void
  1578. */
  1579. public function testDeleteNoDependentNoCascade() {
  1580. $table = TableRegistry::get('authors');
  1581. $table->hasMany('article', [
  1582. 'foreignKey' => 'author_id',
  1583. 'dependent' => false,
  1584. ]);
  1585. $query = $table->find('all')->where(['id' => 1]);
  1586. $entity = $query->first();
  1587. $result = $table->delete($entity);
  1588. $articles = $table->association('articles')->target();
  1589. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  1590. $this->assertCount(2, $query->execute(), 'Should find rows.');
  1591. }
  1592. /**
  1593. * Test delete with BelongsToMany
  1594. *
  1595. * @return void
  1596. */
  1597. public function testDeleteBelongsToMany() {
  1598. $table = TableRegistry::get('articles');
  1599. $table->belongsToMany('tag', [
  1600. 'foreignKey' => 'article_id',
  1601. 'joinTable' => 'articles_tags'
  1602. ]);
  1603. $query = $table->find('all')->where(['id' => 1]);
  1604. $entity = $query->first();
  1605. $table->delete($entity);
  1606. $junction = $table->association('tags')->junction();
  1607. $query = $junction->find('all')->where(['article_id' => 1]);
  1608. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1609. }
  1610. /**
  1611. * Test delete callbacks
  1612. *
  1613. * @return void
  1614. */
  1615. public function testDeleteCallbacks() {
  1616. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1617. $options = new \ArrayObject(['atomic' => true]);
  1618. $mock = $this->getMock('Cake\Event\EventManager');
  1619. $mock->expects($this->at(0))
  1620. ->method('attach');
  1621. $mock->expects($this->at(1))
  1622. ->method('dispatch')
  1623. ->with($this->logicalAnd(
  1624. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  1625. $this->attributeEqualTo(
  1626. 'data',
  1627. ['entity' => $entity, 'options' => $options]
  1628. )
  1629. ));
  1630. $mock->expects($this->at(2))
  1631. ->method('dispatch')
  1632. ->with($this->logicalAnd(
  1633. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  1634. $this->attributeEqualTo(
  1635. 'data',
  1636. ['entity' => $entity, 'options' => $options]
  1637. )
  1638. ));
  1639. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1640. $entity->isNew(false);
  1641. $table->delete($entity);
  1642. }
  1643. /**
  1644. * Test delete beforeDelete can abort the delete.
  1645. *
  1646. * @return void
  1647. */
  1648. public function testDeleteBeforeDeleteAbort() {
  1649. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1650. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1651. $mock = $this->getMock('Cake\Event\EventManager');
  1652. $mock->expects($this->once())
  1653. ->method('dispatch')
  1654. ->will($this->returnCallback(function($event) {
  1655. $event->stopPropagation();
  1656. }));
  1657. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1658. $entity->isNew(false);
  1659. $result = $table->delete($entity);
  1660. $this->assertNull($result);
  1661. }
  1662. /**
  1663. * Test delete beforeDelete return result
  1664. *
  1665. * @return void
  1666. */
  1667. public function testDeleteBeforeDeleteReturnResult() {
  1668. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1669. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1670. $mock = $this->getMock('Cake\Event\EventManager');
  1671. $mock->expects($this->once())
  1672. ->method('dispatch')
  1673. ->will($this->returnCallback(function($event) {
  1674. $event->stopPropagation();
  1675. $event->result = 'got stopped';
  1676. }));
  1677. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1678. $entity->isNew(false);
  1679. $result = $table->delete($entity);
  1680. $this->assertEquals('got stopped', $result);
  1681. }
  1682. /**
  1683. * Test deleting new entities does nothing.
  1684. *
  1685. * @return void
  1686. */
  1687. public function testDeleteIsNew() {
  1688. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1689. $table = $this->getMock(
  1690. 'Cake\ORM\Table',
  1691. ['query'],
  1692. [['connection' => $this->connection]]
  1693. );
  1694. $table->expects($this->never())
  1695. ->method('query');
  1696. $entity->isNew(true);
  1697. $result = $table->delete($entity);
  1698. $this->assertFalse($result);
  1699. }
  1700. /**
  1701. * test hasField()
  1702. *
  1703. * @return void
  1704. */
  1705. public function testHasField() {
  1706. $table = TableRegistry::get('articles');
  1707. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  1708. $this->assertTrue($table->hasField('title'), 'Should be there.');
  1709. $this->assertTrue($table->hasField('body'), 'Should be there.');
  1710. }
  1711. /**
  1712. * Tests that there exists a default validator
  1713. *
  1714. * @return void
  1715. */
  1716. public function testValidatorDefault() {
  1717. $table = new Table();
  1718. $validator = $table->validator();
  1719. $this->assertSame($table, $validator->provider('table'));
  1720. $this->assertInstanceOf('\Cake\Validation\Validator', $validator);
  1721. $default = $table->validator('default');
  1722. $this->assertSame($validator, $default);
  1723. }
  1724. /**
  1725. * Tests that it is possible to define custom validator methods
  1726. *
  1727. * @return void
  1728. */
  1729. public function functionTestValidationWithDefiner() {
  1730. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  1731. $table->expects($this->once())->method('validationForOtherStuff')
  1732. ->will($this->returnArgument(0));
  1733. $other = $table->validator('forOtherStuff');
  1734. $this->assertInstanceOf('\Cake\Validation\Validator', $other);
  1735. $this->assertNotSame($other, $table->validator());
  1736. $this->assertSame($table, $other->provider('table'));
  1737. }
  1738. /**
  1739. * Tests that it is possible to set a custom validator under a name
  1740. *
  1741. * @return void
  1742. */
  1743. public function testValidatorSetter() {
  1744. $table = new Table;
  1745. $validator = new \Cake\Validation\Validator;
  1746. $table->validator('other', $validator);
  1747. $this->assertSame($validator, $table->validator('other'));
  1748. $this->assertSame($table, $validator->provider('table'));
  1749. }
  1750. /**
  1751. * Tests saving with validation
  1752. *
  1753. * @return void
  1754. */
  1755. public function testSaveWithValidationError() {
  1756. $entity = new \Cake\ORM\Entity([
  1757. 'username' => 'superuser'
  1758. ]);
  1759. $table = TableRegistry::get('users');
  1760. $table->validator()->validatePresence('password');
  1761. $this->assertFalse($table->save($entity));
  1762. $this->assertNotEmpty($entity->errors('password'));
  1763. $this->assertSame($entity, $table->validator()->provider('entity'));
  1764. $this->assertSame($table, $table->validator()->provider('table'));
  1765. }
  1766. /**
  1767. * Tests saving with validation and field list
  1768. *
  1769. * @return void
  1770. */
  1771. public function testSaveWithValidationErrorAndFieldList() {
  1772. $entity = new \Cake\ORM\Entity([
  1773. 'username' => 'superuser'
  1774. ]);
  1775. $table = TableRegistry::get('users');
  1776. $table->validator()->validatePresence('password');
  1777. $this->assertFalse($table->save($entity));
  1778. $this->assertNotEmpty($entity->errors('password'));
  1779. }
  1780. /**
  1781. * Tests using a custom validation object when saving
  1782. *
  1783. * @return void
  1784. */
  1785. public function testSaveWithDifferentValidator() {
  1786. $entity = new \Cake\ORM\Entity([
  1787. 'username' => 'superuser'
  1788. ]);
  1789. $table = TableRegistry::get('users');
  1790. $validator = (new Validator)->validatePresence('password');
  1791. $table->validator('custom', $validator);
  1792. $this->assertFalse($table->save($entity, ['validate' => 'custom']));
  1793. $this->assertNotEmpty($entity->errors('password'));
  1794. $this->assertSame($entity, $table->save($entity), 'default was not used');
  1795. }
  1796. /**
  1797. * Tests saving with successful validation
  1798. *
  1799. * @return void
  1800. */
  1801. public function testSaveWithValidationSuccess() {
  1802. $entity = new \Cake\ORM\Entity([
  1803. 'username' => 'superuser',
  1804. 'password' => 'hey'
  1805. ]);
  1806. $table = TableRegistry::get('users');
  1807. $table->validator()->validatePresence('password');
  1808. $this->assertSame($entity, $table->save($entity));
  1809. $this->assertEmpty($entity->errors('password'));
  1810. }
  1811. /**
  1812. * Tests beforeValidate event is triggered
  1813. *
  1814. * @return void
  1815. */
  1816. public function testBeforeValidate() {
  1817. $entity = new \Cake\ORM\Entity([
  1818. 'username' => 'superuser'
  1819. ]);
  1820. $table = TableRegistry::get('users');
  1821. $table->getEventManager()->attach(function($ev, $en, $opt, $val) use ($entity) {
  1822. $this->assertSame($entity, $en);
  1823. $this->assertTrue($opt['crazy']);
  1824. $this->assertSame($ev->subject()->validator('default'), $val);
  1825. $val->validatePresence('password');
  1826. }, 'Model.beforeValidate');
  1827. $this->assertFalse($table->save($entity, ['crazy' => true]));
  1828. $this->assertNotEmpty($entity->errors('password'));
  1829. }
  1830. /**
  1831. * Tests that beforeValidate can set the validation result
  1832. *
  1833. * @return void
  1834. */
  1835. public function testBeforeValidateSetResult() {
  1836. $entity = new \Cake\ORM\Entity([
  1837. 'username' => 'superuser'
  1838. ]);
  1839. $table = TableRegistry::get('users');
  1840. $table->getEventManager()->attach(function($ev, $en) {
  1841. $en->errors('username', 'Not good');
  1842. return false;
  1843. }, 'Model.beforeValidate');
  1844. $this->assertFalse($table->save($entity));
  1845. $this->assertEquals(['Not good'], $entity->errors('username'));
  1846. }
  1847. /**
  1848. * Tests that afterValidate is triggered and can set a result
  1849. *
  1850. * @return void
  1851. */
  1852. public function testAfterValidate() {
  1853. $entity = new \Cake\ORM\Entity([
  1854. 'username' => 'superuser',
  1855. 'password' => 'hey'
  1856. ]);
  1857. $table = TableRegistry::get('users');
  1858. $table->validator()->validatePresence('password');
  1859. $table->getEventManager()->attach(function($ev, $en, $opt, $val) use ($entity) {
  1860. $this->assertSame($entity, $en);
  1861. $this->assertTrue($opt['crazy']);
  1862. $this->assertSame($ev->subject()->validator('default'), $val);
  1863. $en->errors('username', 'Not good');
  1864. return false;
  1865. }, 'Model.afterValidate');
  1866. $this->assertFalse($table->save($entity, ['crazy' => true]));
  1867. $this->assertEmpty($entity->errors('password'));
  1868. $this->assertEquals(['Not good'], $entity->errors('username'));
  1869. }
  1870. /**
  1871. * Test magic findByXX method.
  1872. *
  1873. * @return void
  1874. */
  1875. public function testMagicFindDefaultToAll() {
  1876. $table = TableRegistry::get('Users');
  1877. $result = $table->findByUsername('garrett');
  1878. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1879. $expected = new QueryExpression(['username' => 'garrett'], $this->usersTypeMap);
  1880. $this->assertEquals($expected, $result->clause('where'));
  1881. }
  1882. /**
  1883. * Test magic findByXX errors on missing arguments.
  1884. *
  1885. * @expectedException \Cake\Error\Exception
  1886. * @expectedExceptionMessage Not enough arguments to magic finder. Got 0 required 1
  1887. * @return void
  1888. */
  1889. public function testMagicFindError() {
  1890. $table = TableRegistry::get('Users');
  1891. $table->findByUsername();
  1892. }
  1893. /**
  1894. * Test magic findByXX errors on missing arguments.
  1895. *
  1896. * @expectedException \Cake\Error\Exception
  1897. * @expectedExceptionMessage Not enough arguments to magic finder. Got 1 required 2
  1898. * @return void
  1899. */
  1900. public function testMagicFindErrorMissingField() {
  1901. $table = TableRegistry::get('Users');
  1902. $table->findByUsernameAndId('garrett');
  1903. }
  1904. /**
  1905. * Test magic findByXX errors when there is a mix of or & and.
  1906. *
  1907. * @expectedException \Cake\Error\Exception
  1908. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  1909. * @return void
  1910. */
  1911. public function testMagicFindErrorMixOfOperators() {
  1912. $table = TableRegistry::get('Users');
  1913. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  1914. }
  1915. /**
  1916. * Test magic findByXX method.
  1917. *
  1918. * @return void
  1919. */
  1920. public function testMagicFindFirstAnd() {
  1921. $table = TableRegistry::get('Users');
  1922. $result = $table->findByUsernameAndId('garrett', 4);
  1923. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1924. $expected = new QueryExpression(['username' => 'garrett', 'id' => 4], $this->usersTypeMap);
  1925. $this->assertEquals($expected, $result->clause('where'));
  1926. }
  1927. /**
  1928. * Test magic findByXX method.
  1929. *
  1930. * @return void
  1931. */
  1932. public function testMagicFindFirstOr() {
  1933. $table = TableRegistry::get('Users');
  1934. $result = $table->findByUsernameOrId('garrett', 4);
  1935. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1936. $expected = new QueryExpression([], $this->usersTypeMap);
  1937. $expected->add([
  1938. 'OR' => [
  1939. 'username' => 'garrett',
  1940. 'id' => 4
  1941. ]]
  1942. );
  1943. $this->assertEquals($expected, $result->clause('where'));
  1944. }
  1945. /**
  1946. * Test magic findAllByXX method.
  1947. *
  1948. * @return void
  1949. */
  1950. public function testMagicFindAll() {
  1951. $table = TableRegistry::get('Articles');
  1952. $result = $table->findAllByAuthorId(1);
  1953. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1954. $this->assertNull($result->clause('limit'));
  1955. $expected = new QueryExpression(['author_id' => 1], $this->articlesTypeMap);
  1956. $this->assertEquals($expected, $result->clause('where'));
  1957. }
  1958. /**
  1959. * Test magic findAllByXX method.
  1960. *
  1961. * @return void
  1962. */
  1963. public function testMagicFindAllAnd() {
  1964. $table = TableRegistry::get('Users');
  1965. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  1966. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1967. $this->assertNull($result->clause('limit'));
  1968. $expected = new QueryExpression(
  1969. ['author_id' => 1, 'published' => 'Y'],
  1970. $this->usersTypeMap
  1971. );
  1972. $this->assertEquals($expected, $result->clause('where'));
  1973. }
  1974. /**
  1975. * Test magic findAllByXX method.
  1976. *
  1977. * @return void
  1978. */
  1979. public function testMagicFindAllOr() {
  1980. $table = TableRegistry::get('Users');
  1981. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  1982. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1983. $this->assertNull($result->clause('limit'));
  1984. $expected = new QueryExpression();
  1985. $expected->typeMap()->defaults([
  1986. 'Users.id' => 'integer',
  1987. 'id' => 'integer',
  1988. 'Users.username' => 'string',
  1989. 'username' => 'string',
  1990. 'Users.password' => 'string',
  1991. 'password' => 'string',
  1992. 'Users.created' => 'timestamp',
  1993. 'created' => 'timestamp',
  1994. 'Users.updated' => 'timestamp',
  1995. 'updated' => 'timestamp',
  1996. ]);
  1997. $expected->add(
  1998. ['or' => ['author_id' => 1, 'published' => 'Y']]
  1999. );
  2000. $this->assertEquals($expected, $result->clause('where'));
  2001. $this->assertNull($result->clause('order'));
  2002. }
  2003. /**
  2004. * Test the behavior method.
  2005. *
  2006. * @return void
  2007. */
  2008. public function testBehaviorIntrospection() {
  2009. $table = TableRegistry::get('users');
  2010. $this->assertEquals([], $table->behaviors(), 'no loaded behaviors');
  2011. $table->addBehavior('Timestamp');
  2012. $this->assertEquals(['Timestamp'], $table->behaviors(), 'Should have loaded behavior');
  2013. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  2014. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  2015. }
  2016. /**
  2017. * Tests saving belongsTo association
  2018. *
  2019. * @group save
  2020. * @return void
  2021. */
  2022. public function testSaveBelongsTo() {
  2023. $entity = new \Cake\ORM\Entity([
  2024. 'title' => 'A Title',
  2025. 'body' => 'A body'
  2026. ]);
  2027. $entity->author = new \Cake\ORM\Entity([
  2028. 'name' => 'Jose'
  2029. ]);
  2030. $table = TableRegistry::get('articles');
  2031. $table->belongsTo('authors');
  2032. $this->assertSame($entity, $table->save($entity));
  2033. $this->assertFalse($entity->isNew());
  2034. $this->assertFalse($entity->author->isNew());
  2035. $this->assertEquals(5, $entity->author->id);
  2036. $this->assertEquals(5, $entity->get('author_id'));
  2037. }
  2038. /**
  2039. * Tests saving belongsTo association and get a validation error
  2040. *
  2041. * @group save
  2042. * @return void
  2043. */
  2044. public function testsSaveBelongsToWithValidationError() {
  2045. $entity = new \Cake\ORM\Entity([
  2046. 'title' => 'A Title',
  2047. 'body' => 'A body'
  2048. ]);
  2049. $entity->author = new \Cake\ORM\Entity([
  2050. 'name' => 'Jose'
  2051. ]);
  2052. $table = TableRegistry::get('articles');
  2053. $table->belongsTo('authors');
  2054. $table->association('authors')
  2055. ->target()
  2056. ->validator()
  2057. ->add('name', 'num', ['rule' => 'numeric']);
  2058. $this->assertFalse($table->save($entity));
  2059. $this->assertTrue($entity->isNew());
  2060. $this->assertTrue($entity->author->isNew());
  2061. $this->assertNull($entity->get('author_id'));
  2062. $this->assertNotEmpty($entity->author->errors('name'));
  2063. }
  2064. /**
  2065. * Tests saving hasOne association
  2066. *
  2067. * @group save
  2068. * @return void
  2069. */
  2070. public function testSaveHasOne() {
  2071. $entity = new \Cake\ORM\Entity([
  2072. 'name' => 'Jose'
  2073. ]);
  2074. $entity->article = new \Cake\ORM\Entity([
  2075. 'title' => 'A Title',
  2076. 'body' => 'A body'
  2077. ]);
  2078. $table = TableRegistry::get('authors');
  2079. $table->hasOne('articles');
  2080. $this->assertSame($entity, $table->save($entity));
  2081. $this->assertFalse($entity->isNew());
  2082. $this->assertFalse($entity->article->isNew());
  2083. $this->assertEquals(4, $entity->article->id);
  2084. $this->assertEquals(5, $entity->article->get('author_id'));
  2085. $this->assertFalse($entity->article->dirty('author_id'));
  2086. }
  2087. /**
  2088. * Tests saving associations only saves associations
  2089. * if they are entities.
  2090. *
  2091. * @group save
  2092. * @return void
  2093. */
  2094. public function testSaveOnlySaveAssociatedEntities() {
  2095. $entity = new \Cake\ORM\Entity([
  2096. 'name' => 'Jose'
  2097. ]);
  2098. // Not an entity.
  2099. $entity->article = [
  2100. 'title' => 'A Title',
  2101. 'body' => 'A body'
  2102. ];
  2103. $table = TableRegistry::get('authors');
  2104. $table->hasOne('articles');
  2105. $this->assertSame($entity, $table->save($entity));
  2106. $this->assertFalse($entity->isNew());
  2107. $this->assertInternalType('array', $entity->article);
  2108. }
  2109. /**
  2110. * Tests saving hasOne association and returning a validation error will
  2111. * abort the saving process
  2112. *
  2113. * @group save
  2114. * @return void
  2115. */
  2116. public function testSaveHasOneWithValidationError() {
  2117. $entity = new \Cake\ORM\Entity([
  2118. 'name' => 'Jose'
  2119. ]);
  2120. $entity->article = new \Cake\ORM\Entity([
  2121. 'title' => 'A Title',
  2122. 'body' => 'A body'
  2123. ]);
  2124. $table = TableRegistry::get('authors');
  2125. $table->hasOne('articles');
  2126. $table->association('articles')
  2127. ->target()
  2128. ->validator()
  2129. ->add('title', 'num', ['rule' => 'numeric']);
  2130. $this->assertFalse($table->save($entity));
  2131. $this->assertTrue($entity->isNew());
  2132. $this->assertTrue($entity->article->isNew());
  2133. $this->assertNull($entity->article->id);
  2134. $this->assertNull($entity->article->get('author_id'));
  2135. $this->assertTrue($entity->article->dirty('author_id'));
  2136. $this->assertNotEmpty($entity->article->errors('title'));
  2137. }
  2138. /**
  2139. * Tests saving multiple entities in a hasMany association
  2140. *
  2141. * @return void
  2142. */
  2143. public function testSaveHasMany() {
  2144. $entity = new \Cake\ORM\Entity([
  2145. 'name' => 'Jose'
  2146. ]);
  2147. $entity->articles = [
  2148. new \Cake\ORM\Entity([
  2149. 'title' => 'A Title',
  2150. 'body' => 'A body'
  2151. ]),
  2152. new \Cake\ORM\Entity([
  2153. 'title' => 'Another Title',
  2154. 'body' => 'Another body'
  2155. ])
  2156. ];
  2157. $table = TableRegistry::get('authors');
  2158. $table->hasMany('articles');
  2159. $this->assertSame($entity, $table->save($entity));
  2160. $this->assertFalse($entity->isNew());
  2161. $this->assertFalse($entity->articles[0]->isNew());
  2162. $this->assertFalse($entity->articles[1]->isNew());
  2163. $this->assertEquals(4, $entity->articles[0]->id);
  2164. $this->assertEquals(5, $entity->articles[1]->id);
  2165. $this->assertEquals(5, $entity->articles[0]->author_id);
  2166. $this->assertEquals(5, $entity->articles[1]->author_id);
  2167. }
  2168. /**
  2169. * Tests saving multiple entities in a hasMany association and getting and
  2170. * error while saving one of them. It should abort all the save operation
  2171. * when options are set to defaults
  2172. *
  2173. * @return void
  2174. */
  2175. public function testSaveHasManyWithErrorsAtomic() {
  2176. $entity = new \Cake\ORM\Entity([
  2177. 'name' => 'Jose'
  2178. ]);
  2179. $entity->articles = [
  2180. new \Cake\ORM\Entity([
  2181. 'title' => '1',
  2182. 'body' => 'A body'
  2183. ]),
  2184. new \Cake\ORM\Entity([
  2185. 'title' => 'Another Title',
  2186. 'body' => 'Another body'
  2187. ])
  2188. ];
  2189. $table = TableRegistry::get('authors');
  2190. $table->hasMany('articles');
  2191. $table->association('articles')
  2192. ->target()
  2193. ->validator()
  2194. ->add('title', 'num', ['rule' => 'numeric']);
  2195. $this->assertFalse($table->save($entity));
  2196. $this->assertTrue($entity->isNew());
  2197. $this->assertNull($entity->articles[0]->isNew());
  2198. $this->assertNull($entity->articles[1]->isNew());
  2199. $this->assertNull($entity->articles[0]->id);
  2200. $this->assertNull($entity->articles[1]->id);
  2201. $this->assertNull($entity->articles[0]->author_id);
  2202. $this->assertNull($entity->articles[1]->author_id);
  2203. $this->assertEmpty($entity->articles[0]->errors());
  2204. $this->assertNotEmpty($entity->articles[1]->errors());
  2205. }
  2206. /**
  2207. * Tests that it is possible to continue saving hasMany associations
  2208. * even if any of the records fail validation when atomic is set
  2209. * to false
  2210. *
  2211. * @return void
  2212. */
  2213. public function testSaveHasManyWithErrorsNonAtomic() {
  2214. $entity = new \Cake\ORM\Entity([
  2215. 'name' => 'Jose'
  2216. ]);
  2217. $entity->articles = [
  2218. new \Cake\ORM\Entity([
  2219. 'title' => 'A title',
  2220. 'body' => 'A body'
  2221. ]),
  2222. new \Cake\ORM\Entity([
  2223. 'title' => '1',
  2224. 'body' => 'Another body'
  2225. ])
  2226. ];
  2227. $table = TableRegistry::get('authors');
  2228. $table->hasMany('articles');
  2229. $table->association('articles')
  2230. ->target()
  2231. ->validator()
  2232. ->add('title', 'num', ['rule' => 'numeric']);
  2233. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2234. $this->assertFalse($entity->isNew());
  2235. $this->assertTrue($entity->articles[0]->isNew());
  2236. $this->assertFalse($entity->articles[1]->isNew());
  2237. $this->assertEquals(4, $entity->articles[1]->id);
  2238. $this->assertNull($entity->articles[0]->id);
  2239. $this->assertEquals(5, $entity->articles[0]->author_id);
  2240. $this->assertEquals(5, $entity->articles[1]->author_id);
  2241. }
  2242. /**
  2243. * Tests saving hasOne association and returning a validation error will
  2244. * not abort the saving process if atomic is set to false
  2245. *
  2246. * @group save
  2247. * @return void
  2248. */
  2249. public function testSaveHasOneWithValidationErrorNonAtomic() {
  2250. $entity = new \Cake\ORM\Entity([
  2251. 'name' => 'Jose'
  2252. ]);
  2253. $entity->article = new \Cake\ORM\Entity([
  2254. 'title' => 'A Title',
  2255. 'body' => 'A body'
  2256. ]);
  2257. $table = TableRegistry::get('authors');
  2258. $table->hasOne('articles');
  2259. $table->association('articles')
  2260. ->target()
  2261. ->validator()
  2262. ->add('title', 'num', ['rule' => 'numeric']);
  2263. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2264. $this->assertFalse($entity->isNew());
  2265. $this->assertTrue($entity->article->isNew());
  2266. $this->assertNull($entity->article->id);
  2267. $this->assertNull($entity->article->get('author_id'));
  2268. $this->assertTrue($entity->article->dirty('author_id'));
  2269. $this->assertNotEmpty($entity->article->errors('title'));
  2270. }
  2271. /**
  2272. * Tests saving belongsTo association and get a validation error won't stop
  2273. * saving if atomic is set to false
  2274. *
  2275. * @group save
  2276. * @return void
  2277. */
  2278. public function testSaveBelongsToWithValidationErrorNotAtomic() {
  2279. $entity = new \Cake\ORM\Entity([
  2280. 'title' => 'A Title',
  2281. 'body' => 'A body'
  2282. ]);
  2283. $entity->author = new \Cake\ORM\Entity([
  2284. 'name' => 'Jose'
  2285. ]);
  2286. $table = TableRegistry::get('articles');
  2287. $table->belongsTo('authors');
  2288. $table->association('authors')
  2289. ->target()
  2290. ->validator()
  2291. ->add('name', 'num', ['rule' => 'numeric']);
  2292. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2293. $this->assertFalse($entity->isNew());
  2294. $this->assertTrue($entity->author->isNew());
  2295. $this->assertNull($entity->get('author_id'));
  2296. $this->assertNotEmpty($entity->author->errors('name'));
  2297. }
  2298. /**
  2299. * Tests saving belongsToMany records
  2300. *
  2301. * @group save
  2302. * @return void
  2303. */
  2304. public function testSaveBelongsToMany() {
  2305. $entity = new \Cake\ORM\Entity([
  2306. 'title' => 'A Title',
  2307. 'body' => 'A body'
  2308. ]);
  2309. $entity->tags = [
  2310. new \Cake\ORM\Entity([
  2311. 'name' => 'Something New'
  2312. ]),
  2313. new \Cake\ORM\Entity([
  2314. 'name' => 'Another Something'
  2315. ])
  2316. ];
  2317. $table = TableRegistry::get('articles');
  2318. $table->belongsToMany('tags');
  2319. $this->assertSame($entity, $table->save($entity));
  2320. $this->assertFalse($entity->isNew());
  2321. $this->assertFalse($entity->tags[0]->isNew());
  2322. $this->assertFalse($entity->tags[1]->isNew());
  2323. $this->assertEquals(4, $entity->tags[0]->id);
  2324. $this->assertEquals(5, $entity->tags[1]->id);
  2325. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2326. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2327. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2328. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2329. }
  2330. /**
  2331. * Tests saving belongsToMany records with a validation error and atomic set
  2332. * to true
  2333. *
  2334. * @group save
  2335. * @return void
  2336. */
  2337. public function testSaveBelongsToWithValidationErrorAtomic() {
  2338. $entity = new \Cake\ORM\Entity([
  2339. 'title' => 'A Title',
  2340. 'body' => 'A body'
  2341. ]);
  2342. $entity->tags = [
  2343. new \Cake\ORM\Entity([
  2344. 'name' => '100'
  2345. ]),
  2346. new \Cake\ORM\Entity([
  2347. 'name' => 'Something New'
  2348. ])
  2349. ];
  2350. $table = TableRegistry::get('articles');
  2351. $table->belongsToMany('tags');
  2352. $tags = $table->association('tags')
  2353. ->target()
  2354. ->validator()
  2355. ->add('name', 'num', ['rule' => 'numeric']);
  2356. $this->assertFalse($table->save($entity));
  2357. $this->assertTrue($entity->isNew());
  2358. $this->assertNull($entity->tags[0]->isNew());
  2359. $this->assertNull($entity->tags[1]->isNew());
  2360. $this->assertNull($entity->tags[0]->id);
  2361. $this->assertNull($entity->tags[1]->id);
  2362. $this->assertNull($entity->tags[0]->_joinData);
  2363. $this->assertNull($entity->tags[1]->_joinData);
  2364. $this->assertEmpty($entity->tags[0]->errors('name'));
  2365. $this->assertNotEmpty($entity->tags[1]->errors('name'));
  2366. }
  2367. /**
  2368. * Tests saving belongsToMany records with a validation error and atomic set
  2369. * to false
  2370. *
  2371. * @group save
  2372. * @return void
  2373. */
  2374. public function testSaveBelongsToWithValidationErrorNonAtomic() {
  2375. $entity = new \Cake\ORM\Entity([
  2376. 'title' => 'A Title',
  2377. 'body' => 'A body'
  2378. ]);
  2379. $entity->tags = [
  2380. new \Cake\ORM\Entity([
  2381. 'name' => 'Something New'
  2382. ]),
  2383. new \Cake\ORM\Entity([
  2384. 'name' => '100'
  2385. ])
  2386. ];
  2387. $table = TableRegistry::get('articles');
  2388. $table->belongsToMany('tags');
  2389. $tags = $table->association('tags')
  2390. ->target()
  2391. ->validator()
  2392. ->add('name', 'num', ['rule' => 'numeric']);
  2393. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2394. $this->assertFalse($entity->isNew());
  2395. $this->assertTrue($entity->tags[0]->isNew());
  2396. $this->assertFalse($entity->tags[1]->isNew());
  2397. $this->assertNull($entity->tags[0]->id);
  2398. $this->assertEquals(4, $entity->tags[1]->id);
  2399. $this->assertNull($entity->tags[0]->_joinData);
  2400. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2401. $this->assertEquals(4, $entity->tags[1]->_joinData->tag_id);
  2402. }
  2403. /**
  2404. * Tests saving belongsToMany records with a validation error in a joint entity
  2405. *
  2406. * @group save
  2407. * @return void
  2408. */
  2409. public function testSaveBelongsToWithValidationErrorInJointEntity() {
  2410. $entity = new \Cake\ORM\Entity([
  2411. 'title' => 'A Title',
  2412. 'body' => 'A body'
  2413. ]);
  2414. $entity->tags = [
  2415. new \Cake\ORM\Entity([
  2416. 'name' => 'Something New'
  2417. ]),
  2418. new \Cake\ORM\Entity([
  2419. 'name' => '100'
  2420. ])
  2421. ];
  2422. $table = TableRegistry::get('articles');
  2423. $table->belongsToMany('tags');
  2424. $table->association('tags')
  2425. ->junction()
  2426. ->validator()
  2427. ->add('article_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2428. $this->assertFalse($table->save($entity));
  2429. $this->assertTrue($entity->isNew());
  2430. $this->assertNull($entity->tags[0]->isNew());
  2431. $this->assertNull($entity->tags[1]->isNew());
  2432. $this->assertNull($entity->tags[0]->id);
  2433. $this->assertNull($entity->tags[1]->id);
  2434. $this->assertNull($entity->tags[0]->_joinData);
  2435. $this->assertNull($entity->tags[1]->_joinData);
  2436. }
  2437. /**
  2438. * Tests saving belongsToMany records with a validation error in a joint entity
  2439. * and atomic set to false
  2440. *
  2441. * @group save
  2442. * @return void
  2443. */
  2444. public function testSaveBelongsToWithValidationErrorInJointEntityNonAtomic() {
  2445. $entity = new \Cake\ORM\Entity([
  2446. 'title' => 'A Title',
  2447. 'body' => 'A body'
  2448. ]);
  2449. $entity->tags = [
  2450. new \Cake\ORM\Entity([
  2451. 'name' => 'Something New'
  2452. ]),
  2453. new \Cake\ORM\Entity([
  2454. 'name' => 'New one'
  2455. ])
  2456. ];
  2457. $table = TableRegistry::get('articles');
  2458. $table->belongsToMany('tags');
  2459. $table->association('tags')
  2460. ->junction()
  2461. ->validator()
  2462. ->add('tag_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2463. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2464. $this->assertFalse($entity->isNew());
  2465. $this->assertFalse($entity->tags[0]->isNew());
  2466. $this->assertFalse($entity->tags[1]->isNew());
  2467. $this->assertEquals(4, $entity->tags[0]->id);
  2468. $this->assertEquals(5, $entity->tags[1]->id);
  2469. $this->assertTrue($entity->tags[0]->_joinData->isNew());
  2470. $this->assertNotEmpty($entity->tags[0]->_joinData->errors());
  2471. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2472. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2473. }
  2474. /**
  2475. * Tests that saving a persisted and clean entity will is a no-op
  2476. *
  2477. * @group save
  2478. * @return void
  2479. */
  2480. public function testSaveCleanEntity() {
  2481. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  2482. $entity = new \Cake\ORM\Entity(
  2483. ['id' => 'foo'],
  2484. ['markNew' => false, 'markClean' => true]
  2485. );
  2486. $table->expects($this->never())->method('_processSave');
  2487. $this->assertSame($entity, $table->save($entity));
  2488. }
  2489. /**
  2490. * Integration test to show how to append a new tag to an article
  2491. *
  2492. * @group save
  2493. * @return void
  2494. */
  2495. public function testBelongsToManyIntegration() {
  2496. $table = TableRegistry::get('articles');
  2497. $table->belongsToMany('tags');
  2498. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2499. $tags = $article->tags;
  2500. $this->assertNotEmpty($tags);
  2501. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  2502. $article->tags = $tags;
  2503. $this->assertSame($article, $table->save($article));
  2504. $tags = $article->tags;
  2505. $this->assertCount(3, $tags);
  2506. $this->assertFalse($tags[2]->isNew());
  2507. $this->assertEquals(4, $tags[2]->id);
  2508. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  2509. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  2510. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2511. $this->assertEquals($tags, $article->tags);
  2512. }
  2513. /**
  2514. * Tests that it is possible to do a deep save and control what associations get saved,
  2515. * while having control of the options passed to each level of the save
  2516. *
  2517. * @group save
  2518. * @return void
  2519. */
  2520. public function testSaveDeepAssociationOptions() {
  2521. $articles = $this->getMock(
  2522. '\Cake\ORM\Table',
  2523. ['_insert'],
  2524. [['table' => 'articles', 'connection' => $this->connection]]
  2525. );
  2526. $authors = $this->getMock(
  2527. '\Cake\ORM\Table',
  2528. ['_insert', 'validate'],
  2529. [['table' => 'authors', 'connection' => $this->connection]]
  2530. );
  2531. $supervisors = $this->getMock(
  2532. '\Cake\ORM\Table',
  2533. ['_insert', 'validate'],
  2534. [[
  2535. 'table' => 'authors',
  2536. 'alias' => 'supervisors',
  2537. 'connection' => $this->connection
  2538. ]]
  2539. );
  2540. $tags = $this->getMock(
  2541. '\Cake\ORM\Table',
  2542. ['_insert'],
  2543. [['table' => 'tags', 'connection' => $this->connection]]
  2544. );
  2545. $articles->belongsTo('authors', ['targetTable' => $authors]);
  2546. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  2547. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  2548. $entity = new \Cake\ORM\Entity([
  2549. 'title' => 'bar',
  2550. 'author' => new \Cake\ORM\Entity([
  2551. 'name' => 'Juan',
  2552. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  2553. 'tags' => [
  2554. new \Cake\ORM\Entity(['name' => 'foo'])
  2555. ]
  2556. ]),
  2557. ]);
  2558. $entity->isNew(true);
  2559. $entity->author->isNew(true);
  2560. $entity->author->supervisor->isNew(true);
  2561. $entity->author->tags[0]->isNew(true);
  2562. $articles->expects($this->once())
  2563. ->method('_insert')
  2564. ->with($entity, ['title' => 'bar'])
  2565. ->will($this->returnValue($entity));
  2566. $authors->expects($this->once())
  2567. ->method('_insert')
  2568. ->with($entity->author, ['name' => 'Juan'])
  2569. ->will($this->returnValue($entity->author));
  2570. $authors->expects($this->once())
  2571. ->method('validate')
  2572. ->with($entity->author)
  2573. ->will($this->returnValue(true));
  2574. $supervisors->expects($this->once())
  2575. ->method('_insert')
  2576. ->with($entity->author->supervisor, ['name' => 'Marc'])
  2577. ->will($this->returnValue($entity->author->supervisor));
  2578. $supervisors->expects($this->never())->method('validate');
  2579. $tags->expects($this->never())->method('_insert');
  2580. $this->assertSame($entity, $articles->save($entity, [
  2581. 'associated' => [
  2582. 'authors' => [
  2583. 'validate' => 'special',
  2584. 'associated' => [
  2585. 'supervisors' => [
  2586. 'atomic' => false,
  2587. 'validate' => false,
  2588. 'associated' => false
  2589. ]
  2590. ]
  2591. ]
  2592. ]
  2593. ]));
  2594. }
  2595. /**
  2596. * Integration test for linking entities with belongsToMany
  2597. *
  2598. * @return void
  2599. */
  2600. public function testLinkBelongsToMany() {
  2601. $table = TableRegistry::get('articles');
  2602. $table->belongsToMany('tags');
  2603. $tagsTable = TableRegistry::get('tags');
  2604. $source = ['source' => 'tags'];
  2605. $options = ['markNew' => false];
  2606. $article = new \Cake\ORM\Entity([
  2607. 'id' => 1,
  2608. ], $options);
  2609. $newTag = new \TestApp\Model\Entity\Tag([
  2610. 'name' => 'Foo'
  2611. ], $source);
  2612. $tags[] = new \TestApp\Model\Entity\Tag([
  2613. 'id' => 3
  2614. ], $options + $source);
  2615. $tags[] = $newTag;
  2616. $tagsTable->save($newTag);
  2617. $table->association('tags')->link($article, $tags);
  2618. $this->assertEquals($article->tags, $tags);
  2619. foreach ($tags as $tag) {
  2620. $this->assertFalse($tag->isNew());
  2621. }
  2622. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2623. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  2624. $this->assertEquals($article->tags[3], $tags[1]);
  2625. }
  2626. /**
  2627. * Integration test to show how to unlink a single record from a belongsToMany
  2628. *
  2629. * @return void
  2630. */
  2631. public function testUnlinkBelongsToMany() {
  2632. $table = TableRegistry::get('articles');
  2633. $table->belongsToMany('tags');
  2634. $tagsTable = TableRegistry::get('tags');
  2635. $options = ['markNew' => false];
  2636. $article = $table->find('all')
  2637. ->where(['id' => 1])
  2638. ->contain(['tags'])->first();
  2639. $table->association('tags')->unlink($article, [$article->tags[0]]);
  2640. $this->assertCount(1, $article->tags);
  2641. $this->assertEquals(2, $article->tags[0]->get('id'));
  2642. $this->assertFalse($article->dirty('tags'));
  2643. }
  2644. /**
  2645. * Integration test to show how to unlink multiple records from a belongsToMany
  2646. *
  2647. * @return void
  2648. */
  2649. public function testUnlinkBelongsToManyMultiple() {
  2650. $table = TableRegistry::get('articles');
  2651. $table->belongsToMany('tags');
  2652. $tagsTable = TableRegistry::get('tags');
  2653. $options = ['markNew' => false];
  2654. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2655. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2656. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2657. $table->association('tags')->unlink($article, $tags);
  2658. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2659. $this->assertEmpty($left->tags);
  2660. }
  2661. /**
  2662. * Integration test to show how to unlink multiple records from a belongsToMany
  2663. * providing some of the joint
  2664. *
  2665. * @return void
  2666. */
  2667. public function testUnlinkBelongsToManyPassingJoint() {
  2668. $table = TableRegistry::get('articles');
  2669. $table->belongsToMany('tags');
  2670. $tagsTable = TableRegistry::get('tags');
  2671. $options = ['markNew' => false];
  2672. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2673. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2674. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2675. $tags[1]->_joinData = new \Cake\ORM\Entity([
  2676. 'article_id' => 1,
  2677. 'tag_id' => 2
  2678. ]);
  2679. $table->association('tags')->unlink($article, $tags);
  2680. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2681. $this->assertEmpty($left->tags);
  2682. }
  2683. /**
  2684. * Integration test to show how to replace records from a belongsToMany
  2685. *
  2686. * @return void
  2687. */
  2688. public function testReplacelinksBelongsToMany() {
  2689. $table = TableRegistry::get('articles');
  2690. $table->belongsToMany('tags');
  2691. $tagsTable = TableRegistry::get('tags');
  2692. $options = ['markNew' => false];
  2693. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2694. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2695. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2696. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  2697. $table->association('tags')->replaceLinks($article, $tags);
  2698. $this->assertEquals(2, $article->tags[0]->id);
  2699. $this->assertEquals(3, $article->tags[1]->id);
  2700. $this->assertEquals(4, $article->tags[2]->id);
  2701. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2702. $this->assertCount(3, $article->tags);
  2703. $this->assertEquals(2, $article->tags[0]->id);
  2704. $this->assertEquals(3, $article->tags[1]->id);
  2705. $this->assertEquals(4, $article->tags[2]->id);
  2706. $this->assertEquals('foo', $article->tags[2]->name);
  2707. }
  2708. /**
  2709. * Integration test to show how remove all links from a belongsToMany
  2710. *
  2711. * @return void
  2712. */
  2713. public function testReplacelinksBelongsToManyWithEmpty() {
  2714. $table = TableRegistry::get('articles');
  2715. $table->belongsToMany('tags');
  2716. $tagsTable = TableRegistry::get('tags');
  2717. $options = ['markNew' => false];
  2718. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2719. $tags = [];
  2720. $table->association('tags')->replaceLinks($article, $tags);
  2721. $this->assertSame($tags, $article->tags);
  2722. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2723. $this->assertEmpty($article->tags);
  2724. }
  2725. /**
  2726. * Integration test to show how to replace records from a belongsToMany
  2727. * passing the joint property along in the target entity
  2728. *
  2729. * @return void
  2730. */
  2731. public function testReplacelinksBelongsToManyWithJoint() {
  2732. $table = TableRegistry::get('articles');
  2733. $table->belongsToMany('tags');
  2734. $tagsTable = TableRegistry::get('tags');
  2735. $options = ['markNew' => false];
  2736. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2737. $tags[] = new \TestApp\Model\Entity\Tag([
  2738. 'id' => 2,
  2739. '_joinData' => new \Cake\ORM\Entity([
  2740. 'article_id' => 1,
  2741. 'tag_id' => 2,
  2742. ])
  2743. ], $options);
  2744. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2745. $table->association('tags')->replaceLinks($article, $tags);
  2746. $this->assertSame($tags, $article->tags);
  2747. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2748. $this->assertCount(2, $article->tags);
  2749. $this->assertEquals(2, $article->tags[0]->id);
  2750. $this->assertEquals(3, $article->tags[1]->id);
  2751. }
  2752. /**
  2753. * Tests that it is possible to call find with no arguments
  2754. *
  2755. * @return void
  2756. */
  2757. public function testSimplifiedFind() {
  2758. $table = $this->getMock(
  2759. '\Cake\ORM\Table',
  2760. ['callFinder'],
  2761. [[
  2762. 'connection' => $this->connection,
  2763. 'schema' => ['id' => ['type' => 'integer']]
  2764. ]]
  2765. );
  2766. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  2767. $table->expects($this->once())->method('callFinder')
  2768. ->with('all', $query, []);
  2769. $table->find();
  2770. }
  2771. /**
  2772. * Test that get() will use the primary key for searching and return the first
  2773. * entity found
  2774. *
  2775. * @return void
  2776. */
  2777. public function testGet() {
  2778. $table = $this->getMock(
  2779. '\Cake\ORM\Table',
  2780. ['callFinder', 'query'],
  2781. [[
  2782. 'connection' => $this->connection,
  2783. 'schema' => [
  2784. 'id' => ['type' => 'integer'],
  2785. 'bar' => ['type' => 'integer'],
  2786. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2787. ]
  2788. ]]
  2789. );
  2790. $query = $this->getMock(
  2791. '\Cake\ORM\Query',
  2792. ['addDefaultTypes', 'first', 'where'],
  2793. [$this->connection, $table]
  2794. );
  2795. $entity = new \Cake\ORM\Entity;
  2796. $table->expects($this->once())->method('query')
  2797. ->will($this->returnValue($query));
  2798. $table->expects($this->once())->method('callFinder')
  2799. ->with('all', $query, ['fields' => ['id']])
  2800. ->will($this->returnValue($query));
  2801. $query->expects($this->once())->method('where')
  2802. ->with([$table->alias() . '.bar' => 10])
  2803. ->will($this->returnSelf());
  2804. $query->expects($this->once())->method('first')
  2805. ->will($this->returnValue($entity));
  2806. $result = $table->get(10, ['fields' => ['id']]);
  2807. $this->assertSame($entity, $result);
  2808. }
  2809. /**
  2810. * Tests that get() will throw an exception if the record was not found
  2811. *
  2812. * @expectedException \Cake\ORM\Error\RecordNotFoundException
  2813. * @expectedExceptionMessage Record "10" not found in table "articles"
  2814. * @return void
  2815. */
  2816. public function testGetException() {
  2817. $table = $this->getMock(
  2818. '\Cake\ORM\Table',
  2819. ['callFinder', 'query'],
  2820. [[
  2821. 'connection' => $this->connection,
  2822. 'table' => 'articles',
  2823. 'schema' => [
  2824. 'id' => ['type' => 'integer'],
  2825. 'bar' => ['type' => 'integer'],
  2826. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2827. ]
  2828. ]]
  2829. );
  2830. $query = $this->getMock(
  2831. '\Cake\ORM\Query',
  2832. ['addDefaultTypes', 'first', 'where'],
  2833. [$this->connection, $table]
  2834. );
  2835. $table->expects($this->once())->method('query')
  2836. ->will($this->returnValue($query));
  2837. $table->expects($this->once())->method('callFinder')
  2838. ->with('all', $query, ['contain' => ['foo']])
  2839. ->will($this->returnValue($query));
  2840. $query->expects($this->once())->method('where')
  2841. ->with([$table->alias() . '.bar' => 10])
  2842. ->will($this->returnSelf());
  2843. $query->expects($this->once())->method('first')
  2844. ->will($this->returnValue(false));
  2845. $result = $table->get(10, ['contain' => ['foo']]);
  2846. }
  2847. /**
  2848. * Tests entityValidator
  2849. *
  2850. * @return void
  2851. */
  2852. public function testEntityValidator() {
  2853. $table = new Table;
  2854. $expected = new \Cake\ORM\EntityValidator($table);
  2855. $table->entityValidator();
  2856. $this->assertEquals($expected, $table->entityValidator());
  2857. }
  2858. /**
  2859. * Tests that validate will call the entity validator with the correct
  2860. * options
  2861. *
  2862. * @return void
  2863. */
  2864. public function testValidateDefaultAssociations() {
  2865. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2866. $table->belongsTo('users');
  2867. $table->hasMany('articles');
  2868. $table->schema([]);
  2869. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2870. $entity = $table->newEntity([]);
  2871. $table->expects($this->once())->method('entityValidator')
  2872. ->will($this->returnValue($entityValidator));
  2873. $entityValidator->expects($this->once())->method('one')
  2874. ->with($entity, ['associated' => ['users', 'articles']])
  2875. ->will($this->returnValue(true));
  2876. $this->assertTrue($table->validate($entity));
  2877. }
  2878. /**
  2879. * Tests that validate will call the entity validator with the correct
  2880. * options
  2881. *
  2882. * @return void
  2883. */
  2884. public function testValidateWithCustomOptions() {
  2885. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2886. $table->schema([]);
  2887. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2888. $entity = $table->newEntity([]);
  2889. $options = ['associated' => ['users'], 'validate' => 'foo'];
  2890. $table->expects($this->once())->method('entityValidator')
  2891. ->will($this->returnValue($entityValidator));
  2892. $entityValidator->expects($this->once())->method('one')
  2893. ->with($entity, $options)
  2894. ->will($this->returnValue(false));
  2895. $this->assertFalse($table->validate($entity, $options));
  2896. }
  2897. /**
  2898. * Tests that validateMany will call the entity validator with the correct
  2899. * options
  2900. *
  2901. * @return void
  2902. */
  2903. public function testValidateManyDefaultAssociaion() {
  2904. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2905. $table->belongsTo('users');
  2906. $table->hasMany('articles');
  2907. $table->schema([]);
  2908. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2909. $entities = ['a', 'b'];
  2910. $table->expects($this->once())->method('entityValidator')
  2911. ->will($this->returnValue($entityValidator));
  2912. $entityValidator->expects($this->once())->method('many')
  2913. ->with($entities, ['associated' => ['users', 'articles']])
  2914. ->will($this->returnValue(true));
  2915. $this->assertTrue($table->validateMany($entities));
  2916. }
  2917. /**
  2918. * Tests that validateMany will call the entity validator with the correct
  2919. * options
  2920. *
  2921. * @return void
  2922. */
  2923. public function testValidateManyWithCustomOptions() {
  2924. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2925. $table->schema([]);
  2926. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2927. $entities = ['a', 'b', 'c'];
  2928. $options = ['associated' => ['users'], 'validate' => 'foo'];
  2929. $table->expects($this->once())->method('entityValidator')
  2930. ->will($this->returnValue($entityValidator));
  2931. $entityValidator->expects($this->once())->method('many')
  2932. ->with($entities, $options)
  2933. ->will($this->returnValue(false));
  2934. $this->assertFalse($table->validateMany($entities, $options));
  2935. }
  2936. /**
  2937. * Tests that patchEntity delegates the task to the marshaller and passed
  2938. * all associations
  2939. *
  2940. * @return void
  2941. */
  2942. public function testPatchEntity() {
  2943. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  2944. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  2945. $table->belongsTo('users');
  2946. $table->hasMany('articles');
  2947. $table->expects($this->once())->method('marshaller')
  2948. ->will($this->returnValue($marshaller));
  2949. $entity = new \Cake\ORM\Entity;
  2950. $data = ['foo' => 'bar'];
  2951. $marshaller->expects($this->once())
  2952. ->method('merge')
  2953. ->with($entity, $data, ['users', 'articles'])
  2954. ->will($this->returnValue($entity));
  2955. $table->patchEntity($entity, $data);
  2956. }
  2957. /**
  2958. * Tests that patchEntities delegates the task to the marshaller and passed
  2959. * all associations
  2960. *
  2961. * @return void
  2962. */
  2963. public function testPatchEntities() {
  2964. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  2965. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  2966. $table->belongsTo('users');
  2967. $table->hasMany('articles');
  2968. $table->expects($this->once())->method('marshaller')
  2969. ->will($this->returnValue($marshaller));
  2970. $entities = [new \Cake\ORM\Entity];
  2971. $data = [['foo' => 'bar']];
  2972. $marshaller->expects($this->once())
  2973. ->method('mergeMany')
  2974. ->with($entities, $data, ['users', 'articles'])
  2975. ->will($this->returnValue($entities));
  2976. $table->patchEntities($entities, $data);
  2977. }
  2978. /**
  2979. * Tests __debugInfo
  2980. *
  2981. * @return void
  2982. */
  2983. public function testDebugInfo() {
  2984. $articles = TableRegistry::get('articles');
  2985. $articles->addBehavior('Timestamp');
  2986. $result = $articles->__debugInfo();
  2987. $expected = [
  2988. 'table' => 'articles',
  2989. 'alias' => 'articles',
  2990. 'entityClass' => 'TestApp\Model\Entity\Article',
  2991. 'associations' => ['authors', 'tags', 'articlestags'],
  2992. 'behaviors' => ['Timestamp'],
  2993. 'defaultConnection' => 'default',
  2994. 'connectionName' => 'test'
  2995. ];
  2996. $this->assertEquals($expected, $result);
  2997. }
  2998. }