TableTest.php 87 KB

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