TableTest.php 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180
  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\ConnectionManager;
  18. use Cake\Database\Expression\OrderByExpression;
  19. use Cake\Database\Expression\QueryExpression;
  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. * Tests that saving an entity will filter out properties that
  1010. * are not present in the table schema when saving
  1011. *
  1012. * @group save
  1013. * @return void
  1014. */
  1015. public function testSaveEntityOnlySchemaFields() {
  1016. $entity = new \Cake\ORM\Entity([
  1017. 'username' => 'superuser',
  1018. 'password' => 'root',
  1019. 'crazyness' => 'super crazy value',
  1020. 'created' => new \DateTime('2013-10-10 00:00'),
  1021. 'updated' => new \DateTime('2013-10-10 00:00'),
  1022. ]);
  1023. $table = TableRegistry::get('users');
  1024. $this->assertSame($entity, $table->save($entity));
  1025. $this->assertEquals($entity->id, self::$nextUserId);
  1026. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1027. $entity->unsetProperty('crazyness');
  1028. $this->assertEquals($entity->toArray(), $row->toArray());
  1029. }
  1030. /**
  1031. * Tests that it is possible to modify data from the beforeSave callback
  1032. *
  1033. * @group save
  1034. * @return void
  1035. */
  1036. public function testBeforeSaveModifyData() {
  1037. $table = TableRegistry::get('users');
  1038. $data = new \Cake\ORM\Entity([
  1039. 'username' => 'superuser',
  1040. 'created' => new \DateTime('2013-10-10 00:00'),
  1041. 'updated' => new \DateTime('2013-10-10 00:00')
  1042. ]);
  1043. $listener = function($e, $entity, $options) use ($data) {
  1044. $this->assertSame($data, $entity);
  1045. $entity->set('password', 'foo');
  1046. };
  1047. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1048. $this->assertSame($data, $table->save($data));
  1049. $this->assertEquals($data->id, self::$nextUserId);
  1050. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1051. $this->assertEquals('foo', $row->get('password'));
  1052. }
  1053. /**
  1054. * Tests that it is possible to modify the options array in beforeSave
  1055. *
  1056. * @group save
  1057. * @return void
  1058. */
  1059. public function testBeforeSaveModifyOptions() {
  1060. $table = TableRegistry::get('users');
  1061. $data = new \Cake\ORM\Entity([
  1062. 'username' => 'superuser',
  1063. 'password' => 'foo',
  1064. 'created' => new \DateTime('2013-10-10 00:00'),
  1065. 'updated' => new \DateTime('2013-10-10 00:00')
  1066. ]);
  1067. $listener1 = function($e, $entity, $options) {
  1068. $options['crazy'] = true;
  1069. };
  1070. $listener2 = function($e, $entity, $options) {
  1071. $this->assertTrue($options['crazy']);
  1072. };
  1073. $table->getEventManager()->attach($listener1, 'Model.beforeSave');
  1074. $table->getEventManager()->attach($listener2, 'Model.beforeSave');
  1075. $this->assertSame($data, $table->save($data));
  1076. $this->assertEquals($data->id, self::$nextUserId);
  1077. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1078. $this->assertEquals($data->toArray(), $row->toArray());
  1079. }
  1080. /**
  1081. * Tests that it is possible to stop the saving altogether, without implying
  1082. * the save operation failed
  1083. *
  1084. * @group save
  1085. * @return void
  1086. */
  1087. public function testBeforeSaveStopEvent() {
  1088. $table = TableRegistry::get('users');
  1089. $data = new \Cake\ORM\Entity([
  1090. 'username' => 'superuser',
  1091. 'created' => new \DateTime('2013-10-10 00:00'),
  1092. 'updated' => new \DateTime('2013-10-10 00:00')
  1093. ]);
  1094. $listener = function($e, $entity) {
  1095. $e->stopPropagation();
  1096. return $entity;
  1097. };
  1098. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1099. $this->assertSame($data, $table->save($data));
  1100. $this->assertNull($data->id);
  1101. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1102. $this->assertNull($row);
  1103. }
  1104. /**
  1105. * Asserts that afterSave callback is called on successful save
  1106. *
  1107. * @group save
  1108. * @return void
  1109. */
  1110. public function testAfterSave() {
  1111. $table = TableRegistry::get('users');
  1112. $data = new \Cake\ORM\Entity([
  1113. 'username' => 'superuser',
  1114. 'created' => new \DateTime('2013-10-10 00:00'),
  1115. 'updated' => new \DateTime('2013-10-10 00:00')
  1116. ]);
  1117. $called = false;
  1118. $listener = function($e, $entity, $options) use ($data, &$called) {
  1119. $this->assertSame($data, $entity);
  1120. $called = true;
  1121. };
  1122. $table->getEventManager()->attach($listener, 'Model.afterSave');
  1123. $this->assertSame($data, $table->save($data));
  1124. $this->assertEquals($data->id, self::$nextUserId);
  1125. $this->assertTrue($called);
  1126. }
  1127. /**
  1128. * Asserts that afterSave callback not is called on unsuccessful save
  1129. *
  1130. * @group save
  1131. * @return void
  1132. */
  1133. public function testAfterSaveNotCalled() {
  1134. $table = $this->getMock(
  1135. '\Cake\ORM\Table',
  1136. ['query', 'exists'],
  1137. [['table' => 'users', 'connection' => $this->connection]]
  1138. );
  1139. $query = $this->getMock(
  1140. '\Cake\ORM\Query',
  1141. ['execute', 'addDefaultTypes'],
  1142. [null, $table]
  1143. );
  1144. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1145. $data = new \Cake\ORM\Entity([
  1146. 'username' => 'superuser',
  1147. 'created' => new \DateTime('2013-10-10 00:00'),
  1148. 'updated' => new \DateTime('2013-10-10 00:00')
  1149. ]);
  1150. $table->expects($this->once())->method('exists')
  1151. ->will($this->returnValue(false));
  1152. $table->expects($this->once())->method('query')
  1153. ->will($this->returnValue($query));
  1154. $query->expects($this->once())->method('execute')
  1155. ->will($this->returnValue($statement));
  1156. $statement->expects($this->once())->method('rowCount')
  1157. ->will($this->returnValue(0));
  1158. $called = false;
  1159. $listener = function($e, $entity, $options) use ($data, &$called) {
  1160. $called = true;
  1161. };
  1162. $table->getEventManager()->attach($listener, 'Model.afterSave');
  1163. $this->assertFalse($table->save($data));
  1164. $this->assertFalse($called);
  1165. }
  1166. /**
  1167. * Tests that save is wrapped around a transaction
  1168. *
  1169. * @group save
  1170. * @return void
  1171. */
  1172. public function testAtomicSave() {
  1173. $config = ConnectionManager::config('test');
  1174. $connection = $this->getMock(
  1175. '\Cake\Database\Connection',
  1176. ['begin', 'commit'],
  1177. [$config]
  1178. );
  1179. $connection->driver($this->connection->driver());
  1180. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  1181. $table->expects($this->any())->method('connection')
  1182. ->will($this->returnValue($connection));
  1183. $connection->expects($this->once())->method('begin');
  1184. $connection->expects($this->once())->method('commit');
  1185. $data = new \Cake\ORM\Entity([
  1186. 'username' => 'superuser',
  1187. 'created' => new \DateTime('2013-10-10 00:00'),
  1188. 'updated' => new \DateTime('2013-10-10 00:00')
  1189. ]);
  1190. $this->assertSame($data, $table->save($data));
  1191. }
  1192. /**
  1193. * Tests that save will rollback the transaction in the case of an exception
  1194. *
  1195. * @group save
  1196. * @expectedException \PDOException
  1197. * @return void
  1198. */
  1199. public function testAtomicSaveRollback() {
  1200. $connection = $this->getMock(
  1201. '\Cake\Database\Connection',
  1202. ['begin', 'rollback'],
  1203. [ConnectionManager::config('test')]
  1204. );
  1205. $connection->driver(ConnectionManager::get('test')->driver());
  1206. $table = $this->getMock(
  1207. '\Cake\ORM\Table',
  1208. ['query', 'connection', 'exists'],
  1209. [['table' => 'users']]
  1210. );
  1211. $query = $this->getMock(
  1212. '\Cake\ORM\Query',
  1213. ['execute', 'addDefaultTypes'],
  1214. [null, $table]
  1215. );
  1216. $table->expects($this->once())->method('exists')
  1217. ->will($this->returnValue(false));
  1218. $table->expects($this->any())->method('connection')
  1219. ->will($this->returnValue($connection));
  1220. $table->expects($this->once())->method('query')
  1221. ->will($this->returnValue($query));
  1222. $connection->expects($this->once())->method('begin');
  1223. $connection->expects($this->once())->method('rollback');
  1224. $query->expects($this->once())->method('execute')
  1225. ->will($this->throwException(new \PDOException));
  1226. $data = new \Cake\ORM\Entity([
  1227. 'username' => 'superuser',
  1228. 'created' => new \DateTime('2013-10-10 00:00'),
  1229. 'updated' => new \DateTime('2013-10-10 00:00')
  1230. ]);
  1231. $table->save($data);
  1232. }
  1233. /**
  1234. * Tests that save will rollback the transaction in the case of an exception
  1235. *
  1236. * @group save
  1237. * @return void
  1238. */
  1239. public function testAtomicSaveRollbackOnFailure() {
  1240. $connection = $this->getMock(
  1241. '\Cake\Database\Connection',
  1242. ['begin', 'rollback'],
  1243. [ConnectionManager::config('test')]
  1244. );
  1245. $connection->driver(ConnectionManager::get('test')->driver());
  1246. $table = $this->getMock(
  1247. '\Cake\ORM\Table',
  1248. ['query', 'connection', 'exists'],
  1249. [['table' => 'users']]
  1250. );
  1251. $query = $this->getMock(
  1252. '\Cake\ORM\Query',
  1253. ['execute', 'addDefaultTypes'],
  1254. [null, $table]
  1255. );
  1256. $table->expects($this->once())->method('exists')
  1257. ->will($this->returnValue(false));
  1258. $table->expects($this->any())->method('connection')
  1259. ->will($this->returnValue($connection));
  1260. $table->expects($this->once())->method('query')
  1261. ->will($this->returnValue($query));
  1262. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1263. $statement->expects($this->once())
  1264. ->method('rowCount')
  1265. ->will($this->returnValue(0));
  1266. $connection->expects($this->once())->method('begin');
  1267. $connection->expects($this->once())->method('rollback');
  1268. $query->expects($this->once())
  1269. ->method('execute')
  1270. ->will($this->returnValue($statement));
  1271. $data = new \Cake\ORM\Entity([
  1272. 'username' => 'superuser',
  1273. 'created' => new \DateTime('2013-10-10 00:00'),
  1274. 'updated' => new \DateTime('2013-10-10 00:00')
  1275. ]);
  1276. $table->save($data);
  1277. }
  1278. /**
  1279. * Tests that only the properties marked as dirty are actually saved
  1280. * to the database
  1281. *
  1282. * @group save
  1283. * @return void
  1284. */
  1285. public function testSaveOnlyDirtyProperties() {
  1286. $entity = new \Cake\ORM\Entity([
  1287. 'username' => 'superuser',
  1288. 'password' => 'root',
  1289. 'created' => new \DateTime('2013-10-10 00:00'),
  1290. 'updated' => new \DateTime('2013-10-10 00:00')
  1291. ]);
  1292. $entity->clean();
  1293. $entity->dirty('username', true);
  1294. $entity->dirty('created', true);
  1295. $entity->dirty('updated', true);
  1296. $table = TableRegistry::get('users');
  1297. $this->assertSame($entity, $table->save($entity));
  1298. $this->assertEquals($entity->id, self::$nextUserId);
  1299. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1300. $entity->set('password', null);
  1301. $this->assertEquals($entity->toArray(), $row->toArray());
  1302. }
  1303. /**
  1304. * Tests that a recently saved entity is marked as clean
  1305. *
  1306. * @group save
  1307. * @return void
  1308. */
  1309. public function testsASavedEntityIsClean() {
  1310. $entity = new \Cake\ORM\Entity([
  1311. 'username' => 'superuser',
  1312. 'password' => 'root',
  1313. 'created' => new \DateTime('2013-10-10 00:00'),
  1314. 'updated' => new \DateTime('2013-10-10 00:00')
  1315. ]);
  1316. $table = TableRegistry::get('users');
  1317. $this->assertSame($entity, $table->save($entity));
  1318. $this->assertFalse($entity->dirty('usermane'));
  1319. $this->assertFalse($entity->dirty('password'));
  1320. $this->assertFalse($entity->dirty('created'));
  1321. $this->assertFalse($entity->dirty('updated'));
  1322. }
  1323. /**
  1324. * Tests that a recently saved entity is marked as not new
  1325. *
  1326. * @group save
  1327. * @return void
  1328. */
  1329. public function testsASavedEntityIsNotNew() {
  1330. $entity = new \Cake\ORM\Entity([
  1331. 'username' => 'superuser',
  1332. 'password' => 'root',
  1333. 'created' => new \DateTime('2013-10-10 00:00'),
  1334. 'updated' => new \DateTime('2013-10-10 00:00')
  1335. ]);
  1336. $table = TableRegistry::get('users');
  1337. $this->assertSame($entity, $table->save($entity));
  1338. $this->assertFalse($entity->isNew());
  1339. }
  1340. /**
  1341. * Tests that save can detect automatically if it needs to insert
  1342. * or update a row
  1343. *
  1344. * @group save
  1345. * @return void
  1346. */
  1347. public function testSaveUpdateAuto() {
  1348. $entity = new \Cake\ORM\Entity([
  1349. 'id' => 2,
  1350. 'username' => 'baggins'
  1351. ]);
  1352. $table = TableRegistry::get('users');
  1353. $original = $table->find('all')->where(['id' => 2])->first();
  1354. $this->assertSame($entity, $table->save($entity));
  1355. $row = $table->find('all')->where(['id' => 2])->first();
  1356. $this->assertEquals('baggins', $row->username);
  1357. $this->assertEquals($original->password, $row->password);
  1358. $this->assertEquals($original->created, $row->created);
  1359. $this->assertEquals($original->updated, $row->updated);
  1360. $this->assertFalse($entity->isNew());
  1361. $this->assertFalse($entity->dirty('id'));
  1362. $this->assertFalse($entity->dirty('username'));
  1363. }
  1364. /**
  1365. * Tests that beforeFind gets the correct isNew() state for the entity
  1366. *
  1367. * @return void
  1368. */
  1369. public function testBeforeSaveGetsCorrectPersistance() {
  1370. $entity = new \Cake\ORM\Entity([
  1371. 'id' => 2,
  1372. 'username' => 'baggins'
  1373. ]);
  1374. $table = TableRegistry::get('users');
  1375. $called = false;
  1376. $listener = function($event, $entity) use (&$called) {
  1377. $this->assertFalse($entity->isNew());
  1378. $called = true;
  1379. };
  1380. $table->getEventManager()->attach($listener, 'Model.beforeSave');
  1381. $this->assertSame($entity, $table->save($entity));
  1382. $this->assertTrue($called);
  1383. }
  1384. /**
  1385. * Tests that marking an entity as already persisted will prevent the save
  1386. * method from trying to infer the entity's actual status.
  1387. *
  1388. * @group save
  1389. * @return void
  1390. */
  1391. public function testSaveUpdateWithHint() {
  1392. $table = $this->getMock(
  1393. '\Cake\ORM\Table',
  1394. ['exists'],
  1395. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  1396. );
  1397. $entity = new \Cake\ORM\Entity([
  1398. 'id' => 2,
  1399. 'username' => 'baggins'
  1400. ], ['markNew' => false]);
  1401. $this->assertFalse($entity->isNew());
  1402. $table->expects($this->never())->method('exists');
  1403. $this->assertSame($entity, $table->save($entity));
  1404. }
  1405. /**
  1406. * Tests that when updating the primary key is not passed to the list of
  1407. * attributes to change
  1408. *
  1409. * @group save
  1410. * @return void
  1411. */
  1412. public function testSaveUpdatePrimaryKeyNotModified() {
  1413. $table = $this->getMock(
  1414. '\Cake\ORM\Table',
  1415. ['query'],
  1416. [['table' => 'users', 'connection' => $this->connection]]
  1417. );
  1418. $query = $this->getMock(
  1419. '\Cake\ORM\Query',
  1420. ['execute', 'addDefaultTypes', 'set'],
  1421. [null, $table]
  1422. );
  1423. $table->expects($this->once())->method('query')
  1424. ->will($this->returnValue($query));
  1425. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1426. $statement->expects($this->once())->method('rowCount')
  1427. ->will($this->returnValue(1));
  1428. $query->expects($this->once())->method('execute')
  1429. ->will($this->returnValue($statement));
  1430. $query->expects($this->once())->method('set')
  1431. ->with(['username' => 'baggins'])
  1432. ->will($this->returnValue($query));
  1433. $entity = new \Cake\ORM\Entity([
  1434. 'id' => 2,
  1435. 'username' => 'baggins'
  1436. ], ['markNew' => false]);
  1437. $this->assertSame($entity, $table->save($entity));
  1438. }
  1439. /**
  1440. * Tests that passing only the primary key to save will not execute any queries
  1441. * but still return success
  1442. *
  1443. * @group save
  1444. * @return void
  1445. */
  1446. public function testUpdateNoChange() {
  1447. $table = $this->getMock(
  1448. '\Cake\ORM\Table',
  1449. ['query'],
  1450. [['table' => 'users', 'connection' => $this->connection]]
  1451. );
  1452. $table->expects($this->never())->method('query');
  1453. $entity = new \Cake\ORM\Entity([
  1454. 'id' => 2,
  1455. ], ['markNew' => false]);
  1456. $this->assertSame($entity, $table->save($entity));
  1457. }
  1458. /**
  1459. * Tests that failing to pass a primary key to save will result in exception
  1460. *
  1461. * @group save
  1462. * @expectedException \InvalidArgumentException
  1463. * @return void
  1464. */
  1465. public function testUpdateNoPrimaryButOtherKeys() {
  1466. $table = $this->getMock(
  1467. '\Cake\ORM\Table',
  1468. ['query'],
  1469. [['table' => 'users', 'connection' => $this->connection]]
  1470. );
  1471. $table->expects($this->never())->method('query');
  1472. $entity = new \Cake\ORM\Entity([
  1473. 'username' => 'mariano',
  1474. ], ['markNew' => false]);
  1475. $this->assertSame($entity, $table->save($entity));
  1476. }
  1477. /**
  1478. * Test simple delete.
  1479. *
  1480. * @return void
  1481. */
  1482. public function testDelete() {
  1483. $table = TableRegistry::get('users');
  1484. $conditions = [
  1485. 'limit' => 1,
  1486. 'conditions' => [
  1487. 'username' => 'nate'
  1488. ]
  1489. ];
  1490. $query = $table->find('all', $conditions);
  1491. $entity = $query->first();
  1492. $result = $table->delete($entity);
  1493. $this->assertTrue($result);
  1494. $query = $table->find('all', $conditions);
  1495. $results = $query->execute();
  1496. $this->assertCount(0, $results, 'Find should fail.');
  1497. }
  1498. /**
  1499. * Test delete with dependent records
  1500. *
  1501. * @return void
  1502. */
  1503. public function testDeleteDependent() {
  1504. $table = TableRegistry::get('authors');
  1505. $table->hasOne('articles', [
  1506. 'foreignKey' => 'author_id',
  1507. 'dependent' => true,
  1508. ]);
  1509. $query = $table->find('all')->where(['id' => 1]);
  1510. $entity = $query->first();
  1511. $result = $table->delete($entity);
  1512. $articles = $table->association('articles')->target();
  1513. $query = $articles->find('all', [
  1514. 'conditions' => [
  1515. 'author_id' => $entity->id
  1516. ]
  1517. ]);
  1518. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1519. }
  1520. /**
  1521. * Test delete with dependent = false does not cascade.
  1522. *
  1523. * @return void
  1524. */
  1525. public function testDeleteNoDependentNoCascade() {
  1526. $table = TableRegistry::get('authors');
  1527. $table->hasMany('article', [
  1528. 'foreignKey' => 'author_id',
  1529. 'dependent' => false,
  1530. ]);
  1531. $query = $table->find('all')->where(['id' => 1]);
  1532. $entity = $query->first();
  1533. $result = $table->delete($entity);
  1534. $articles = $table->association('articles')->target();
  1535. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  1536. $this->assertCount(2, $query->execute(), 'Should find rows.');
  1537. }
  1538. /**
  1539. * Test delete with BelongsToMany
  1540. *
  1541. * @return void
  1542. */
  1543. public function testDeleteBelongsToMany() {
  1544. $table = TableRegistry::get('articles');
  1545. $table->belongsToMany('tag', [
  1546. 'foreignKey' => 'article_id',
  1547. 'joinTable' => 'articles_tags'
  1548. ]);
  1549. $query = $table->find('all')->where(['id' => 1]);
  1550. $entity = $query->first();
  1551. $table->delete($entity);
  1552. $junction = $table->association('tags')->junction();
  1553. $query = $junction->find('all')->where(['article_id' => 1]);
  1554. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1555. }
  1556. /**
  1557. * Test delete callbacks
  1558. *
  1559. * @return void
  1560. */
  1561. public function testDeleteCallbacks() {
  1562. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1563. $options = new \ArrayObject(['atomic' => true]);
  1564. $mock = $this->getMock('Cake\Event\EventManager');
  1565. $mock->expects($this->at(0))
  1566. ->method('attach');
  1567. $mock->expects($this->at(1))
  1568. ->method('dispatch')
  1569. ->with($this->logicalAnd(
  1570. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  1571. $this->attributeEqualTo(
  1572. 'data',
  1573. ['entity' => $entity, 'options' => $options]
  1574. )
  1575. ));
  1576. $mock->expects($this->at(2))
  1577. ->method('dispatch')
  1578. ->with($this->logicalAnd(
  1579. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  1580. $this->attributeEqualTo(
  1581. 'data',
  1582. ['entity' => $entity, 'options' => $options]
  1583. )
  1584. ));
  1585. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1586. $entity->isNew(false);
  1587. $table->delete($entity);
  1588. }
  1589. /**
  1590. * Test delete beforeDelete can abort the delete.
  1591. *
  1592. * @return void
  1593. */
  1594. public function testDeleteBeforeDeleteAbort() {
  1595. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1596. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1597. $mock = $this->getMock('Cake\Event\EventManager');
  1598. $mock->expects($this->once())
  1599. ->method('dispatch')
  1600. ->will($this->returnCallback(function($event) {
  1601. $event->stopPropagation();
  1602. }));
  1603. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1604. $entity->isNew(false);
  1605. $result = $table->delete($entity);
  1606. $this->assertNull($result);
  1607. }
  1608. /**
  1609. * Test delete beforeDelete return result
  1610. *
  1611. * @return void
  1612. */
  1613. public function testDeleteBeforeDeleteReturnResult() {
  1614. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1615. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1616. $mock = $this->getMock('Cake\Event\EventManager');
  1617. $mock->expects($this->once())
  1618. ->method('dispatch')
  1619. ->will($this->returnCallback(function($event) {
  1620. $event->stopPropagation();
  1621. $event->result = 'got stopped';
  1622. }));
  1623. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1624. $entity->isNew(false);
  1625. $result = $table->delete($entity);
  1626. $this->assertEquals('got stopped', $result);
  1627. }
  1628. /**
  1629. * Test deleting new entities does nothing.
  1630. *
  1631. * @return void
  1632. */
  1633. public function testDeleteIsNew() {
  1634. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1635. $table = $this->getMock(
  1636. 'Cake\ORM\Table',
  1637. ['query'],
  1638. [['connection' => $this->connection]]
  1639. );
  1640. $table->expects($this->never())
  1641. ->method('query');
  1642. $entity->isNew(true);
  1643. $result = $table->delete($entity);
  1644. $this->assertFalse($result);
  1645. }
  1646. /**
  1647. * test hasField()
  1648. *
  1649. * @return void
  1650. */
  1651. public function testHasField() {
  1652. $table = TableRegistry::get('articles');
  1653. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  1654. $this->assertTrue($table->hasField('title'), 'Should be there.');
  1655. $this->assertTrue($table->hasField('body'), 'Should be there.');
  1656. }
  1657. /**
  1658. * Tests that there exists a default validator
  1659. *
  1660. * @return void
  1661. */
  1662. public function testValidatorDefault() {
  1663. $table = new Table();
  1664. $validator = $table->validator();
  1665. $this->assertSame($table, $validator->provider('table'));
  1666. $this->assertInstanceOf('\Cake\Validation\Validator', $validator);
  1667. $default = $table->validator('default');
  1668. $this->assertSame($validator, $default);
  1669. }
  1670. /**
  1671. * Tests that it is possible to define custom validator methods
  1672. *
  1673. * @return void
  1674. */
  1675. public function functionTestValidationWithDefiner() {
  1676. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  1677. $table->expects($this->once())->method('validationForOtherStuff')
  1678. ->will($this->returnArgument(0));
  1679. $other = $table->validator('forOtherStuff');
  1680. $this->assertInstanceOf('\Cake\Validation\Validator', $other);
  1681. $this->assertNotSame($other, $table->validator());
  1682. $this->assertSame($table, $other->provider('table'));
  1683. }
  1684. /**
  1685. * Tests that it is possible to set a custom validator under a name
  1686. *
  1687. * @return void
  1688. */
  1689. public function testValidatorSetter() {
  1690. $table = new Table;
  1691. $validator = new \Cake\Validation\Validator;
  1692. $table->validator('other', $validator);
  1693. $this->assertSame($validator, $table->validator('other'));
  1694. $this->assertSame($table, $validator->provider('table'));
  1695. }
  1696. /**
  1697. * Tests saving with validation
  1698. *
  1699. * @return void
  1700. */
  1701. public function testSaveWithValidationError() {
  1702. $entity = new \Cake\ORM\Entity([
  1703. 'username' => 'superuser'
  1704. ]);
  1705. $table = TableRegistry::get('users');
  1706. $table->validator()->validatePresence('password');
  1707. $this->assertFalse($table->save($entity));
  1708. $this->assertNotEmpty($entity->errors('password'));
  1709. $this->assertSame($entity, $table->validator()->provider('entity'));
  1710. $this->assertSame($table, $table->validator()->provider('table'));
  1711. }
  1712. /**
  1713. * Tests saving with validation and field list
  1714. *
  1715. * @return void
  1716. */
  1717. public function testSaveWithValidationErrorAndFieldList() {
  1718. $entity = new \Cake\ORM\Entity([
  1719. 'username' => 'superuser'
  1720. ]);
  1721. $table = TableRegistry::get('users');
  1722. $table->validator()->validatePresence('password');
  1723. $this->assertFalse($table->save($entity));
  1724. $this->assertNotEmpty($entity->errors('password'));
  1725. }
  1726. /**
  1727. * Tests using a custom validation object when saving
  1728. *
  1729. * @return void
  1730. */
  1731. public function testSaveWithDifferentValidator() {
  1732. $entity = new \Cake\ORM\Entity([
  1733. 'username' => 'superuser'
  1734. ]);
  1735. $table = TableRegistry::get('users');
  1736. $validator = (new Validator)->validatePresence('password');
  1737. $table->validator('custom', $validator);
  1738. $this->assertFalse($table->save($entity, ['validate' => 'custom']));
  1739. $this->assertNotEmpty($entity->errors('password'));
  1740. $this->assertSame($entity, $table->save($entity), 'default was not used');
  1741. }
  1742. /**
  1743. * Tests saving with successful validation
  1744. *
  1745. * @return void
  1746. */
  1747. public function testSaveWithValidationSuccess() {
  1748. $entity = new \Cake\ORM\Entity([
  1749. 'username' => 'superuser',
  1750. 'password' => 'hey'
  1751. ]);
  1752. $table = TableRegistry::get('users');
  1753. $table->validator()->validatePresence('password');
  1754. $this->assertSame($entity, $table->save($entity));
  1755. $this->assertEmpty($entity->errors('password'));
  1756. }
  1757. /**
  1758. * Tests beforeValidate event is triggered
  1759. *
  1760. * @return void
  1761. */
  1762. public function testBeforeValidate() {
  1763. $entity = new \Cake\ORM\Entity([
  1764. 'username' => 'superuser'
  1765. ]);
  1766. $table = TableRegistry::get('users');
  1767. $table->getEventManager()->attach(function($ev, $en, $opt, $val) use ($entity) {
  1768. $this->assertSame($entity, $en);
  1769. $this->assertTrue($opt['crazy']);
  1770. $this->assertSame($ev->subject()->validator('default'), $val);
  1771. $val->validatePresence('password');
  1772. }, 'Model.beforeValidate');
  1773. $this->assertFalse($table->save($entity, ['crazy' => true]));
  1774. $this->assertNotEmpty($entity->errors('password'));
  1775. }
  1776. /**
  1777. * Tests that beforeValidate can set the validation result
  1778. *
  1779. * @return void
  1780. */
  1781. public function testBeforeValidateSetResult() {
  1782. $entity = new \Cake\ORM\Entity([
  1783. 'username' => 'superuser'
  1784. ]);
  1785. $table = TableRegistry::get('users');
  1786. $table->getEventManager()->attach(function($ev, $en) {
  1787. $en->errors('username', 'Not good');
  1788. return false;
  1789. }, 'Model.beforeValidate');
  1790. $this->assertFalse($table->save($entity));
  1791. $this->assertEquals(['Not good'], $entity->errors('username'));
  1792. }
  1793. /**
  1794. * Tests that afterValidate is triggered and can set a result
  1795. *
  1796. * @return void
  1797. */
  1798. public function testAfterValidate() {
  1799. $entity = new \Cake\ORM\Entity([
  1800. 'username' => 'superuser',
  1801. 'password' => 'hey'
  1802. ]);
  1803. $table = TableRegistry::get('users');
  1804. $table->validator()->validatePresence('password');
  1805. $table->getEventManager()->attach(function($ev, $en, $opt, $val) use ($entity) {
  1806. $this->assertSame($entity, $en);
  1807. $this->assertTrue($opt['crazy']);
  1808. $this->assertSame($ev->subject()->validator('default'), $val);
  1809. $en->errors('username', 'Not good');
  1810. return false;
  1811. }, 'Model.afterValidate');
  1812. $this->assertFalse($table->save($entity, ['crazy' => true]));
  1813. $this->assertEmpty($entity->errors('password'));
  1814. $this->assertEquals(['Not good'], $entity->errors('username'));
  1815. }
  1816. /**
  1817. * Test magic findByXX method.
  1818. *
  1819. * @return void
  1820. */
  1821. public function testMagicFindDefaultToAll() {
  1822. $table = TableRegistry::get('Users');
  1823. $result = $table->findByUsername('garrett');
  1824. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1825. $expected = new QueryExpression(['username' => 'garrett'], ['username' => 'string']);
  1826. $this->assertEquals($expected, $result->clause('where'));
  1827. }
  1828. /**
  1829. * Test magic findByXX errors on missing arguments.
  1830. *
  1831. * @expectedException Cake\Error\Exception
  1832. * @expectedExceptionMessage Not enough arguments to magic finder. Got 0 required 1
  1833. * @return void
  1834. */
  1835. public function testMagicFindError() {
  1836. $table = TableRegistry::get('Users');
  1837. $table->findByUsername();
  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 1 required 2
  1844. * @return void
  1845. */
  1846. public function testMagicFindErrorMissingField() {
  1847. $table = TableRegistry::get('Users');
  1848. $table->findByUsernameAndId('garrett');
  1849. }
  1850. /**
  1851. * Test magic findByXX errors when there is a mix of or & and.
  1852. *
  1853. * @expectedException Cake\Error\Exception
  1854. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  1855. * @return void
  1856. */
  1857. public function testMagicFindErrorMixOfOperators() {
  1858. $table = TableRegistry::get('Users');
  1859. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  1860. }
  1861. /**
  1862. * Test magic findByXX method.
  1863. *
  1864. * @return void
  1865. */
  1866. public function testMagicFindFirstAnd() {
  1867. $table = TableRegistry::get('Users');
  1868. $result = $table->findByUsernameAndId('garrett', 4);
  1869. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1870. $expected = new QueryExpression(
  1871. ['username' => 'garrett', 'id' => 4],
  1872. ['username' => 'string', 'id' => 'integer'],
  1873. 'AND'
  1874. );
  1875. $this->assertEquals($expected, $result->clause('where'));
  1876. }
  1877. /**
  1878. * Test magic findByXX method.
  1879. *
  1880. * @return void
  1881. */
  1882. public function testMagicFindFirstOr() {
  1883. $table = TableRegistry::get('Users');
  1884. $result = $table->findByUsernameOrId('garrett', 4);
  1885. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1886. $expected = new QueryExpression();
  1887. $expected->add([
  1888. 'OR' => [
  1889. 'username' => 'garrett',
  1890. 'id' => 4
  1891. ]],
  1892. ['username' => 'string', 'id' => 'integer']
  1893. );
  1894. $this->assertEquals($expected, $result->clause('where'));
  1895. }
  1896. /**
  1897. * Test magic findAllByXX method.
  1898. *
  1899. * @return void
  1900. */
  1901. public function testMagicFindAll() {
  1902. $table = TableRegistry::get('Articles');
  1903. $result = $table->findAllByAuthorId(1);
  1904. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1905. $this->assertNull($result->clause('limit'));
  1906. $expected = new QueryExpression(
  1907. ['author_id' => 1],
  1908. ['author_id' => 'integer'],
  1909. 'AND'
  1910. );
  1911. $this->assertEquals($expected, $result->clause('where'));
  1912. }
  1913. /**
  1914. * Test magic findAllByXX method.
  1915. *
  1916. * @return void
  1917. */
  1918. public function testMagicFindAllAnd() {
  1919. $table = TableRegistry::get('Users');
  1920. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  1921. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1922. $this->assertNull($result->clause('limit'));
  1923. $expected = new QueryExpression(
  1924. ['author_id' => 1, 'published' => 'Y']
  1925. );
  1926. $this->assertEquals($expected, $result->clause('where'));
  1927. }
  1928. /**
  1929. * Test magic findAllByXX method.
  1930. *
  1931. * @return void
  1932. */
  1933. public function testMagicFindAllOr() {
  1934. $table = TableRegistry::get('Users');
  1935. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  1936. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1937. $this->assertNull($result->clause('limit'));
  1938. $expected = new QueryExpression();
  1939. $expected->add(
  1940. ['or' => ['author_id' => 1, 'published' => 'Y']]
  1941. );
  1942. $this->assertEquals($expected, $result->clause('where'));
  1943. $this->assertNull($result->clause('order'));
  1944. }
  1945. /**
  1946. * Test the behavior method.
  1947. *
  1948. * @return void
  1949. */
  1950. public function testBehaviorIntrospection() {
  1951. $table = TableRegistry::get('users');
  1952. $this->assertEquals([], $table->behaviors(), 'no loaded behaviors');
  1953. $table->addBehavior('Timestamp');
  1954. $this->assertEquals(['Timestamp'], $table->behaviors(), 'Should have loaded behavior');
  1955. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  1956. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  1957. }
  1958. /**
  1959. * Tests saving belongsTo association
  1960. *
  1961. * @group save
  1962. * @return void
  1963. */
  1964. public function testSaveBelongsTo() {
  1965. $entity = new \Cake\ORM\Entity([
  1966. 'title' => 'A Title',
  1967. 'body' => 'A body'
  1968. ]);
  1969. $entity->author = new \Cake\ORM\Entity([
  1970. 'name' => 'Jose'
  1971. ]);
  1972. $table = TableRegistry::get('articles');
  1973. $table->belongsTo('authors');
  1974. $this->assertSame($entity, $table->save($entity));
  1975. $this->assertFalse($entity->isNew());
  1976. $this->assertFalse($entity->author->isNew());
  1977. $this->assertEquals(5, $entity->author->id);
  1978. $this->assertEquals(5, $entity->get('author_id'));
  1979. }
  1980. /**
  1981. * Tests saving belongsTo association and get a validation error
  1982. *
  1983. * @group save
  1984. * @return void
  1985. */
  1986. public function testsSaveBelongsToWithValidationError() {
  1987. $entity = new \Cake\ORM\Entity([
  1988. 'title' => 'A Title',
  1989. 'body' => 'A body'
  1990. ]);
  1991. $entity->author = new \Cake\ORM\Entity([
  1992. 'name' => 'Jose'
  1993. ]);
  1994. $table = TableRegistry::get('articles');
  1995. $table->belongsTo('authors');
  1996. $table->association('authors')
  1997. ->target()
  1998. ->validator()
  1999. ->add('name', 'num', ['rule' => 'numeric']);
  2000. $this->assertFalse($table->save($entity));
  2001. $this->assertTrue($entity->isNew());
  2002. $this->assertTrue($entity->author->isNew());
  2003. $this->assertNull($entity->get('author_id'));
  2004. $this->assertNotEmpty($entity->author->errors('name'));
  2005. }
  2006. /**
  2007. * Tests saving hasOne association
  2008. *
  2009. * @group save
  2010. * @return void
  2011. */
  2012. public function testSaveHasOne() {
  2013. $entity = new \Cake\ORM\Entity([
  2014. 'name' => 'Jose'
  2015. ]);
  2016. $entity->article = new \Cake\ORM\Entity([
  2017. 'title' => 'A Title',
  2018. 'body' => 'A body'
  2019. ]);
  2020. $table = TableRegistry::get('authors');
  2021. $table->hasOne('articles');
  2022. $this->assertSame($entity, $table->save($entity));
  2023. $this->assertFalse($entity->isNew());
  2024. $this->assertFalse($entity->article->isNew());
  2025. $this->assertEquals(4, $entity->article->id);
  2026. $this->assertEquals(5, $entity->article->get('author_id'));
  2027. $this->assertFalse($entity->article->dirty('author_id'));
  2028. }
  2029. /**
  2030. * Tests saving associations only saves associations
  2031. * if they are entities.
  2032. *
  2033. * @group save
  2034. * @return void
  2035. */
  2036. public function testSaveOnlySaveAssociatedEntities() {
  2037. $entity = new \Cake\ORM\Entity([
  2038. 'name' => 'Jose'
  2039. ]);
  2040. // Not an entity.
  2041. $entity->article = [
  2042. 'title' => 'A Title',
  2043. 'body' => 'A body'
  2044. ];
  2045. $table = TableRegistry::get('authors');
  2046. $table->hasOne('articles');
  2047. $this->assertSame($entity, $table->save($entity));
  2048. $this->assertFalse($entity->isNew());
  2049. $this->assertInternalType('array', $entity->article);
  2050. }
  2051. /**
  2052. * Tests saving hasOne association and returning a validation error will
  2053. * abort the saving process
  2054. *
  2055. * @group save
  2056. * @return void
  2057. */
  2058. public function testSaveHasOneWithValidationError() {
  2059. $entity = new \Cake\ORM\Entity([
  2060. 'name' => 'Jose'
  2061. ]);
  2062. $entity->article = new \Cake\ORM\Entity([
  2063. 'title' => 'A Title',
  2064. 'body' => 'A body'
  2065. ]);
  2066. $table = TableRegistry::get('authors');
  2067. $table->hasOne('articles');
  2068. $table->association('articles')
  2069. ->target()
  2070. ->validator()
  2071. ->add('title', 'num', ['rule' => 'numeric']);
  2072. $this->assertFalse($table->save($entity));
  2073. $this->assertTrue($entity->isNew());
  2074. $this->assertTrue($entity->article->isNew());
  2075. $this->assertNull($entity->article->id);
  2076. $this->assertNull($entity->article->get('author_id'));
  2077. $this->assertTrue($entity->article->dirty('author_id'));
  2078. $this->assertNotEmpty($entity->article->errors('title'));
  2079. }
  2080. /**
  2081. * Tests saving multiple entities in a hasMany association
  2082. *
  2083. * @return void
  2084. */
  2085. public function testSaveHasMany() {
  2086. $entity = new \Cake\ORM\Entity([
  2087. 'name' => 'Jose'
  2088. ]);
  2089. $entity->articles = [
  2090. new \Cake\ORM\Entity([
  2091. 'title' => 'A Title',
  2092. 'body' => 'A body'
  2093. ]),
  2094. new \Cake\ORM\Entity([
  2095. 'title' => 'Another Title',
  2096. 'body' => 'Another body'
  2097. ])
  2098. ];
  2099. $table = TableRegistry::get('authors');
  2100. $table->hasMany('articles');
  2101. $this->assertSame($entity, $table->save($entity));
  2102. $this->assertFalse($entity->isNew());
  2103. $this->assertFalse($entity->articles[0]->isNew());
  2104. $this->assertFalse($entity->articles[1]->isNew());
  2105. $this->assertEquals(4, $entity->articles[0]->id);
  2106. $this->assertEquals(5, $entity->articles[1]->id);
  2107. $this->assertEquals(5, $entity->articles[0]->author_id);
  2108. $this->assertEquals(5, $entity->articles[1]->author_id);
  2109. }
  2110. /**
  2111. * Tests saving multiple entities in a hasMany association and getting and
  2112. * error while saving one of them. It should abort all the save operation
  2113. * when options are set to defaults
  2114. *
  2115. * @return void
  2116. */
  2117. public function testSaveHasManyWithErrorsAtomic() {
  2118. $entity = new \Cake\ORM\Entity([
  2119. 'name' => 'Jose'
  2120. ]);
  2121. $entity->articles = [
  2122. new \Cake\ORM\Entity([
  2123. 'title' => '1',
  2124. 'body' => 'A body'
  2125. ]),
  2126. new \Cake\ORM\Entity([
  2127. 'title' => 'Another Title',
  2128. 'body' => 'Another body'
  2129. ])
  2130. ];
  2131. $table = TableRegistry::get('authors');
  2132. $table->hasMany('articles');
  2133. $table->association('articles')
  2134. ->target()
  2135. ->validator()
  2136. ->add('title', 'num', ['rule' => 'numeric']);
  2137. $this->assertFalse($table->save($entity));
  2138. $this->assertTrue($entity->isNew());
  2139. $this->assertNull($entity->articles[0]->isNew());
  2140. $this->assertNull($entity->articles[1]->isNew());
  2141. $this->assertNull($entity->articles[0]->id);
  2142. $this->assertNull($entity->articles[1]->id);
  2143. $this->assertNull($entity->articles[0]->author_id);
  2144. $this->assertNull($entity->articles[1]->author_id);
  2145. $this->assertEmpty($entity->articles[0]->errors());
  2146. $this->assertNotEmpty($entity->articles[1]->errors());
  2147. }
  2148. /**
  2149. * Tests that it is possible to continue saving hasMany associations
  2150. * even if any of the records fail validation when atomic is set
  2151. * to false
  2152. *
  2153. * @return void
  2154. */
  2155. public function testSaveHasManyWithErrorsNonAtomic() {
  2156. $entity = new \Cake\ORM\Entity([
  2157. 'name' => 'Jose'
  2158. ]);
  2159. $entity->articles = [
  2160. new \Cake\ORM\Entity([
  2161. 'title' => 'A title',
  2162. 'body' => 'A body'
  2163. ]),
  2164. new \Cake\ORM\Entity([
  2165. 'title' => '1',
  2166. 'body' => 'Another body'
  2167. ])
  2168. ];
  2169. $table = TableRegistry::get('authors');
  2170. $table->hasMany('articles');
  2171. $table->association('articles')
  2172. ->target()
  2173. ->validator()
  2174. ->add('title', 'num', ['rule' => 'numeric']);
  2175. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2176. $this->assertFalse($entity->isNew());
  2177. $this->assertTrue($entity->articles[0]->isNew());
  2178. $this->assertFalse($entity->articles[1]->isNew());
  2179. $this->assertEquals(4, $entity->articles[1]->id);
  2180. $this->assertNull($entity->articles[0]->id);
  2181. $this->assertEquals(5, $entity->articles[0]->author_id);
  2182. $this->assertEquals(5, $entity->articles[1]->author_id);
  2183. }
  2184. /**
  2185. * Tests saving hasOne association and returning a validation error will
  2186. * not abort the saving process if atomic is set to false
  2187. *
  2188. * @group save
  2189. * @return void
  2190. */
  2191. public function testSaveHasOneWithValidationErrorNonAtomic() {
  2192. $entity = new \Cake\ORM\Entity([
  2193. 'name' => 'Jose'
  2194. ]);
  2195. $entity->article = new \Cake\ORM\Entity([
  2196. 'title' => 'A Title',
  2197. 'body' => 'A body'
  2198. ]);
  2199. $table = TableRegistry::get('authors');
  2200. $table->hasOne('articles');
  2201. $table->association('articles')
  2202. ->target()
  2203. ->validator()
  2204. ->add('title', 'num', ['rule' => 'numeric']);
  2205. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2206. $this->assertFalse($entity->isNew());
  2207. $this->assertTrue($entity->article->isNew());
  2208. $this->assertNull($entity->article->id);
  2209. $this->assertNull($entity->article->get('author_id'));
  2210. $this->assertTrue($entity->article->dirty('author_id'));
  2211. $this->assertNotEmpty($entity->article->errors('title'));
  2212. }
  2213. /**
  2214. * Tests saving belongsTo association and get a validation error won't stop
  2215. * saving if atomic is set to false
  2216. *
  2217. * @group save
  2218. * @return void
  2219. */
  2220. public function testSaveBelongsToWithValidationErrorNotAtomic() {
  2221. $entity = new \Cake\ORM\Entity([
  2222. 'title' => 'A Title',
  2223. 'body' => 'A body'
  2224. ]);
  2225. $entity->author = new \Cake\ORM\Entity([
  2226. 'name' => 'Jose'
  2227. ]);
  2228. $table = TableRegistry::get('articles');
  2229. $table->belongsTo('authors');
  2230. $table->association('authors')
  2231. ->target()
  2232. ->validator()
  2233. ->add('name', 'num', ['rule' => 'numeric']);
  2234. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2235. $this->assertFalse($entity->isNew());
  2236. $this->assertTrue($entity->author->isNew());
  2237. $this->assertNull($entity->get('author_id'));
  2238. $this->assertNotEmpty($entity->author->errors('name'));
  2239. }
  2240. /**
  2241. * Tests saving belongsToMany records
  2242. *
  2243. * @group save
  2244. * @return void
  2245. */
  2246. public function testSaveBelongsToMany() {
  2247. $entity = new \Cake\ORM\Entity([
  2248. 'title' => 'A Title',
  2249. 'body' => 'A body'
  2250. ]);
  2251. $entity->tags = [
  2252. new \Cake\ORM\Entity([
  2253. 'name' => 'Something New'
  2254. ]),
  2255. new \Cake\ORM\Entity([
  2256. 'name' => 'Another Something'
  2257. ])
  2258. ];
  2259. $table = TableRegistry::get('articles');
  2260. $table->belongsToMany('tags');
  2261. $this->assertSame($entity, $table->save($entity));
  2262. $this->assertFalse($entity->isNew());
  2263. $this->assertFalse($entity->tags[0]->isNew());
  2264. $this->assertFalse($entity->tags[1]->isNew());
  2265. $this->assertEquals(4, $entity->tags[0]->id);
  2266. $this->assertEquals(5, $entity->tags[1]->id);
  2267. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2268. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2269. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2270. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2271. }
  2272. /**
  2273. * Tests saving belongsToMany records with a validation error and atomic set
  2274. * to true
  2275. *
  2276. * @group save
  2277. * @return void
  2278. */
  2279. public function testSaveBelongsToWithValidationErrorAtomic() {
  2280. $entity = new \Cake\ORM\Entity([
  2281. 'title' => 'A Title',
  2282. 'body' => 'A body'
  2283. ]);
  2284. $entity->tags = [
  2285. new \Cake\ORM\Entity([
  2286. 'name' => '100'
  2287. ]),
  2288. new \Cake\ORM\Entity([
  2289. 'name' => 'Something New'
  2290. ])
  2291. ];
  2292. $table = TableRegistry::get('articles');
  2293. $table->belongsToMany('tags');
  2294. $tags = $table->association('tags')
  2295. ->target()
  2296. ->validator()
  2297. ->add('name', 'num', ['rule' => 'numeric']);
  2298. $this->assertFalse($table->save($entity));
  2299. $this->assertTrue($entity->isNew());
  2300. $this->assertNull($entity->tags[0]->isNew());
  2301. $this->assertNull($entity->tags[1]->isNew());
  2302. $this->assertNull($entity->tags[0]->id);
  2303. $this->assertNull($entity->tags[1]->id);
  2304. $this->assertNull($entity->tags[0]->_joinData);
  2305. $this->assertNull($entity->tags[1]->_joinData);
  2306. $this->assertEmpty($entity->tags[0]->errors('name'));
  2307. $this->assertNotEmpty($entity->tags[1]->errors('name'));
  2308. }
  2309. /**
  2310. * Tests saving belongsToMany records with a validation error and atomic set
  2311. * to false
  2312. *
  2313. * @group save
  2314. * @return void
  2315. */
  2316. public function testSaveBelongsToWithValidationErrorNonAtomic() {
  2317. $entity = new \Cake\ORM\Entity([
  2318. 'title' => 'A Title',
  2319. 'body' => 'A body'
  2320. ]);
  2321. $entity->tags = [
  2322. new \Cake\ORM\Entity([
  2323. 'name' => 'Something New'
  2324. ]),
  2325. new \Cake\ORM\Entity([
  2326. 'name' => '100'
  2327. ])
  2328. ];
  2329. $table = TableRegistry::get('articles');
  2330. $table->belongsToMany('tags');
  2331. $tags = $table->association('tags')
  2332. ->target()
  2333. ->validator()
  2334. ->add('name', 'num', ['rule' => 'numeric']);
  2335. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2336. $this->assertFalse($entity->isNew());
  2337. $this->assertTrue($entity->tags[0]->isNew());
  2338. $this->assertFalse($entity->tags[1]->isNew());
  2339. $this->assertNull($entity->tags[0]->id);
  2340. $this->assertEquals(4, $entity->tags[1]->id);
  2341. $this->assertNull($entity->tags[0]->_joinData);
  2342. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2343. $this->assertEquals(4, $entity->tags[1]->_joinData->tag_id);
  2344. }
  2345. /**
  2346. * Tests saving belongsToMany records with a validation error in a joint entity
  2347. *
  2348. * @group save
  2349. * @return void
  2350. */
  2351. public function testSaveBelongsToWithValidationErrorInJointEntity() {
  2352. $entity = new \Cake\ORM\Entity([
  2353. 'title' => 'A Title',
  2354. 'body' => 'A body'
  2355. ]);
  2356. $entity->tags = [
  2357. new \Cake\ORM\Entity([
  2358. 'name' => 'Something New'
  2359. ]),
  2360. new \Cake\ORM\Entity([
  2361. 'name' => '100'
  2362. ])
  2363. ];
  2364. $table = TableRegistry::get('articles');
  2365. $table->belongsToMany('tags');
  2366. $table->association('tags')
  2367. ->junction()
  2368. ->validator()
  2369. ->add('article_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2370. $this->assertFalse($table->save($entity));
  2371. $this->assertTrue($entity->isNew());
  2372. $this->assertNull($entity->tags[0]->isNew());
  2373. $this->assertNull($entity->tags[1]->isNew());
  2374. $this->assertNull($entity->tags[0]->id);
  2375. $this->assertNull($entity->tags[1]->id);
  2376. $this->assertNull($entity->tags[0]->_joinData);
  2377. $this->assertNull($entity->tags[1]->_joinData);
  2378. }
  2379. /**
  2380. * Tests saving belongsToMany records with a validation error in a joint entity
  2381. * and atomic set to false
  2382. *
  2383. * @group save
  2384. * @return void
  2385. */
  2386. public function testSaveBelongsToWithValidationErrorInJointEntityNonAtomic() {
  2387. $entity = new \Cake\ORM\Entity([
  2388. 'title' => 'A Title',
  2389. 'body' => 'A body'
  2390. ]);
  2391. $entity->tags = [
  2392. new \Cake\ORM\Entity([
  2393. 'name' => 'Something New'
  2394. ]),
  2395. new \Cake\ORM\Entity([
  2396. 'name' => 'New one'
  2397. ])
  2398. ];
  2399. $table = TableRegistry::get('articles');
  2400. $table->belongsToMany('tags');
  2401. $table->association('tags')
  2402. ->junction()
  2403. ->validator()
  2404. ->add('tag_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2405. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2406. $this->assertFalse($entity->isNew());
  2407. $this->assertFalse($entity->tags[0]->isNew());
  2408. $this->assertFalse($entity->tags[1]->isNew());
  2409. $this->assertEquals(4, $entity->tags[0]->id);
  2410. $this->assertEquals(5, $entity->tags[1]->id);
  2411. $this->assertTrue($entity->tags[0]->_joinData->isNew());
  2412. $this->assertNotEmpty($entity->tags[0]->_joinData->errors());
  2413. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2414. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2415. }
  2416. /**
  2417. * Tests that saving a persisted and clean entity will is a no-op
  2418. *
  2419. * @group save
  2420. * @return void
  2421. */
  2422. public function testSaveCleanEntity() {
  2423. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  2424. $entity = new \Cake\ORM\Entity(
  2425. ['id' => 'foo'],
  2426. ['markNew' => false, 'markClean' => true]
  2427. );
  2428. $table->expects($this->never())->method('_processSave');
  2429. $this->assertSame($entity, $table->save($entity));
  2430. }
  2431. /**
  2432. * Integration test to show how to append a new tag to an article
  2433. *
  2434. * @group save
  2435. * @return void
  2436. */
  2437. public function testBelongsToManyIntegration() {
  2438. $table = TableRegistry::get('articles');
  2439. $table->belongsToMany('tags');
  2440. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2441. $tags = $article->tags;
  2442. $this->assertNotEmpty($tags);
  2443. $tags[] = new \TestApp\Model\Entity\Tag([
  2444. 'name' => 'Something New'
  2445. ]);
  2446. $article->tags = $tags;
  2447. $this->assertSame($article, $table->save($article));
  2448. $tags = $article->tags;
  2449. $this->assertCount(3, $tags);
  2450. $this->assertFalse($tags[2]->isNew());
  2451. $this->assertEquals(4, $tags[2]->id);
  2452. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  2453. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  2454. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2455. $this->assertEquals($tags, $article->tags);
  2456. }
  2457. /**
  2458. * Tests that it is possible to do a deep save and control what associations get saved,
  2459. * while having control of the options passed to each level of the save
  2460. *
  2461. * @group save
  2462. * @return void
  2463. */
  2464. public function testSaveDeepAssociationOptions() {
  2465. $articles = $this->getMock(
  2466. '\Cake\ORM\Table',
  2467. ['_insert'],
  2468. [['table' => 'articles', 'connection' => $this->connection]]
  2469. );
  2470. $authors = $this->getMock(
  2471. '\Cake\ORM\Table',
  2472. ['_insert', 'validate'],
  2473. [['table' => 'authors', 'connection' => $this->connection]]
  2474. );
  2475. $supervisors = $this->getMock(
  2476. '\Cake\ORM\Table',
  2477. ['_insert', 'validate'],
  2478. [[
  2479. 'table' => 'authors',
  2480. 'alias' => 'supervisors',
  2481. 'connection' => $this->connection
  2482. ]]
  2483. );
  2484. $tags = $this->getMock(
  2485. '\Cake\ORM\Table',
  2486. ['_insert'],
  2487. [['table' => 'tags', 'connection' => $this->connection]]
  2488. );
  2489. $articles->belongsTo('authors', ['targetTable' => $authors]);
  2490. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  2491. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  2492. $entity = new \Cake\ORM\Entity([
  2493. 'title' => 'bar',
  2494. 'author' => new \Cake\ORM\Entity([
  2495. 'name' => 'Juan',
  2496. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  2497. 'tags' => [
  2498. new \Cake\ORM\Entity(['name' => 'foo'])
  2499. ]
  2500. ]),
  2501. ]);
  2502. $entity->isNew(true);
  2503. $entity->author->isNew(true);
  2504. $entity->author->supervisor->isNew(true);
  2505. $entity->author->tags[0]->isNew(true);
  2506. $articles->expects($this->once())
  2507. ->method('_insert')
  2508. ->with($entity, ['title' => 'bar'])
  2509. ->will($this->returnValue($entity));
  2510. $authors->expects($this->once())
  2511. ->method('_insert')
  2512. ->with($entity->author, ['name' => 'Juan'])
  2513. ->will($this->returnValue($entity->author));
  2514. $authors->expects($this->once())
  2515. ->method('validate')
  2516. ->with($entity->author)
  2517. ->will($this->returnValue(true));
  2518. $supervisors->expects($this->once())
  2519. ->method('_insert')
  2520. ->with($entity->author->supervisor, ['name' => 'Marc'])
  2521. ->will($this->returnValue($entity->author->supervisor));
  2522. $options = new \ArrayObject([
  2523. 'validate' => false,
  2524. 'atomic' => false,
  2525. 'associated' => []
  2526. ]);
  2527. $supervisors->expects($this->once())
  2528. ->method('validate')
  2529. ->with($entity->author->supervisor, $options)
  2530. ->will($this->returnValue(true));
  2531. $tags->expects($this->never())->method('_insert');
  2532. $this->assertSame($entity, $articles->save($entity, [
  2533. 'associated' => [
  2534. 'authors' => [
  2535. 'validate' => 'special',
  2536. 'associated' => [
  2537. 'supervisors' => [
  2538. 'atomic' => false,
  2539. 'validate' => false,
  2540. 'associated' => false
  2541. ]
  2542. ]
  2543. ]
  2544. ]
  2545. ]));
  2546. }
  2547. /**
  2548. * Integration test for linking entities with belongsToMany
  2549. *
  2550. * @return void
  2551. */
  2552. public function testLinkBelongsToMany() {
  2553. $table = TableRegistry::get('articles');
  2554. $table->belongsToMany('tags');
  2555. $tagsTable = TableRegistry::get('tags');
  2556. $options = ['markNew' => false];
  2557. $article = new \Cake\ORM\Entity([
  2558. 'id' => 1,
  2559. ], $options);
  2560. $newTag = new \TestApp\Model\Entity\Tag([
  2561. 'name' => 'Foo'
  2562. ]);
  2563. $tags[] = new \TestApp\Model\Entity\Tag([
  2564. 'id' => 3
  2565. ], $options);
  2566. $tags[] = $newTag;
  2567. $tagsTable->save($newTag);
  2568. $table->association('tags')->link($article, $tags);
  2569. $this->assertEquals($article->tags, $tags);
  2570. foreach ($tags as $tag) {
  2571. $this->assertFalse($tag->isNew());
  2572. }
  2573. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2574. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  2575. $this->assertEquals($article->tags[3], $tags[1]);
  2576. }
  2577. /**
  2578. * Integration test to show how to unlink a single record from a belongsToMany
  2579. *
  2580. * @return void
  2581. */
  2582. public function testUnlinkBelongsToMany() {
  2583. $table = TableRegistry::get('articles');
  2584. $table->belongsToMany('tags');
  2585. $tagsTable = TableRegistry::get('tags');
  2586. $options = ['markNew' => false];
  2587. $article = $table->find('all')
  2588. ->where(['id' => 1])
  2589. ->contain(['tags'])->first();
  2590. $table->association('tags')->unlink($article, [$article->tags[0]]);
  2591. $this->assertCount(1, $article->tags);
  2592. $this->assertEquals(2, $article->tags[0]->get('id'));
  2593. $this->assertFalse($article->dirty('tags'));
  2594. }
  2595. /**
  2596. * Integration test to show how to unlink multiple records from a belongsToMany
  2597. *
  2598. * @return void
  2599. */
  2600. public function testUnlinkBelongsToManyMultiple() {
  2601. $table = TableRegistry::get('articles');
  2602. $table->belongsToMany('tags');
  2603. $tagsTable = TableRegistry::get('tags');
  2604. $options = ['markNew' => false];
  2605. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2606. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2607. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2608. $table->association('tags')->unlink($article, $tags);
  2609. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2610. $this->assertNull($left->tags);
  2611. }
  2612. /**
  2613. * Integration test to show how to unlink multiple records from a belongsToMany
  2614. * providing some of the joint
  2615. *
  2616. * @return void
  2617. */
  2618. public function testUnlinkBelongsToManyPassingJoint() {
  2619. $table = TableRegistry::get('articles');
  2620. $table->belongsToMany('tags');
  2621. $tagsTable = TableRegistry::get('tags');
  2622. $options = ['markNew' => false];
  2623. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2624. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2625. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2626. $tags[1]->_joinData = new \Cake\ORM\Entity([
  2627. 'article_id' => 1,
  2628. 'tag_id' => 2
  2629. ]);
  2630. $table->association('tags')->unlink($article, $tags);
  2631. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2632. $this->assertNull($left->tags);
  2633. }
  2634. /**
  2635. * Integration test to show how to replace records from a belongsToMany
  2636. *
  2637. * @return void
  2638. */
  2639. public function testReplacelinksBelongsToMany() {
  2640. $table = TableRegistry::get('articles');
  2641. $table->belongsToMany('tags');
  2642. $tagsTable = TableRegistry::get('tags');
  2643. $options = ['markNew' => false];
  2644. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2645. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2646. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2647. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  2648. $table->association('tags')->replaceLinks($article, $tags);
  2649. $this->assertEquals(2, $article->tags[0]->id);
  2650. $this->assertEquals(3, $article->tags[1]->id);
  2651. $this->assertEquals(4, $article->tags[2]->id);
  2652. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2653. $this->assertCount(3, $article->tags);
  2654. $this->assertEquals(2, $article->tags[0]->id);
  2655. $this->assertEquals(3, $article->tags[1]->id);
  2656. $this->assertEquals(4, $article->tags[2]->id);
  2657. $this->assertEquals('foo', $article->tags[2]->name);
  2658. }
  2659. /**
  2660. * Integration test to show how remove all links from a belongsToMany
  2661. *
  2662. * @return void
  2663. */
  2664. public function testReplacelinksBelongsToManyWithEmpty() {
  2665. $table = TableRegistry::get('articles');
  2666. $table->belongsToMany('tags');
  2667. $tagsTable = TableRegistry::get('tags');
  2668. $options = ['markNew' => false];
  2669. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2670. $tags = [];
  2671. $table->association('tags')->replaceLinks($article, $tags);
  2672. $this->assertSame($tags, $article->tags);
  2673. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2674. $this->assertNull($article->tags);
  2675. }
  2676. /**
  2677. * Integration test to show how to replace records from a belongsToMany
  2678. * passing the joint property along in the target entity
  2679. *
  2680. * @return void
  2681. */
  2682. public function testReplacelinksBelongsToManyWithJoint() {
  2683. $table = TableRegistry::get('articles');
  2684. $table->belongsToMany('tags');
  2685. $tagsTable = TableRegistry::get('tags');
  2686. $options = ['markNew' => false];
  2687. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2688. $tags[] = new \TestApp\Model\Entity\Tag([
  2689. 'id' => 2,
  2690. '_joinData' => new \Cake\ORM\Entity([
  2691. 'article_id' => 1,
  2692. 'tag_id' => 2,
  2693. ])
  2694. ], $options);
  2695. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2696. $table->association('tags')->replaceLinks($article, $tags);
  2697. $this->assertSame($tags, $article->tags);
  2698. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2699. $this->assertCount(2, $article->tags);
  2700. $this->assertEquals(2, $article->tags[0]->id);
  2701. $this->assertEquals(3, $article->tags[1]->id);
  2702. }
  2703. /**
  2704. * Tests that it is possible to call find with no arguments
  2705. *
  2706. * @return void
  2707. */
  2708. public function testSimplifiedFind() {
  2709. $table = $this->getMock(
  2710. '\Cake\ORM\Table',
  2711. ['callFinder'],
  2712. [[
  2713. 'connection' => $this->connection,
  2714. 'schema' => ['id' => ['type' => 'integer']]
  2715. ]]
  2716. );
  2717. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  2718. $table->expects($this->once())->method('callFinder')
  2719. ->with('all', $query, []);
  2720. $table->find();
  2721. }
  2722. /**
  2723. * Test that get() will use the primary key for searching and return the first
  2724. * entity found
  2725. *
  2726. * @return void
  2727. */
  2728. public function testGet() {
  2729. $table = $this->getMock(
  2730. '\Cake\ORM\Table',
  2731. ['callFinder', 'query'],
  2732. [[
  2733. 'connection' => $this->connection,
  2734. 'schema' => [
  2735. 'id' => ['type' => 'integer'],
  2736. 'bar' => ['type' => 'integer'],
  2737. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2738. ]
  2739. ]]
  2740. );
  2741. $query = $this->getMock(
  2742. '\Cake\ORM\Query',
  2743. ['addDefaultTypes', 'first', 'where'],
  2744. [$this->connection, $table]
  2745. );
  2746. $entity = new \Cake\ORM\Entity;
  2747. $table->expects($this->once())->method('query')
  2748. ->will($this->returnValue($query));
  2749. $table->expects($this->once())->method('callFinder')
  2750. ->with('all', $query, ['fields' => ['id']])
  2751. ->will($this->returnValue($query));
  2752. $query->expects($this->once())->method('where')
  2753. ->with(['bar' => 10])
  2754. ->will($this->returnSelf());
  2755. $query->expects($this->once())->method('first')
  2756. ->will($this->returnValue($entity));
  2757. $result = $table->get(10, ['fields' => ['id']]);
  2758. $this->assertSame($entity, $result);
  2759. }
  2760. /**
  2761. * Tests that get() will throw an exception if the record was not found
  2762. *
  2763. * @expectedException \Cake\ORM\Error\RecordNotFoundException
  2764. * @expectedExceptionMessage Record "10" not found in table "articles"
  2765. * @return void
  2766. */
  2767. public function testGetException() {
  2768. $table = $this->getMock(
  2769. '\Cake\ORM\Table',
  2770. ['callFinder', 'query'],
  2771. [[
  2772. 'connection' => $this->connection,
  2773. 'table' => 'articles',
  2774. 'schema' => [
  2775. 'id' => ['type' => 'integer'],
  2776. 'bar' => ['type' => 'integer'],
  2777. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2778. ]
  2779. ]]
  2780. );
  2781. $query = $this->getMock(
  2782. '\Cake\ORM\Query',
  2783. ['addDefaultTypes', 'first', 'where'],
  2784. [$this->connection, $table]
  2785. );
  2786. $table->expects($this->once())->method('query')
  2787. ->will($this->returnValue($query));
  2788. $table->expects($this->once())->method('callFinder')
  2789. ->with('all', $query, ['contain' => ['foo']])
  2790. ->will($this->returnValue($query));
  2791. $query->expects($this->once())->method('where')
  2792. ->with(['bar' => 10])
  2793. ->will($this->returnSelf());
  2794. $query->expects($this->once())->method('first')
  2795. ->will($this->returnValue(false));
  2796. $result = $table->get(10, ['contain' => ['foo']]);
  2797. }
  2798. /**
  2799. * Tests entityValidator
  2800. *
  2801. * @return void
  2802. */
  2803. public function testEntityValidator() {
  2804. $table = new Table;
  2805. $expected = new \Cake\ORM\EntityValidator($table);
  2806. $table->entityValidator();
  2807. $this->assertEquals($expected, $table->entityValidator());
  2808. }
  2809. /**
  2810. * Tests that validate will call the entity validator with the correct
  2811. * options
  2812. *
  2813. * @return void
  2814. */
  2815. public function testValidateDefaultAssociations() {
  2816. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2817. $table->belongsTo('users');
  2818. $table->hasMany('articles');
  2819. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2820. $entity = $table->newEntity([]);
  2821. $table->expects($this->once())->method('entityValidator')
  2822. ->will($this->returnValue($entityValidator));
  2823. $entityValidator->expects($this->once())->method('one')
  2824. ->with($entity, ['associated' => ['users', 'articles']])
  2825. ->will($this->returnValue(true));
  2826. $this->assertTrue($table->validate($entity));
  2827. }
  2828. /**
  2829. * Tests that validate will call the entity validator with the correct
  2830. * options
  2831. *
  2832. * @return void
  2833. */
  2834. public function testValidateWithCustomOptions() {
  2835. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2836. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2837. $entity = $table->newEntity([]);
  2838. $options = ['associated' => ['users'], 'validate' => 'foo'];
  2839. $table->expects($this->once())->method('entityValidator')
  2840. ->will($this->returnValue($entityValidator));
  2841. $entityValidator->expects($this->once())->method('one')
  2842. ->with($entity, $options)
  2843. ->will($this->returnValue(false));
  2844. $this->assertFalse($table->validate($entity, $options));
  2845. }
  2846. /**
  2847. * Tests that validateMany will call the entity validator with the correct
  2848. * options
  2849. *
  2850. * @return void
  2851. */
  2852. public function testValidateManyDefaultAssociaion() {
  2853. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2854. $table->belongsTo('users');
  2855. $table->hasMany('articles');
  2856. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2857. $entities = ['a', 'b'];
  2858. $table->expects($this->once())->method('entityValidator')
  2859. ->will($this->returnValue($entityValidator));
  2860. $entityValidator->expects($this->once())->method('many')
  2861. ->with($entities, ['associated' => ['users', 'articles']])
  2862. ->will($this->returnValue(true));
  2863. $this->assertTrue($table->validateMany($entities));
  2864. }
  2865. /**
  2866. * Tests that validateMany will call the entity validator with the correct
  2867. * options
  2868. *
  2869. * @return void
  2870. */
  2871. public function testValidateManyWithCustomOptions() {
  2872. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2873. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2874. $entities = ['a', 'b', 'c'];
  2875. $options = ['associated' => ['users'], 'validate' => 'foo'];
  2876. $table->expects($this->once())->method('entityValidator')
  2877. ->will($this->returnValue($entityValidator));
  2878. $entityValidator->expects($this->once())->method('many')
  2879. ->with($entities, $options)
  2880. ->will($this->returnValue(false));
  2881. $this->assertFalse($table->validateMany($entities, $options));
  2882. }
  2883. }