RulesCheckerIntegrationTest.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\ORM\Entity;
  17. use Cake\ORM\RulesChecker;
  18. use Cake\ORM\TableRegistry;
  19. use Cake\TestSuite\TestCase;
  20. /**
  21. * Tests the integration between the ORM and the domain checker
  22. */
  23. class RulesCheckerIntegrationTest extends TestCase
  24. {
  25. /**
  26. * Fixtures to be loaded
  27. *
  28. * @var array
  29. */
  30. public $fixtures = [
  31. 'core.articles', 'core.articles_tags', 'core.authors', 'core.tags',
  32. 'core.special_tags', 'core.categories', 'core.site_articles', 'core.site_authors'
  33. ];
  34. /**
  35. * Tear down
  36. *
  37. * @return void
  38. */
  39. public function tearDown()
  40. {
  41. parent::tearDown();
  42. TableRegistry::clear();
  43. }
  44. /**
  45. * Tests saving belongsTo association and get a validation error
  46. *
  47. * @group save
  48. * @return void
  49. */
  50. public function testsSaveBelongsToWithValidationError()
  51. {
  52. $entity = new Entity([
  53. 'title' => 'A Title',
  54. 'body' => 'A body'
  55. ]);
  56. $entity->author = new Entity([
  57. 'name' => 'Jose'
  58. ]);
  59. $table = TableRegistry::get('articles');
  60. $table->belongsTo('authors');
  61. $table->association('authors')
  62. ->target()
  63. ->rulesChecker()
  64. ->add(
  65. function (Entity $author, array $options) use ($table) {
  66. $this->assertSame($options['repository'], $table->association('authors')->target());
  67. return false;
  68. },
  69. ['errorField' => 'name', 'message' => 'This is an error']
  70. );
  71. $this->assertFalse($table->save($entity));
  72. $this->assertTrue($entity->isNew());
  73. $this->assertTrue($entity->author->isNew());
  74. $this->assertNull($entity->get('author_id'));
  75. $this->assertNotEmpty($entity->author->errors('name'));
  76. $this->assertEquals(['This is an error'], $entity->author->errors('name'));
  77. }
  78. /**
  79. * Tests saving hasOne association and returning a validation error will
  80. * abort the saving process
  81. *
  82. * @group save
  83. * @return void
  84. */
  85. public function testSaveHasOneWithValidationError()
  86. {
  87. $entity = new \Cake\ORM\Entity([
  88. 'name' => 'Jose'
  89. ]);
  90. $entity->article = new \Cake\ORM\Entity([
  91. 'title' => 'A Title',
  92. 'body' => 'A body'
  93. ]);
  94. $table = TableRegistry::get('authors');
  95. $table->hasOne('articles');
  96. $table->association('articles')
  97. ->target()
  98. ->rulesChecker()
  99. ->add(
  100. function (Entity $entity) {
  101. return false;
  102. },
  103. ['errorField' => 'title', 'message' => 'This is an error']
  104. );
  105. $this->assertFalse($table->save($entity));
  106. $this->assertTrue($entity->isNew());
  107. $this->assertTrue($entity->article->isNew());
  108. $this->assertNull($entity->article->id);
  109. $this->assertNull($entity->article->get('author_id'));
  110. $this->assertFalse($entity->article->dirty('author_id'));
  111. $this->assertNotEmpty($entity->article->errors('title'));
  112. $this->assertSame('A Title', $entity->article->invalid('title'));
  113. }
  114. /**
  115. * Tests saving multiple entities in a hasMany association and getting and
  116. * error while saving one of them. It should abort all the save operation
  117. * when options are set to defaults
  118. *
  119. * @return void
  120. */
  121. public function testSaveHasManyWithErrorsAtomic()
  122. {
  123. $entity = new \Cake\ORM\Entity([
  124. 'name' => 'Jose'
  125. ]);
  126. $entity->articles = [
  127. new \Cake\ORM\Entity([
  128. 'title' => '1',
  129. 'body' => 'A body'
  130. ]),
  131. new \Cake\ORM\Entity([
  132. 'title' => 'Another Title',
  133. 'body' => 'Another body'
  134. ])
  135. ];
  136. $table = TableRegistry::get('authors');
  137. $table->hasMany('articles');
  138. $table->association('articles')
  139. ->target()
  140. ->rulesChecker()
  141. ->add(
  142. function (Entity $entity, $options) use ($table) {
  143. $this->assertSame($table, $options['_sourceTable']);
  144. return $entity->title === '1';
  145. },
  146. ['errorField' => 'title', 'message' => 'This is an error']
  147. );
  148. $this->assertFalse($table->save($entity));
  149. $this->assertTrue($entity->isNew());
  150. $this->assertTrue($entity->articles[0]->isNew());
  151. $this->assertTrue($entity->articles[1]->isNew());
  152. $this->assertNull($entity->articles[0]->id);
  153. $this->assertNull($entity->articles[1]->id);
  154. $this->assertNull($entity->articles[0]->author_id);
  155. $this->assertNull($entity->articles[1]->author_id);
  156. $this->assertEmpty($entity->articles[0]->errors());
  157. $this->assertNotEmpty($entity->articles[1]->errors());
  158. }
  159. /**
  160. * Tests that it is possible to continue saving hasMany associations
  161. * even if any of the records fail validation when atomic is set
  162. * to false
  163. *
  164. * @return void
  165. */
  166. public function testSaveHasManyWithErrorsNonAtomic()
  167. {
  168. $entity = new \Cake\ORM\Entity([
  169. 'name' => 'Jose'
  170. ]);
  171. $entity->articles = [
  172. new \Cake\ORM\Entity([
  173. 'title' => 'A title',
  174. 'body' => 'A body'
  175. ]),
  176. new \Cake\ORM\Entity([
  177. 'title' => '1',
  178. 'body' => 'Another body'
  179. ])
  180. ];
  181. $table = TableRegistry::get('authors');
  182. $table->hasMany('articles');
  183. $table->association('articles')
  184. ->target()
  185. ->rulesChecker()
  186. ->add(
  187. function (Entity $article) {
  188. return is_numeric($article->title);
  189. },
  190. ['errorField' => 'title', 'message' => 'This is an error']
  191. );
  192. $result = $table->save($entity, ['atomic' => false]);
  193. $this->assertSame($entity, $result);
  194. $this->assertFalse($entity->isNew());
  195. $this->assertTrue($entity->articles[0]->isNew());
  196. $this->assertFalse($entity->articles[1]->isNew());
  197. $this->assertEquals(4, $entity->articles[1]->id);
  198. $this->assertNull($entity->articles[0]->id);
  199. $this->assertNotEmpty($entity->articles[0]->errors('title'));
  200. }
  201. /**
  202. * Tests saving belongsToMany records with a validation error in a joint entity
  203. *
  204. * @group save
  205. * @return void
  206. */
  207. public function testSaveBelongsToManyWithValidationErrorInJointEntity()
  208. {
  209. $entity = new \Cake\ORM\Entity([
  210. 'title' => 'A Title',
  211. 'body' => 'A body'
  212. ]);
  213. $entity->tags = [
  214. new \Cake\ORM\Entity([
  215. 'name' => 'Something New'
  216. ]),
  217. new \Cake\ORM\Entity([
  218. 'name' => '100'
  219. ])
  220. ];
  221. $table = TableRegistry::get('articles');
  222. $table->belongsToMany('tags');
  223. $table->association('tags')
  224. ->junction()
  225. ->rulesChecker()
  226. ->add(function (Entity $entity) {
  227. return $entity->article_id > 4;
  228. });
  229. $this->assertFalse($table->save($entity));
  230. $this->assertTrue($entity->isNew());
  231. $this->assertTrue($entity->tags[0]->isNew());
  232. $this->assertTrue($entity->tags[1]->isNew());
  233. $this->assertNull($entity->tags[0]->id);
  234. $this->assertNull($entity->tags[1]->id);
  235. $this->assertNull($entity->tags[0]->_joinData);
  236. $this->assertNull($entity->tags[1]->_joinData);
  237. }
  238. /**
  239. * Tests saving belongsToMany records with a validation error in a joint entity
  240. * and atomic set to false
  241. *
  242. * @group save
  243. * @return void
  244. */
  245. public function testSaveBelongsToManyWithValidationErrorInJointEntityNonAtomic()
  246. {
  247. $entity = new \Cake\ORM\Entity([
  248. 'title' => 'A Title',
  249. 'body' => 'A body'
  250. ]);
  251. $entity->tags = [
  252. new \Cake\ORM\Entity([
  253. 'name' => 'Something New'
  254. ]),
  255. new \Cake\ORM\Entity([
  256. 'name' => 'New one'
  257. ])
  258. ];
  259. $table = TableRegistry::get('articles');
  260. $table->belongsToMany('tags');
  261. $table->association('tags')
  262. ->junction()
  263. ->rulesChecker()
  264. ->add(function (Entity $entity) {
  265. return $entity->tag_id > 4;
  266. });
  267. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  268. $this->assertFalse($entity->isNew());
  269. $this->assertFalse($entity->tags[0]->isNew());
  270. $this->assertFalse($entity->tags[1]->isNew());
  271. $this->assertEquals(4, $entity->tags[0]->id);
  272. $this->assertEquals(5, $entity->tags[1]->id);
  273. $this->assertTrue($entity->tags[0]->_joinData->isNew());
  274. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  275. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  276. }
  277. /**
  278. * Test adding rule with name
  279. *
  280. * @group save
  281. * @return void
  282. */
  283. public function testAddingRuleWithName()
  284. {
  285. $entity = new Entity([
  286. 'name' => 'larry'
  287. ]);
  288. $table = TableRegistry::get('Authors');
  289. $rules = $table->rulesChecker();
  290. $rules->add(
  291. function () {
  292. return false;
  293. },
  294. 'ruleName',
  295. ['errorField' => 'name']
  296. );
  297. $this->assertFalse($table->save($entity));
  298. $this->assertEquals(['ruleName' => 'invalid'], $entity->errors('name'));
  299. }
  300. /**
  301. * Ensure that add(isUnique()) only invokes a rule once.
  302. *
  303. * @return void
  304. */
  305. public function testIsUniqueRuleSingleInvocation()
  306. {
  307. $entity = new Entity([
  308. 'name' => 'larry'
  309. ]);
  310. $table = TableRegistry::get('Authors');
  311. $rules = $table->rulesChecker();
  312. $rules->add($rules->isUnique(['name']), '_isUnique', ['errorField' => 'title']);
  313. $this->assertFalse($table->save($entity));
  314. $this->assertEquals(
  315. ['_isUnique' => 'This value is already in use'],
  316. $entity->errors('title'),
  317. 'Provided field should have errors'
  318. );
  319. $this->assertEmpty($entity->errors('name'), 'Errors should not apply to original field.');
  320. }
  321. /**
  322. * Tests the isUnique domain rule
  323. *
  324. * @group save
  325. * @return void
  326. */
  327. public function testIsUniqueDomainRule()
  328. {
  329. $entity = new Entity([
  330. 'name' => 'larry'
  331. ]);
  332. $table = TableRegistry::get('Authors');
  333. $rules = $table->rulesChecker();
  334. $rules->add($rules->isUnique(['name']));
  335. $this->assertFalse($table->save($entity));
  336. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('name'));
  337. $entity->name = 'jose';
  338. $this->assertSame($entity, $table->save($entity));
  339. $entity = $table->get(1);
  340. $entity->dirty('name', true);
  341. $this->assertSame($entity, $table->save($entity));
  342. }
  343. /**
  344. * Tests isUnique with multiple fields
  345. *
  346. * @group save
  347. * @return void
  348. */
  349. public function testIsUniqueMultipleFields()
  350. {
  351. $entity = new Entity([
  352. 'author_id' => 1,
  353. 'title' => 'First Article'
  354. ]);
  355. $table = TableRegistry::get('Articles');
  356. $rules = $table->rulesChecker();
  357. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  358. $this->assertFalse($table->save($entity));
  359. $this->assertEquals(['title' => ['_isUnique' => 'Nope']], $entity->errors());
  360. $entity->clean();
  361. $entity->author_id = 2;
  362. $this->assertSame($entity, $table->save($entity));
  363. }
  364. /**
  365. * Tests isUnique with allowMultipleNulls
  366. *
  367. * @group save
  368. * @return void
  369. */
  370. public function testIsUniqueAllowMultipleNulls()
  371. {
  372. $entity = new Entity([
  373. 'article_id' => 11,
  374. 'tag_id' => 11,
  375. 'author_id' => null
  376. ]);
  377. $table = TableRegistry::get('SpecialTags');
  378. $rules = $table->rulesChecker();
  379. $rules->add($rules->isUnique(['author_id'], [
  380. 'allowMultipleNulls' => false,
  381. 'message' => 'All fields are required'
  382. ]));
  383. $this->assertFalse($table->save($entity));
  384. $this->assertEquals(['_isUnique' => 'All fields are required'], $entity->errors('author_id'));
  385. $entity->author_id = 11;
  386. $this->assertSame($entity, $table->save($entity));
  387. $entity = $table->get(1);
  388. $entity->dirty('author_id', true);
  389. $this->assertSame($entity, $table->save($entity));
  390. }
  391. /**
  392. * Tests isUnique with multiple fields and allowMultipleNulls
  393. *
  394. * @group save
  395. * @return void
  396. */
  397. public function testIsUniqueMultipleFieldsAllowMultipleNulls()
  398. {
  399. $entity = new Entity([
  400. 'article_id' => 10,
  401. 'tag_id' => 12,
  402. 'author_id' => null
  403. ]);
  404. $table = TableRegistry::get('SpecialTags');
  405. $rules = $table->rulesChecker();
  406. $rules->add($rules->isUnique(['author_id', 'article_id'], [
  407. 'allowMultipleNulls' => false,
  408. 'message' => 'Nope'
  409. ]));
  410. $this->assertFalse($table->save($entity));
  411. $this->assertEquals(['author_id' => ['_isUnique' => 'Nope']], $entity->errors());
  412. $entity->clean();
  413. $entity->article_id = 10;
  414. $entity->tag_id = 12;
  415. $entity->author_id = 12;
  416. $this->assertSame($entity, $table->save($entity));
  417. }
  418. /**
  419. * Tests isUnique with multiple fields emulates SQL UNIQUE keys
  420. *
  421. * @group save
  422. * @return void
  423. */
  424. public function testIsUniqueMultipleFieldsOneIsNull()
  425. {
  426. $entity = new Entity([
  427. 'author_id' => null,
  428. 'title' => 'First Article'
  429. ]);
  430. $table = TableRegistry::get('Articles');
  431. $rules = $table->rulesChecker();
  432. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  433. $this->assertSame($entity, $table->save($entity));
  434. // Make a matching record
  435. $entity = new Entity([
  436. 'author_id' => null,
  437. 'title' => 'New Article'
  438. ]);
  439. $this->assertSame($entity, $table->save($entity));
  440. }
  441. /**
  442. * Tests the existsIn domain rule
  443. *
  444. * @group save
  445. * @return void
  446. */
  447. public function testExistsInDomainRule()
  448. {
  449. $entity = new Entity([
  450. 'title' => 'An Article',
  451. 'author_id' => 500
  452. ]);
  453. $table = TableRegistry::get('Articles');
  454. $table->belongsTo('Authors');
  455. $rules = $table->rulesChecker();
  456. $rules->add($rules->existsIn('author_id', 'Authors'));
  457. $this->assertFalse($table->save($entity));
  458. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  459. }
  460. /**
  461. * Ensure that add(existsIn()) only invokes a rule once.
  462. *
  463. * @return void
  464. */
  465. public function testExistsInRuleSingleInvocation()
  466. {
  467. $entity = new Entity([
  468. 'title' => 'larry',
  469. 'author_id' => 500,
  470. ]);
  471. $table = TableRegistry::get('Articles');
  472. $table->belongsTo('Authors');
  473. $rules = $table->rulesChecker();
  474. $rules->add($rules->existsIn('author_id', 'Authors'), '_existsIn', ['errorField' => 'other']);
  475. $this->assertFalse($table->save($entity));
  476. $this->assertEquals(
  477. ['_existsIn' => 'This value does not exist'],
  478. $entity->errors('other'),
  479. 'Provided field should have errors'
  480. );
  481. $this->assertEmpty($entity->errors('author_id'), 'Errors should not apply to original field.');
  482. }
  483. /**
  484. * Tests the existsIn domain rule when passing an object
  485. *
  486. * @group save
  487. * @return void
  488. */
  489. public function testExistsInDomainRuleWithObject()
  490. {
  491. $entity = new Entity([
  492. 'title' => 'An Article',
  493. 'author_id' => 500
  494. ]);
  495. $table = TableRegistry::get('Articles');
  496. $rules = $table->rulesChecker();
  497. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  498. $this->assertFalse($table->save($entity));
  499. $this->assertEquals(['_existsIn' => 'Nope'], $entity->errors('author_id'));
  500. }
  501. /**
  502. * ExistsIn uses the schema to verify that nullable fields are ok.
  503. *
  504. * @return
  505. */
  506. public function testExistsInNullValue()
  507. {
  508. $entity = new Entity([
  509. 'title' => 'An Article',
  510. 'author_id' => null
  511. ]);
  512. $table = TableRegistry::get('Articles');
  513. $table->belongsTo('Authors');
  514. $rules = $table->rulesChecker();
  515. $rules->add($rules->existsIn('author_id', 'Authors'));
  516. $this->assertEquals($entity, $table->save($entity));
  517. $this->assertEquals([], $entity->errors('author_id'));
  518. }
  519. /**
  520. * Test ExistsIn on a new entity that doesn't have the field populated.
  521. *
  522. * This use case is important for saving records and their
  523. * associated belongsTo records in one pass.
  524. *
  525. * @return void
  526. */
  527. public function testExistsInNotNullValueNewEntity()
  528. {
  529. $entity = new Entity([
  530. 'name' => 'A Category',
  531. ]);
  532. $table = TableRegistry::get('Categories');
  533. $table->belongsTo('Categories', [
  534. 'foreignKey' => 'parent_id',
  535. 'bindingKey' => 'id',
  536. ]);
  537. $rules = $table->rulesChecker();
  538. $rules->add($rules->existsIn('parent_id', 'Categories'));
  539. $this->assertTrue($table->checkRules($entity, RulesChecker::CREATE));
  540. $this->assertEmpty($entity->errors('parent_id'));
  541. }
  542. /**
  543. * Tests exists in uses the bindingKey of the association
  544. *
  545. * @return
  546. */
  547. public function testExistsInWithBindingKey()
  548. {
  549. $entity = new Entity([
  550. 'title' => 'An Article',
  551. ]);
  552. $table = TableRegistry::get('Articles');
  553. $table->belongsTo('Authors', [
  554. 'bindingKey' => 'name',
  555. 'foreignKey' => 'title'
  556. ]);
  557. $rules = $table->rulesChecker();
  558. $rules->add($rules->existsIn('title', 'Authors'));
  559. $this->assertFalse($table->save($entity));
  560. $this->assertNotEmpty($entity->errors('title'));
  561. $entity->clean();
  562. $entity->title = 'larry';
  563. $this->assertEquals($entity, $table->save($entity));
  564. }
  565. /**
  566. * Tests existsIn with invalid associations
  567. *
  568. * @group save
  569. * @expectedException RuntimeException
  570. * @expectedExceptionMessage ExistsIn rule for 'author_id' is invalid. The 'NotValid' association is not defined.
  571. * @return void
  572. */
  573. public function testExistsInInvalidAssociation()
  574. {
  575. $entity = new Entity([
  576. 'title' => 'An Article',
  577. 'author_id' => 500
  578. ]);
  579. $table = TableRegistry::get('Articles');
  580. $table->belongsTo('Authors');
  581. $rules = $table->rulesChecker();
  582. $rules->add($rules->existsIn('author_id', 'NotValid'));
  583. $table->save($entity);
  584. }
  585. /**
  586. * Tests the checkRules save option
  587. *
  588. * @group save
  589. * @return void
  590. */
  591. public function testSkipRulesChecking()
  592. {
  593. $entity = new Entity([
  594. 'title' => 'An Article',
  595. 'author_id' => 500
  596. ]);
  597. $table = TableRegistry::get('Articles');
  598. $rules = $table->rulesChecker();
  599. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  600. $this->assertSame($entity, $table->save($entity, ['checkRules' => false]));
  601. }
  602. /**
  603. * Tests the beforeRules event
  604. *
  605. * @group save
  606. * @return void
  607. */
  608. public function testUseBeforeRules()
  609. {
  610. $entity = new Entity([
  611. 'title' => 'An Article',
  612. 'author_id' => 500
  613. ]);
  614. $table = TableRegistry::get('Articles');
  615. $rules = $table->rulesChecker();
  616. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  617. $table->eventManager()->attach(
  618. function ($event, Entity $entity, \ArrayObject $options, $operation) {
  619. $this->assertEquals(
  620. [
  621. 'atomic' => true,
  622. 'associated' => true,
  623. 'checkRules' => true,
  624. 'checkExisting' => true,
  625. '_primary' => true,
  626. ],
  627. $options->getArrayCopy()
  628. );
  629. $this->assertEquals('create', $operation);
  630. $event->stopPropagation();
  631. return true;
  632. },
  633. 'Model.beforeRules'
  634. );
  635. $this->assertSame($entity, $table->save($entity));
  636. }
  637. /**
  638. * Tests the afterRules event
  639. *
  640. * @group save
  641. * @return void
  642. */
  643. public function testUseAfterRules()
  644. {
  645. $entity = new Entity([
  646. 'title' => 'An Article',
  647. 'author_id' => 500
  648. ]);
  649. $table = TableRegistry::get('Articles');
  650. $rules = $table->rulesChecker();
  651. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  652. $table->eventManager()->attach(
  653. function ($event, Entity $entity, \ArrayObject $options, $result, $operation) {
  654. $this->assertEquals(
  655. [
  656. 'atomic' => true,
  657. 'associated' => true,
  658. 'checkRules' => true,
  659. 'checkExisting' => true,
  660. '_primary' => true,
  661. ],
  662. $options->getArrayCopy()
  663. );
  664. $this->assertEquals('create', $operation);
  665. $this->assertFalse($result);
  666. $event->stopPropagation();
  667. return true;
  668. },
  669. 'Model.afterRules'
  670. );
  671. $this->assertSame($entity, $table->save($entity));
  672. }
  673. /**
  674. * Tests that rules can be changed using the buildRules event
  675. *
  676. * @group save
  677. * @return void
  678. */
  679. public function testUseBuildRulesEvent()
  680. {
  681. $entity = new Entity([
  682. 'title' => 'An Article',
  683. 'author_id' => 500
  684. ]);
  685. $table = TableRegistry::get('Articles');
  686. $table->eventManager()->attach(function ($event, $rules) {
  687. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  688. }, 'Model.buildRules');
  689. $this->assertFalse($table->save($entity));
  690. }
  691. /**
  692. * Tests isUnique with untouched fields
  693. *
  694. * @group save
  695. * @return void
  696. */
  697. public function testIsUniqueWithCleanFields()
  698. {
  699. $table = TableRegistry::get('Articles');
  700. $entity = $table->get(1);
  701. $rules = $table->rulesChecker();
  702. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  703. $entity->body = 'Foo';
  704. $this->assertSame($entity, $table->save($entity));
  705. $entity->title = 'Third Article';
  706. $this->assertFalse($table->save($entity));
  707. }
  708. /**
  709. * Tests isUnique rule with coflicting columns
  710. *
  711. * @group save
  712. * @return void
  713. */
  714. public function testIsUniqueAliasPrefix()
  715. {
  716. $entity = new Entity([
  717. 'title' => 'An Article',
  718. 'author_id' => 1
  719. ]);
  720. $table = TableRegistry::get('Articles');
  721. $table->belongsTo('Authors');
  722. $rules = $table->rulesChecker();
  723. $rules->add($rules->isUnique(['author_id']));
  724. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  725. $query->leftJoin(['a2' => 'authors']);
  726. });
  727. $this->assertFalse($table->save($entity));
  728. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('author_id'));
  729. }
  730. /**
  731. * Tests the existsIn rule when passing non dirty fields
  732. *
  733. * @group save
  734. * @return void
  735. */
  736. public function testExistsInWithCleanFields()
  737. {
  738. $table = TableRegistry::get('Articles');
  739. $table->belongsTo('Authors');
  740. $rules = $table->rulesChecker();
  741. $rules->add($rules->existsIn('author_id', 'Authors'));
  742. $entity = $table->get(1);
  743. $entity->title = 'Foo';
  744. $entity->author_id = 1000;
  745. $entity->dirty('author_id', false);
  746. $this->assertSame($entity, $table->save($entity));
  747. }
  748. /**
  749. * Tests the existsIn with coflicting columns
  750. *
  751. * @group save
  752. * @return void
  753. */
  754. public function testExistsInAliasPrefix()
  755. {
  756. $entity = new Entity([
  757. 'title' => 'An Article',
  758. 'author_id' => 500
  759. ]);
  760. $table = TableRegistry::get('Articles');
  761. $table->belongsTo('Authors');
  762. $rules = $table->rulesChecker();
  763. $rules->add($rules->existsIn('author_id', 'Authors'));
  764. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  765. $query->leftJoin(['a2' => 'authors']);
  766. });
  767. $this->assertFalse($table->save($entity));
  768. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  769. }
  770. /**
  771. * Tests that using an array in existsIn() sets the error message correctly
  772. *
  773. * @return
  774. */
  775. public function testExistsInErrorWithArrayField()
  776. {
  777. $entity = new Entity([
  778. 'title' => 'An Article',
  779. 'author_id' => 500
  780. ]);
  781. $table = TableRegistry::get('Articles');
  782. $table->belongsTo('Authors');
  783. $rules = $table->rulesChecker();
  784. $rules->add($rules->existsIn(['author_id'], 'Authors'));
  785. $this->assertFalse($table->save($entity));
  786. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  787. }
  788. /**
  789. * Tests new allowPartialNulls flag with author id set to null
  790. *
  791. * @return
  792. */
  793. public function testExistsInAllowPartialNullsWithAuthorIdNullA()
  794. {
  795. $entity = new Entity([
  796. 'id' => 10,
  797. 'author_id' => null,
  798. 'site_id' => 1,
  799. 'name' => 'New Site Article without Author',
  800. ]);
  801. $table = TableRegistry::get('SiteArticles');
  802. $table->belongsTo('SiteAuthors');
  803. $rules = $table->rulesChecker();
  804. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  805. 'allowPartialNulls' => true
  806. ]));
  807. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  808. }
  809. /**
  810. * Tests new allowPartialNulls flag with author id set to null
  811. *
  812. * @return
  813. */
  814. public function testExistsInAllowPartialNullsWithAuthorIdNullB()
  815. {
  816. $entity = new Entity([
  817. 'id' => 10,
  818. 'author_id' => null,
  819. 'site_id' => 1,
  820. 'name' => 'New Site Article without Author',
  821. ]);
  822. $table = TableRegistry::get('SiteArticles');
  823. $table->belongsTo('SiteAuthors');
  824. $rules = $table->rulesChecker();
  825. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  826. 'allowPartialNulls' => false
  827. ]));
  828. $this->assertFalse($table->save($entity));
  829. }
  830. /**
  831. * Tests new allowPartialNulls flag with author id set to null
  832. *
  833. * @return
  834. */
  835. public function testExistsInAllowPartialNullsWithAuthorIdNullC()
  836. {
  837. $entity = new Entity([
  838. 'id' => 10,
  839. 'author_id' => null,
  840. 'site_id' => 1,
  841. 'name' => 'New Site Article without Author',
  842. ]);
  843. $table = TableRegistry::get('SiteArticles');
  844. $table->belongsTo('SiteAuthors');
  845. $rules = $table->rulesChecker();
  846. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors'));
  847. $this->assertFalse($table->save($entity));
  848. }
  849. /**
  850. * Tests new allowPartialNulls flag with author id set to null
  851. *
  852. * @return
  853. */
  854. public function testExistsInAllowPartialNullsWithAuthorIdNullD()
  855. {
  856. $entity = new Entity([
  857. 'id' => 10,
  858. 'author_id' => null,
  859. 'site_id' => 1,
  860. 'name' => 'New Site Article without Author',
  861. ]);
  862. $table = TableRegistry::get('SiteArticles');
  863. $table->belongsTo('SiteAuthors');
  864. $rules = $table->rulesChecker();
  865. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  866. 'allowPartialNulls' => false,
  867. 'message' => 'Niente'
  868. ]));
  869. $this->assertFalse($table->save($entity));
  870. $this->assertEquals(['author_id' => ['_existsIn' => 'Niente']], $entity->errors());
  871. }
  872. /**
  873. * Tests new allowPartialNulls flag with author id set to null
  874. *
  875. * @return
  876. */
  877. public function testExistsInAllowPartialNullsWithAuthorIdNullE()
  878. {
  879. $entity = new Entity([
  880. 'id' => 10,
  881. 'author_id' => null,
  882. 'site_id' => 1,
  883. 'name' => 'New Site Article without Author',
  884. ]);
  885. $table = TableRegistry::get('SiteArticles');
  886. $table->belongsTo('SiteAuthors');
  887. $rules = $table->rulesChecker();
  888. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  889. 'allowPartialNulls' => true,
  890. 'message' => 'Niente'
  891. ]));
  892. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  893. }
  894. /**
  895. * Tests new allowPartialNulls flag with author id set to 1
  896. *
  897. * @return
  898. */
  899. public function testExistsInAllowPartialNullsWithAuthorId1A()
  900. {
  901. $entity = new Entity([
  902. 'id' => 10,
  903. 'author_id' => 1,
  904. 'site_id' => 1,
  905. 'name' => 'New Site Article with Author',
  906. ]);
  907. $table = TableRegistry::get('SiteArticles');
  908. $table->belongsTo('SiteAuthors');
  909. $rules = $table->rulesChecker();
  910. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', ['allowPartialNulls' => true]));
  911. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  912. }
  913. /**
  914. * Tests new allowPartialNulls flag with author id set to 1
  915. *
  916. * @return
  917. */
  918. public function testExistsInAllowPartialNullsWithAuthorIdB()
  919. {
  920. $entity = new Entity([
  921. 'id' => 10,
  922. 'author_id' => 1,
  923. 'site_id' => 1,
  924. 'name' => 'New Site Article with Author',
  925. ]);
  926. $table = TableRegistry::get('SiteArticles');
  927. $table->belongsTo('SiteAuthors');
  928. $rules = $table->rulesChecker();
  929. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', ['allowPartialNulls' => false]));
  930. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  931. }
  932. /**
  933. * Tests new allowPartialNulls flag with author id set to 1
  934. *
  935. * @return
  936. */
  937. public function testExistsInAllowPartialNullsWithAuthorId1C()
  938. {
  939. $entity = new Entity([
  940. 'id' => 10,
  941. 'author_id' => 1,
  942. 'site_id' => 1,
  943. 'name' => 'New Site Article with Author',
  944. ]);
  945. $table = TableRegistry::get('SiteArticles');
  946. $table->belongsTo('SiteAuthors');
  947. $rules = $table->rulesChecker();
  948. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors'));
  949. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  950. }
  951. /**
  952. * Tests new allowPartialNulls flag with author id set to 1
  953. *
  954. * @return
  955. */
  956. public function testExistsInAllowPartialNullsWithAuthorId1E()
  957. {
  958. $entity = new Entity([
  959. 'id' => 10,
  960. 'author_id' => 1,
  961. 'site_id' => 1,
  962. 'name' => 'New Site Article with Author',
  963. ]);
  964. $table = TableRegistry::get('SiteArticles');
  965. $table->belongsTo('SiteAuthors');
  966. $rules = $table->rulesChecker();
  967. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  968. 'allowPartialNulls' => true,
  969. 'message' => 'will not error']));
  970. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  971. }
  972. /**
  973. * Tests new allowPartialNulls flag with author id set to 1
  974. *
  975. * @return
  976. */
  977. public function testExistsInAllowPartialNullsWithAuthorId1F()
  978. {
  979. $entity = new Entity([
  980. 'id' => 10,
  981. 'author_id' => 1,
  982. 'site_id' => 1,
  983. 'name' => 'New Site Article with Author',
  984. ]);
  985. $table = TableRegistry::get('SiteArticles');
  986. $table->belongsTo('SiteAuthors');
  987. $rules = $table->rulesChecker();
  988. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  989. 'allowPartialNulls' => false,
  990. 'message' => 'will not error']));
  991. $this->assertInstanceOf('Cake\ORM\Entity', $table->save($entity));
  992. }
  993. /**
  994. * Tests new allowPartialNulls flag with author id set to 99999999 (does not exist)
  995. *
  996. * @return
  997. */
  998. public function testExistsInAllowPartialNullsWithAuthorId1G()
  999. {
  1000. $entity = new Entity([
  1001. 'id' => 10,
  1002. 'author_id' => 99999999,
  1003. 'site_id' => 1,
  1004. 'name' => 'New Site Article with Author',
  1005. ]);
  1006. $table = TableRegistry::get('SiteArticles');
  1007. $table->belongsTo('SiteAuthors');
  1008. $rules = $table->rulesChecker();
  1009. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  1010. 'allowPartialNulls' => true,
  1011. 'message' => 'will error']));
  1012. $this->assertFalse($table->save($entity));
  1013. $this->assertEquals(['author_id' => ['_existsIn' => 'will error']], $entity->errors());
  1014. }
  1015. /**
  1016. * Tests new allowPartialNulls flag with author id set to 99999999 (does not exist)
  1017. * and site_id set to 99999999 (does not exist)
  1018. *
  1019. * @return
  1020. */
  1021. public function testExistsInAllowPartialNullsWithAuthorId1H()
  1022. {
  1023. $entity = new Entity([
  1024. 'id' => 10,
  1025. 'author_id' => 99999999,
  1026. 'site_id' => 99999999,
  1027. 'name' => 'New Site Article with Author',
  1028. ]);
  1029. $table = TableRegistry::get('SiteArticles');
  1030. $table->belongsTo('SiteAuthors');
  1031. $rules = $table->rulesChecker();
  1032. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  1033. 'allowPartialNulls' => true,
  1034. 'message' => 'will error']));
  1035. $this->assertFalse($table->save($entity));
  1036. $this->assertEquals(['author_id' => ['_existsIn' => 'will error']], $entity->errors());
  1037. }
  1038. /**
  1039. * Tests new allowPartialNulls flag with author id set to 1 (does exist)
  1040. * and site_id set to 99999999 (does not exist)
  1041. *
  1042. * @return
  1043. */
  1044. public function testExistsInAllowPartialNullsWithAuthorId1I()
  1045. {
  1046. $entity = new Entity([
  1047. 'id' => 10,
  1048. 'author_id' => 1,
  1049. 'site_id' => 99999999,
  1050. 'name' => 'New Site Article with Author',
  1051. ]);
  1052. $table = TableRegistry::get('SiteArticles');
  1053. $table->belongsTo('SiteAuthors');
  1054. $rules = $table->rulesChecker();
  1055. $rules->add($rules->existsIn(['author_id', 'site_id'], 'SiteAuthors', [
  1056. 'allowPartialNulls' => true,
  1057. 'message' => 'will error']));
  1058. $this->assertFalse($table->save($entity));
  1059. $this->assertEquals(['author_id' => ['_existsIn' => 'will error']], $entity->errors());
  1060. }
  1061. /**
  1062. * Tests using rules to prevent delete operations
  1063. *
  1064. * @group delete
  1065. * @return void
  1066. */
  1067. public function testDeleteRules()
  1068. {
  1069. $table = TableRegistry::get('Articles');
  1070. $rules = $table->rulesChecker();
  1071. $rules->addDelete(function ($entity) {
  1072. return false;
  1073. });
  1074. $entity = $table->get(1);
  1075. $this->assertFalse($table->delete($entity));
  1076. }
  1077. /**
  1078. * Checks that it is possible to pass custom options to rules when saving
  1079. *
  1080. * @group save
  1081. * @return void
  1082. */
  1083. public function testCustomOptionsPassingSave()
  1084. {
  1085. $entity = new Entity([
  1086. 'name' => 'jose'
  1087. ]);
  1088. $table = TableRegistry::get('Authors');
  1089. $rules = $table->rulesChecker();
  1090. $rules->add(function ($entity, $options) {
  1091. $this->assertEquals('bar', $options['foo']);
  1092. $this->assertEquals('option', $options['another']);
  1093. return false;
  1094. }, ['another' => 'option']);
  1095. $this->assertFalse($table->save($entity, ['foo' => 'bar']));
  1096. }
  1097. /**
  1098. * Tests passing custom options to rules from delete
  1099. *
  1100. * @group delete
  1101. * @return void
  1102. */
  1103. public function testCustomOptionsPassingDelete()
  1104. {
  1105. $table = TableRegistry::get('Articles');
  1106. $rules = $table->rulesChecker();
  1107. $rules->addDelete(function ($entity, $options) {
  1108. $this->assertEquals('bar', $options['foo']);
  1109. $this->assertEquals('option', $options['another']);
  1110. return false;
  1111. }, ['another' => 'option']);
  1112. $entity = $table->get(1);
  1113. $this->assertFalse($table->delete($entity, ['foo' => 'bar']));
  1114. }
  1115. /**
  1116. * Test adding rules that return error string
  1117. *
  1118. * @group save
  1119. * @return void
  1120. */
  1121. public function testCustomErrorMessageFromRule()
  1122. {
  1123. $entity = new Entity([
  1124. 'name' => 'larry'
  1125. ]);
  1126. $table = TableRegistry::get('Authors');
  1127. $rules = $table->rulesChecker();
  1128. $rules->add(function () {
  1129. return 'So much nope';
  1130. }, ['errorField' => 'name']);
  1131. $this->assertFalse($table->save($entity));
  1132. $this->assertEquals(['So much nope'], $entity->errors('name'));
  1133. }
  1134. /**
  1135. * Test adding rules with no errorField do not accept strings
  1136. *
  1137. * @group save
  1138. * @return void
  1139. */
  1140. public function testCustomErrorMessageFromRuleNoErrorField()
  1141. {
  1142. $entity = new Entity([
  1143. 'name' => 'larry'
  1144. ]);
  1145. $table = TableRegistry::get('Authors');
  1146. $rules = $table->rulesChecker();
  1147. $rules->add(function () {
  1148. return 'So much nope';
  1149. });
  1150. $this->assertFalse($table->save($entity));
  1151. $this->assertEmpty($entity->errors());
  1152. }
  1153. /**
  1154. * Tests that using existsIn for a hasMany association will not be called
  1155. * as the foreign key for the association was automatically validated already.
  1156. *
  1157. * @group save
  1158. * @return void
  1159. */
  1160. public function testAvoidExistsInOnAutomaticSaving()
  1161. {
  1162. $entity = new \Cake\ORM\Entity([
  1163. 'name' => 'Jose'
  1164. ]);
  1165. $entity->articles = [
  1166. new \Cake\ORM\Entity([
  1167. 'title' => '1',
  1168. 'body' => 'A body'
  1169. ]),
  1170. new \Cake\ORM\Entity([
  1171. 'title' => 'Another Title',
  1172. 'body' => 'Another body'
  1173. ])
  1174. ];
  1175. $table = TableRegistry::get('authors');
  1176. $table->hasMany('articles');
  1177. $table->association('articles')->belongsTo('authors');
  1178. $checker = $table->association('articles')->target()->rulesChecker();
  1179. $checker->add(function ($entity, $options) use ($checker) {
  1180. $rule = $checker->existsIn('author_id', 'authors');
  1181. $id = $entity->author_id;
  1182. $entity->author_id = 5000;
  1183. $result = $rule($entity, $options);
  1184. $this->assertTrue($result);
  1185. $entity->author_id = $id;
  1186. return true;
  1187. });
  1188. $this->assertSame($entity, $table->save($entity));
  1189. }
  1190. /**
  1191. * Tests the existsIn domain rule respects the conditions set for the associations
  1192. *
  1193. * @group save
  1194. * @return void
  1195. */
  1196. public function testExistsInDomainRuleWithAssociationConditions()
  1197. {
  1198. $entity = new Entity([
  1199. 'title' => 'An Article',
  1200. 'author_id' => 1
  1201. ]);
  1202. $table = TableRegistry::get('Articles');
  1203. $table->belongsTo('Authors', [
  1204. 'conditions' => ['Authors.name !=' => 'mariano']
  1205. ]);
  1206. $rules = $table->rulesChecker();
  1207. $rules->add($rules->existsIn('author_id', 'Authors'));
  1208. $this->assertFalse($table->save($entity));
  1209. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  1210. }
  1211. /**
  1212. * Tests that associated items have a count of X.
  1213. *
  1214. * @return void
  1215. */
  1216. public function testCountOfAssociatedItems()
  1217. {
  1218. $entity = new \Cake\ORM\Entity([
  1219. 'title' => 'A Title',
  1220. 'body' => 'A body'
  1221. ]);
  1222. $entity->tags = [
  1223. new \Cake\ORM\Entity([
  1224. 'name' => 'Something New'
  1225. ]),
  1226. new \Cake\ORM\Entity([
  1227. 'name' => '100'
  1228. ])
  1229. ];
  1230. TableRegistry::get('ArticlesTags');
  1231. $table = TableRegistry::get('articles');
  1232. $table->belongsToMany('tags');
  1233. $rules = $table->rulesChecker();
  1234. $rules->add($rules->validCount('tags', 3));
  1235. $this->assertFalse($table->save($entity));
  1236. $this->assertEquals($entity->errors(), [
  1237. 'tags' => [
  1238. '_validCount' => 'The count does not match >3'
  1239. ]
  1240. ]);
  1241. // Testing that undesired types fail
  1242. $entity->tags = null;
  1243. $this->assertFalse($table->save($entity));
  1244. $entity->tags = new \stdClass();
  1245. $this->assertFalse($table->save($entity));
  1246. $entity->tags = 'string';
  1247. $this->assertFalse($table->save($entity));
  1248. $entity->tags = 123456;
  1249. $this->assertFalse($table->save($entity));
  1250. $entity->tags = 0.512;
  1251. $this->assertFalse($table->save($entity));
  1252. }
  1253. }