RulesCheckerIntegrationTest.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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\TableRegistry;
  18. use Cake\TestSuite\TestCase;
  19. /**
  20. * Tests the integration between the ORM and the domain checker
  21. */
  22. class RulesCheckerIntegrationTest extends TestCase
  23. {
  24. /**
  25. * Fixtures to be loaded
  26. *
  27. * @var array
  28. */
  29. public $fixtures = [
  30. 'core.articles', 'core.articles_tags', 'core.authors', 'core.tags',
  31. 'core.special_tags', 'core.categories'
  32. ];
  33. /**
  34. * Tear down
  35. *
  36. * @return void
  37. */
  38. public function tearDown()
  39. {
  40. parent::tearDown();
  41. TableRegistry::clear();
  42. }
  43. /**
  44. * Tests saving belongsTo association and get a validation error
  45. *
  46. * @group save
  47. * @return void
  48. */
  49. public function testsSaveBelongsToWithValidationError()
  50. {
  51. $entity = new Entity([
  52. 'title' => 'A Title',
  53. 'body' => 'A body'
  54. ]);
  55. $entity->author = new Entity([
  56. 'name' => 'Jose'
  57. ]);
  58. $table = TableRegistry::get('articles');
  59. $table->belongsTo('authors');
  60. $table->association('authors')
  61. ->target()
  62. ->rulesChecker()
  63. ->add(
  64. function (Entity $author, array $options) use ($table) {
  65. $this->assertSame($options['repository'], $table->association('authors')->target());
  66. return false;
  67. },
  68. ['errorField' => 'name', 'message' => 'This is an error']
  69. );
  70. $this->assertFalse($table->save($entity));
  71. $this->assertTrue($entity->isNew());
  72. $this->assertTrue($entity->author->isNew());
  73. $this->assertNull($entity->get('author_id'));
  74. $this->assertNotEmpty($entity->author->errors('name'));
  75. $this->assertEquals(['This is an error'], $entity->author->errors('name'));
  76. }
  77. /**
  78. * Tests saving hasOne association and returning a validation error will
  79. * abort the saving process
  80. *
  81. * @group save
  82. * @return void
  83. */
  84. public function testSaveHasOneWithValidationError()
  85. {
  86. $entity = new \Cake\ORM\Entity([
  87. 'name' => 'Jose'
  88. ]);
  89. $entity->article = new \Cake\ORM\Entity([
  90. 'title' => 'A Title',
  91. 'body' => 'A body'
  92. ]);
  93. $table = TableRegistry::get('authors');
  94. $table->hasOne('articles');
  95. $table->association('articles')
  96. ->target()
  97. ->rulesChecker()
  98. ->add(
  99. function (Entity $entity) {
  100. return false;
  101. },
  102. ['errorField' => 'title', 'message' => 'This is an error']
  103. );
  104. $this->assertFalse($table->save($entity));
  105. $this->assertTrue($entity->isNew());
  106. $this->assertTrue($entity->article->isNew());
  107. $this->assertNull($entity->article->id);
  108. $this->assertNull($entity->article->get('author_id'));
  109. $this->assertFalse($entity->article->dirty('author_id'));
  110. $this->assertNotEmpty($entity->article->errors('title'));
  111. $this->assertSame('A Title', $entity->article->invalid('title'));
  112. }
  113. /**
  114. * Tests saving multiple entities in a hasMany association and getting and
  115. * error while saving one of them. It should abort all the save operation
  116. * when options are set to defaults
  117. *
  118. * @return void
  119. */
  120. public function testSaveHasManyWithErrorsAtomic()
  121. {
  122. $entity = new \Cake\ORM\Entity([
  123. 'name' => 'Jose'
  124. ]);
  125. $entity->articles = [
  126. new \Cake\ORM\Entity([
  127. 'title' => '1',
  128. 'body' => 'A body'
  129. ]),
  130. new \Cake\ORM\Entity([
  131. 'title' => 'Another Title',
  132. 'body' => 'Another body'
  133. ])
  134. ];
  135. $table = TableRegistry::get('authors');
  136. $table->hasMany('articles');
  137. $table->association('articles')
  138. ->target()
  139. ->rulesChecker()
  140. ->add(
  141. function (Entity $entity, $options) use ($table) {
  142. $this->assertSame($table, $options['_sourceTable']);
  143. return $entity->title === '1';
  144. },
  145. ['errorField' => 'title', 'message' => 'This is an error']
  146. );
  147. $this->assertFalse($table->save($entity));
  148. $this->assertTrue($entity->isNew());
  149. $this->assertTrue($entity->articles[0]->isNew());
  150. $this->assertTrue($entity->articles[1]->isNew());
  151. $this->assertNull($entity->articles[0]->id);
  152. $this->assertNull($entity->articles[1]->id);
  153. $this->assertNull($entity->articles[0]->author_id);
  154. $this->assertNull($entity->articles[1]->author_id);
  155. $this->assertEmpty($entity->articles[0]->errors());
  156. $this->assertNotEmpty($entity->articles[1]->errors());
  157. }
  158. /**
  159. * Tests that it is possible to continue saving hasMany associations
  160. * even if any of the records fail validation when atomic is set
  161. * to false
  162. *
  163. * @return void
  164. */
  165. public function testSaveHasManyWithErrorsNonAtomic()
  166. {
  167. $entity = new \Cake\ORM\Entity([
  168. 'name' => 'Jose'
  169. ]);
  170. $entity->articles = [
  171. new \Cake\ORM\Entity([
  172. 'title' => 'A title',
  173. 'body' => 'A body'
  174. ]),
  175. new \Cake\ORM\Entity([
  176. 'title' => '1',
  177. 'body' => 'Another body'
  178. ])
  179. ];
  180. $table = TableRegistry::get('authors');
  181. $table->hasMany('articles');
  182. $table->association('articles')
  183. ->target()
  184. ->rulesChecker()
  185. ->add(
  186. function (Entity $article) {
  187. return is_numeric($article->title);
  188. },
  189. ['errorField' => 'title', 'message' => 'This is an error']
  190. );
  191. $result = $table->save($entity, ['atomic' => false]);
  192. $this->assertSame($entity, $result);
  193. $this->assertFalse($entity->isNew());
  194. $this->assertTrue($entity->articles[0]->isNew());
  195. $this->assertFalse($entity->articles[1]->isNew());
  196. $this->assertEquals(4, $entity->articles[1]->id);
  197. $this->assertNull($entity->articles[0]->id);
  198. $this->assertNotEmpty($entity->articles[0]->errors('title'));
  199. }
  200. /**
  201. * Tests saving belongsToMany records with a validation error in a joint entity
  202. *
  203. * @group save
  204. * @return void
  205. */
  206. public function testSaveBelongsToManyWithValidationErrorInJointEntity()
  207. {
  208. $entity = new \Cake\ORM\Entity([
  209. 'title' => 'A Title',
  210. 'body' => 'A body'
  211. ]);
  212. $entity->tags = [
  213. new \Cake\ORM\Entity([
  214. 'name' => 'Something New'
  215. ]),
  216. new \Cake\ORM\Entity([
  217. 'name' => '100'
  218. ])
  219. ];
  220. $table = TableRegistry::get('articles');
  221. $table->belongsToMany('tags');
  222. $table->association('tags')
  223. ->junction()
  224. ->rulesChecker()
  225. ->add(function (Entity $entity) {
  226. return $entity->article_id > 4;
  227. });
  228. $this->assertFalse($table->save($entity));
  229. $this->assertTrue($entity->isNew());
  230. $this->assertTrue($entity->tags[0]->isNew());
  231. $this->assertTrue($entity->tags[1]->isNew());
  232. $this->assertNull($entity->tags[0]->id);
  233. $this->assertNull($entity->tags[1]->id);
  234. $this->assertNull($entity->tags[0]->_joinData);
  235. $this->assertNull($entity->tags[1]->_joinData);
  236. }
  237. /**
  238. * Tests saving belongsToMany records with a validation error in a joint entity
  239. * and atomic set to false
  240. *
  241. * @group save
  242. * @return void
  243. */
  244. public function testSaveBelongsToManyWithValidationErrorInJointEntityNonAtomic()
  245. {
  246. $entity = new \Cake\ORM\Entity([
  247. 'title' => 'A Title',
  248. 'body' => 'A body'
  249. ]);
  250. $entity->tags = [
  251. new \Cake\ORM\Entity([
  252. 'name' => 'Something New'
  253. ]),
  254. new \Cake\ORM\Entity([
  255. 'name' => 'New one'
  256. ])
  257. ];
  258. $table = TableRegistry::get('articles');
  259. $table->belongsToMany('tags');
  260. $table->association('tags')
  261. ->junction()
  262. ->rulesChecker()
  263. ->add(function (Entity $entity) {
  264. return $entity->tag_id > 4;
  265. });
  266. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  267. $this->assertFalse($entity->isNew());
  268. $this->assertFalse($entity->tags[0]->isNew());
  269. $this->assertFalse($entity->tags[1]->isNew());
  270. $this->assertEquals(4, $entity->tags[0]->id);
  271. $this->assertEquals(5, $entity->tags[1]->id);
  272. $this->assertTrue($entity->tags[0]->_joinData->isNew());
  273. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  274. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  275. }
  276. /**
  277. * Test adding rule with name
  278. *
  279. * @group save
  280. * @return void
  281. */
  282. public function testAddingRuleWithName()
  283. {
  284. $entity = new Entity([
  285. 'name' => 'larry'
  286. ]);
  287. $table = TableRegistry::get('Authors');
  288. $rules = $table->rulesChecker();
  289. $rules->add(
  290. function () {
  291. return false;
  292. },
  293. 'ruleName',
  294. ['errorField' => 'name']
  295. );
  296. $this->assertFalse($table->save($entity));
  297. $this->assertEquals(['ruleName' => 'invalid'], $entity->errors('name'));
  298. }
  299. /**
  300. * Tests the isUnique domain rule
  301. *
  302. * @group save
  303. * @return void
  304. */
  305. public function testIsUniqueDomainRule()
  306. {
  307. $entity = new Entity([
  308. 'name' => 'larry'
  309. ]);
  310. $table = TableRegistry::get('Authors');
  311. $rules = $table->rulesChecker();
  312. $rules->add($rules->isUnique(['name']));
  313. $this->assertFalse($table->save($entity));
  314. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('name'));
  315. $entity->name = 'jose';
  316. $this->assertSame($entity, $table->save($entity));
  317. $entity = $table->get(1);
  318. $entity->dirty('name', true);
  319. $this->assertSame($entity, $table->save($entity));
  320. }
  321. /**
  322. * Tests isUnique with multiple fields
  323. *
  324. * @group save
  325. * @return void
  326. */
  327. public function testIsUniqueMultipleFields()
  328. {
  329. $entity = new Entity([
  330. 'author_id' => 1,
  331. 'title' => 'First Article'
  332. ]);
  333. $table = TableRegistry::get('Articles');
  334. $rules = $table->rulesChecker();
  335. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  336. $this->assertFalse($table->save($entity));
  337. $this->assertEquals(['title' => ['_isUnique' => 'Nope']], $entity->errors());
  338. $entity->clean();
  339. $entity->author_id = 2;
  340. $this->assertSame($entity, $table->save($entity));
  341. }
  342. /**
  343. * Tests isUnique with allowMultipleNulls
  344. *
  345. * @group save
  346. * @return void
  347. */
  348. public function testIsUniqueAllowMultipleNulls()
  349. {
  350. $entity = new Entity([
  351. 'article_id' => 11,
  352. 'tag_id' => 11,
  353. 'author_id' => null
  354. ]);
  355. $table = TableRegistry::get('SpecialTags');
  356. $rules = $table->rulesChecker();
  357. $rules->add($rules->isUnique(['author_id']), ['allowMultipleNulls' => false]);
  358. $this->assertFalse($table->save($entity));
  359. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('author_id'));
  360. $entity->author_id = 11;
  361. $this->assertSame($entity, $table->save($entity));
  362. $entity = $table->get(1);
  363. $entity->dirty('author_id', true);
  364. $this->assertSame($entity, $table->save($entity));
  365. }
  366. /**
  367. * Tests isUnique with multiple fields and allowMultipleNulls
  368. *
  369. * @group save
  370. * @return void
  371. */
  372. public function testIsUniqueMultipleFieldsAllowMultipleNulls()
  373. {
  374. $entity = new Entity([
  375. 'article_id' => 10,
  376. 'tag_id' => 12,
  377. 'author_id' => null
  378. ]);
  379. $table = TableRegistry::get('SpecialTags');
  380. $rules = $table->rulesChecker();
  381. $rules->add($rules->isUnique(['author_id', 'article_id'], 'Nope'), ['allowMultipleNulls' => false]);
  382. $this->assertFalse($table->save($entity));
  383. $this->assertEquals(['author_id' => ['_isUnique' => 'Nope']], $entity->errors());
  384. $entity->clean();
  385. $entity->article_id = 10;
  386. $entity->tag_id = 12;
  387. $entity->author_id = 12;
  388. $this->assertSame($entity, $table->save($entity));
  389. }
  390. /**
  391. * Tests isUnique with multiple fields and a nulled field.
  392. *
  393. * @group save
  394. * @return void
  395. */
  396. public function testIsUniqueMultipleFieldsOneIsNull()
  397. {
  398. $entity = new Entity([
  399. 'author_id' => null,
  400. 'title' => 'First Article'
  401. ]);
  402. $table = TableRegistry::get('Articles');
  403. $rules = $table->rulesChecker();
  404. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  405. $this->assertSame($entity, $table->save($entity));
  406. // Make a duplicate
  407. $entity = new Entity([
  408. 'author_id' => null,
  409. 'title' => 'First Article'
  410. ]);
  411. $this->assertFalse($table->save($entity));
  412. $this->assertEquals(['title' => ['_isUnique' => 'Nope']], $entity->errors());
  413. }
  414. /**
  415. * Tests the existsIn domain rule
  416. *
  417. * @group save
  418. * @return void
  419. */
  420. public function testExistsInDomainRule()
  421. {
  422. $entity = new Entity([
  423. 'title' => 'An Article',
  424. 'author_id' => 500
  425. ]);
  426. $table = TableRegistry::get('Articles');
  427. $table->belongsTo('Authors');
  428. $rules = $table->rulesChecker();
  429. $rules->add($rules->existsIn('author_id', 'Authors'));
  430. $this->assertFalse($table->save($entity));
  431. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  432. }
  433. /**
  434. * Tests the existsIn domain rule when passing an object
  435. *
  436. * @group save
  437. * @return void
  438. */
  439. public function testExistsInDomainRuleWithObject()
  440. {
  441. $entity = new Entity([
  442. 'title' => 'An Article',
  443. 'author_id' => 500
  444. ]);
  445. $table = TableRegistry::get('Articles');
  446. $rules = $table->rulesChecker();
  447. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  448. $this->assertFalse($table->save($entity));
  449. $this->assertEquals(['_existsIn' => 'Nope'], $entity->errors('author_id'));
  450. }
  451. /**
  452. * ExistsIn uses the schema to verify that nullable fields are ok.
  453. *
  454. * @return void
  455. */
  456. public function testExistsInNullValue()
  457. {
  458. $entity = new Entity([
  459. 'title' => 'An Article',
  460. 'author_id' => null
  461. ]);
  462. $table = TableRegistry::get('Articles');
  463. $table->belongsTo('Authors');
  464. $rules = $table->rulesChecker();
  465. $rules->add($rules->existsIn('author_id', 'Authors'));
  466. $this->assertEquals($entity, $table->save($entity));
  467. $this->assertEquals([], $entity->errors('author_id'));
  468. }
  469. /**
  470. * Test ExistsIn on not dirty field in new Entity
  471. *
  472. * @return void
  473. */
  474. public function testExistsInNotNullValue()
  475. {
  476. $entity = new Entity([
  477. 'name' => 'A Category',
  478. ]);
  479. $table = TableRegistry::get('Categories');
  480. $table->belongsTo('Categories', [
  481. 'foreignKey' => 'parent_id',
  482. 'bindingKey' => 'id',
  483. ]);
  484. $rules = $table->rulesChecker();
  485. $rules->add($rules->existsIn('parent_id', 'Categories'));
  486. $this->assertFalse($table->save($entity));
  487. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('parent_id'));
  488. }
  489. /**
  490. * Tests exists in uses the bindingKey of the association
  491. *
  492. * @return void
  493. */
  494. public function testExistsInWithBindingKey()
  495. {
  496. $entity = new Entity([
  497. 'title' => 'An Article',
  498. ]);
  499. $table = TableRegistry::get('Articles');
  500. $table->belongsTo('Authors', [
  501. 'bindingKey' => 'name',
  502. 'foreignKey' => 'title'
  503. ]);
  504. $rules = $table->rulesChecker();
  505. $rules->add($rules->existsIn('title', 'Authors'));
  506. $this->assertFalse($table->save($entity));
  507. $this->assertNotEmpty($entity->errors('title'));
  508. $entity->clean();
  509. $entity->title = 'larry';
  510. $this->assertEquals($entity, $table->save($entity));
  511. }
  512. /**
  513. * Tests existsIn with invalid associations
  514. *
  515. * @group save
  516. * @expectedException RuntimeException
  517. * @expectedExceptionMessage ExistsIn rule for 'author_id' is invalid. The 'NotValid' association is not defined.
  518. * @return void
  519. */
  520. public function testExistsInInvalidAssociation()
  521. {
  522. $entity = new Entity([
  523. 'title' => 'An Article',
  524. 'author_id' => 500
  525. ]);
  526. $table = TableRegistry::get('Articles');
  527. $table->belongsTo('Authors');
  528. $rules = $table->rulesChecker();
  529. $rules->add($rules->existsIn('author_id', 'NotValid'));
  530. $table->save($entity);
  531. }
  532. /**
  533. * Tests the checkRules save option
  534. *
  535. * @group save
  536. * @return void
  537. */
  538. public function testSkipRulesChecking()
  539. {
  540. $entity = new Entity([
  541. 'title' => 'An Article',
  542. 'author_id' => 500
  543. ]);
  544. $table = TableRegistry::get('Articles');
  545. $rules = $table->rulesChecker();
  546. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  547. $this->assertSame($entity, $table->save($entity, ['checkRules' => false]));
  548. }
  549. /**
  550. * Tests the beforeRules event
  551. *
  552. * @group save
  553. * @return void
  554. */
  555. public function testUseBeforeRules()
  556. {
  557. $entity = new Entity([
  558. 'title' => 'An Article',
  559. 'author_id' => 500
  560. ]);
  561. $table = TableRegistry::get('Articles');
  562. $rules = $table->rulesChecker();
  563. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  564. $table->eventManager()->attach(
  565. function ($event, Entity $entity, \ArrayObject $options, $operation) {
  566. $this->assertEquals(
  567. [
  568. 'atomic' => true,
  569. 'associated' => true,
  570. 'checkRules' => true,
  571. 'checkExisting' => true,
  572. '_primary' => true,
  573. ],
  574. $options->getArrayCopy()
  575. );
  576. $this->assertEquals('create', $operation);
  577. $event->stopPropagation();
  578. return true;
  579. },
  580. 'Model.beforeRules'
  581. );
  582. $this->assertSame($entity, $table->save($entity));
  583. }
  584. /**
  585. * Tests the afterRules event
  586. *
  587. * @group save
  588. * @return void
  589. */
  590. public function testUseAfterRules()
  591. {
  592. $entity = new Entity([
  593. 'title' => 'An Article',
  594. 'author_id' => 500
  595. ]);
  596. $table = TableRegistry::get('Articles');
  597. $rules = $table->rulesChecker();
  598. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  599. $table->eventManager()->attach(
  600. function ($event, Entity $entity, \ArrayObject $options, $result, $operation) {
  601. $this->assertEquals(
  602. [
  603. 'atomic' => true,
  604. 'associated' => true,
  605. 'checkRules' => true,
  606. 'checkExisting' => true,
  607. '_primary' => true,
  608. ],
  609. $options->getArrayCopy()
  610. );
  611. $this->assertEquals('create', $operation);
  612. $this->assertFalse($result);
  613. $event->stopPropagation();
  614. return true;
  615. },
  616. 'Model.afterRules'
  617. );
  618. $this->assertSame($entity, $table->save($entity));
  619. }
  620. /**
  621. * Tests that rules can be changed using the buildRules event
  622. *
  623. * @group save
  624. * @return void
  625. */
  626. public function testUseBuildRulesEvent()
  627. {
  628. $entity = new Entity([
  629. 'title' => 'An Article',
  630. 'author_id' => 500
  631. ]);
  632. $table = TableRegistry::get('Articles');
  633. $table->eventManager()->attach(function ($event, $rules) {
  634. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  635. }, 'Model.buildRules');
  636. $this->assertFalse($table->save($entity));
  637. }
  638. /**
  639. * Tests isUnique with untouched fields
  640. *
  641. * @group save
  642. * @return void
  643. */
  644. public function testIsUniqueWithCleanFields()
  645. {
  646. $table = TableRegistry::get('Articles');
  647. $entity = $table->get(1);
  648. $rules = $table->rulesChecker();
  649. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  650. $entity->body = 'Foo';
  651. $this->assertSame($entity, $table->save($entity));
  652. $entity->title = 'Third Article';
  653. $this->assertFalse($table->save($entity));
  654. }
  655. /**
  656. * Tests isUnique rule with coflicting columns
  657. *
  658. * @group save
  659. * @return void
  660. */
  661. public function testIsUniqueAliasPrefix()
  662. {
  663. $entity = new Entity([
  664. 'title' => 'An Article',
  665. 'author_id' => 1
  666. ]);
  667. $table = TableRegistry::get('Articles');
  668. $table->belongsTo('Authors');
  669. $rules = $table->rulesChecker();
  670. $rules->add($rules->isUnique(['author_id']));
  671. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  672. $query->leftJoin(['a2' => 'authors']);
  673. });
  674. $this->assertFalse($table->save($entity));
  675. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('author_id'));
  676. }
  677. /**
  678. * Tests the existsIn rule when passing non dirty fields
  679. *
  680. * @group save
  681. * @return void
  682. */
  683. public function testExistsInWithCleanFields()
  684. {
  685. $table = TableRegistry::get('Articles');
  686. $table->belongsTo('Authors');
  687. $rules = $table->rulesChecker();
  688. $rules->add($rules->existsIn('author_id', 'Authors'));
  689. $entity = $table->get(1);
  690. $entity->title = 'Foo';
  691. $entity->author_id = 1000;
  692. $entity->dirty('author_id', false);
  693. $this->assertSame($entity, $table->save($entity));
  694. }
  695. /**
  696. * Tests the existsIn with coflicting columns
  697. *
  698. * @group save
  699. * @return void
  700. */
  701. public function testExistsInAliasPrefix()
  702. {
  703. $entity = new Entity([
  704. 'title' => 'An Article',
  705. 'author_id' => 500
  706. ]);
  707. $table = TableRegistry::get('Articles');
  708. $table->belongsTo('Authors');
  709. $rules = $table->rulesChecker();
  710. $rules->add($rules->existsIn('author_id', 'Authors'));
  711. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  712. $query->leftJoin(['a2' => 'authors']);
  713. });
  714. $this->assertFalse($table->save($entity));
  715. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  716. }
  717. /**
  718. * Tests that using an array in existsIn() sets the error message correctly
  719. *
  720. * @return
  721. */
  722. public function testExistsInErrorWithArrayField()
  723. {
  724. $entity = new Entity([
  725. 'title' => 'An Article',
  726. 'author_id' => 500
  727. ]);
  728. $table = TableRegistry::get('Articles');
  729. $table->belongsTo('Authors');
  730. $rules = $table->rulesChecker();
  731. $rules->add($rules->existsIn(['author_id'], 'Authors'));
  732. $this->assertFalse($table->save($entity));
  733. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  734. }
  735. /**
  736. * Tests using rules to prevent delete operations
  737. *
  738. * @group delete
  739. * @return void
  740. */
  741. public function testDeleteRules()
  742. {
  743. $table = TableRegistry::get('Articles');
  744. $rules = $table->rulesChecker();
  745. $rules->addDelete(function ($entity) {
  746. return false;
  747. });
  748. $entity = $table->get(1);
  749. $this->assertFalse($table->delete($entity));
  750. }
  751. /**
  752. * Checks that it is possible to pass custom options to rules when saving
  753. *
  754. * @group save
  755. * @return void
  756. */
  757. public function testCustomOptionsPassingSave()
  758. {
  759. $entity = new Entity([
  760. 'name' => 'jose'
  761. ]);
  762. $table = TableRegistry::get('Authors');
  763. $rules = $table->rulesChecker();
  764. $rules->add(function ($entity, $options) {
  765. $this->assertEquals('bar', $options['foo']);
  766. $this->assertEquals('option', $options['another']);
  767. return false;
  768. }, ['another' => 'option']);
  769. $this->assertFalse($table->save($entity, ['foo' => 'bar']));
  770. }
  771. /**
  772. * Tests passing custom options to rules from delete
  773. *
  774. * @group delete
  775. * @return void
  776. */
  777. public function testCustomOptionsPassingDelete()
  778. {
  779. $table = TableRegistry::get('Articles');
  780. $rules = $table->rulesChecker();
  781. $rules->addDelete(function ($entity, $options) {
  782. $this->assertEquals('bar', $options['foo']);
  783. $this->assertEquals('option', $options['another']);
  784. return false;
  785. }, ['another' => 'option']);
  786. $entity = $table->get(1);
  787. $this->assertFalse($table->delete($entity, ['foo' => 'bar']));
  788. }
  789. /**
  790. * Test adding rules that return error string
  791. *
  792. * @group save
  793. * @return void
  794. */
  795. public function testCustomErrorMessageFromRule()
  796. {
  797. $entity = new Entity([
  798. 'name' => 'larry'
  799. ]);
  800. $table = TableRegistry::get('Authors');
  801. $rules = $table->rulesChecker();
  802. $rules->add(function () {
  803. return 'So much nope';
  804. }, ['errorField' => 'name']);
  805. $this->assertFalse($table->save($entity));
  806. $this->assertEquals(['So much nope'], $entity->errors('name'));
  807. }
  808. /**
  809. * Test adding rules with no errorField do not accept strings
  810. *
  811. * @group save
  812. * @return void
  813. */
  814. public function testCustomErrorMessageFromRuleNoErrorField()
  815. {
  816. $entity = new Entity([
  817. 'name' => 'larry'
  818. ]);
  819. $table = TableRegistry::get('Authors');
  820. $rules = $table->rulesChecker();
  821. $rules->add(function () {
  822. return 'So much nope';
  823. });
  824. $this->assertFalse($table->save($entity));
  825. $this->assertEmpty($entity->errors());
  826. }
  827. /**
  828. * Tests that using existsIn for a hasMany association will not be called
  829. * as the foreign key for the association was automatically validated already.
  830. *
  831. * @group save
  832. * @return void
  833. */
  834. public function testAvoidExistsInOnAutomaticSaving()
  835. {
  836. $entity = new \Cake\ORM\Entity([
  837. 'name' => 'Jose'
  838. ]);
  839. $entity->articles = [
  840. new \Cake\ORM\Entity([
  841. 'title' => '1',
  842. 'body' => 'A body'
  843. ]),
  844. new \Cake\ORM\Entity([
  845. 'title' => 'Another Title',
  846. 'body' => 'Another body'
  847. ])
  848. ];
  849. $table = TableRegistry::get('authors');
  850. $table->hasMany('articles');
  851. $table->association('articles')->belongsTo('authors');
  852. $checker = $table->association('articles')->target()->rulesChecker();
  853. $checker->add(function ($entity, $options) use ($checker) {
  854. $rule = $checker->existsIn('author_id', 'authors');
  855. $id = $entity->author_id;
  856. $entity->author_id = 5000;
  857. $result = $rule($entity, $options);
  858. $this->assertTrue($result);
  859. $entity->author_id = $id;
  860. return true;
  861. });
  862. $this->assertSame($entity, $table->save($entity));
  863. }
  864. /**
  865. * Tests the existsIn domain rule respects the conditions set for the associations
  866. *
  867. * @group save
  868. * @return void
  869. */
  870. public function testExistsInDomainRuleWithAssociationConditions()
  871. {
  872. $entity = new Entity([
  873. 'title' => 'An Article',
  874. 'author_id' => 1
  875. ]);
  876. $table = TableRegistry::get('Articles');
  877. $table->belongsTo('Authors', [
  878. 'conditions' => ['Authors.name !=' => 'mariano']
  879. ]);
  880. $rules = $table->rulesChecker();
  881. $rules->add($rules->existsIn('author_id', 'Authors'));
  882. $this->assertFalse($table->save($entity));
  883. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  884. }
  885. /**
  886. * Tests that associated items have a count of X.
  887. *
  888. * @return void
  889. */
  890. public function testCountOfAssociatedItems()
  891. {
  892. $entity = new \Cake\ORM\Entity([
  893. 'title' => 'A Title',
  894. 'body' => 'A body'
  895. ]);
  896. $entity->tags = [
  897. new \Cake\ORM\Entity([
  898. 'name' => 'Something New'
  899. ]),
  900. new \Cake\ORM\Entity([
  901. 'name' => '100'
  902. ])
  903. ];
  904. TableRegistry::get('ArticlesTags');
  905. $table = TableRegistry::get('articles');
  906. $table->belongsToMany('tags');
  907. $rules = $table->rulesChecker();
  908. $rules->add($rules->validCount('tags', 3));
  909. $this->assertFalse($table->save($entity));
  910. $this->assertEquals($entity->errors(), [
  911. 'tags' => [
  912. '_validCount' => 'The count does not match >3'
  913. ]
  914. ]);
  915. // Testing that undesired types fail
  916. $entity->tags = null;
  917. $this->assertFalse($table->save($entity));
  918. $entity->tags = new \stdClass();
  919. $this->assertFalse($table->save($entity));
  920. $entity->tags = 'string';
  921. $this->assertFalse($table->save($entity));
  922. $entity->tags = 123456;
  923. $this->assertFalse($table->save($entity));
  924. $entity->tags = 0.512;
  925. $this->assertFalse($table->save($entity));
  926. }
  927. }