RulesCheckerIntegrationTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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'
  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. * Tests the isUnique domain rule
  302. *
  303. * @group save
  304. * @return void
  305. */
  306. public function testIsUniqueDomainRule()
  307. {
  308. $entity = new Entity([
  309. 'name' => 'larry'
  310. ]);
  311. $table = TableRegistry::get('Authors');
  312. $rules = $table->rulesChecker();
  313. $rules->add($rules->isUnique(['name']));
  314. $this->assertFalse($table->save($entity));
  315. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('name'));
  316. $entity->name = 'jose';
  317. $this->assertSame($entity, $table->save($entity));
  318. $entity = $table->get(1);
  319. $entity->dirty('name', true);
  320. $this->assertSame($entity, $table->save($entity));
  321. }
  322. /**
  323. * Tests isUnique with multiple fields
  324. *
  325. * @group save
  326. * @return void
  327. */
  328. public function testIsUniqueMultipleFields()
  329. {
  330. $entity = new Entity([
  331. 'author_id' => 1,
  332. 'title' => 'First Article'
  333. ]);
  334. $table = TableRegistry::get('Articles');
  335. $rules = $table->rulesChecker();
  336. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  337. $this->assertFalse($table->save($entity));
  338. $this->assertEquals(['title' => ['_isUnique' => 'Nope']], $entity->errors());
  339. $entity->clean();
  340. $entity->author_id = 2;
  341. $this->assertSame($entity, $table->save($entity));
  342. }
  343. /**
  344. * Tests isUnique with allowMultipleNulls
  345. *
  346. * @group save
  347. * @return void
  348. */
  349. public function testIsUniqueAllowMultipleNulls()
  350. {
  351. $entity = new Entity([
  352. 'article_id' => 11,
  353. 'tag_id' => 11,
  354. 'author_id' => null
  355. ]);
  356. $table = TableRegistry::get('SpecialTags');
  357. $rules = $table->rulesChecker();
  358. $rules->add($rules->isUnique(['author_id'], [
  359. 'allowMultipleNulls' => false,
  360. 'message' => 'All fields are required'
  361. ]));
  362. $this->assertFalse($table->save($entity));
  363. $this->assertEquals(['_isUnique' => 'All fields are required'], $entity->errors('author_id'));
  364. $entity->author_id = 11;
  365. $this->assertSame($entity, $table->save($entity));
  366. $entity = $table->get(1);
  367. $entity->dirty('author_id', true);
  368. $this->assertSame($entity, $table->save($entity));
  369. }
  370. /**
  371. * Tests isUnique with multiple fields and allowMultipleNulls
  372. *
  373. * @group save
  374. * @return void
  375. */
  376. public function testIsUniqueMultipleFieldsAllowMultipleNulls()
  377. {
  378. $entity = new Entity([
  379. 'article_id' => 10,
  380. 'tag_id' => 12,
  381. 'author_id' => null
  382. ]);
  383. $table = TableRegistry::get('SpecialTags');
  384. $rules = $table->rulesChecker();
  385. $rules->add($rules->isUnique(['author_id', 'article_id'], [
  386. 'allowMultipleNulls' => false,
  387. 'message' => 'Nope'
  388. ]));
  389. $this->assertFalse($table->save($entity));
  390. $this->assertEquals(['author_id' => ['_isUnique' => 'Nope']], $entity->errors());
  391. $entity->clean();
  392. $entity->article_id = 10;
  393. $entity->tag_id = 12;
  394. $entity->author_id = 12;
  395. $this->assertSame($entity, $table->save($entity));
  396. }
  397. /**
  398. * Tests isUnique with multiple fields emulates SQL UNIQUE keys
  399. *
  400. * @group save
  401. * @return void
  402. */
  403. public function testIsUniqueMultipleFieldsOneIsNull()
  404. {
  405. $entity = new Entity([
  406. 'author_id' => null,
  407. 'title' => 'First Article'
  408. ]);
  409. $table = TableRegistry::get('Articles');
  410. $rules = $table->rulesChecker();
  411. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  412. $this->assertSame($entity, $table->save($entity));
  413. // Make a matching record
  414. $entity = new Entity([
  415. 'author_id' => null,
  416. 'title' => 'New Article'
  417. ]);
  418. $this->assertSame($entity, $table->save($entity));
  419. }
  420. /**
  421. * Tests the existsIn domain rule
  422. *
  423. * @group save
  424. * @return void
  425. */
  426. public function testExistsInDomainRule()
  427. {
  428. $entity = new Entity([
  429. 'title' => 'An Article',
  430. 'author_id' => 500
  431. ]);
  432. $table = TableRegistry::get('Articles');
  433. $table->belongsTo('Authors');
  434. $rules = $table->rulesChecker();
  435. $rules->add($rules->existsIn('author_id', 'Authors'));
  436. $this->assertFalse($table->save($entity));
  437. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  438. }
  439. /**
  440. * Tests the existsIn domain rule when passing an object
  441. *
  442. * @group save
  443. * @return void
  444. */
  445. public function testExistsInDomainRuleWithObject()
  446. {
  447. $entity = new Entity([
  448. 'title' => 'An Article',
  449. 'author_id' => 500
  450. ]);
  451. $table = TableRegistry::get('Articles');
  452. $rules = $table->rulesChecker();
  453. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  454. $this->assertFalse($table->save($entity));
  455. $this->assertEquals(['_existsIn' => 'Nope'], $entity->errors('author_id'));
  456. }
  457. /**
  458. * ExistsIn uses the schema to verify that nullable fields are ok.
  459. *
  460. * @return
  461. */
  462. public function testExistsInNullValue()
  463. {
  464. $entity = new Entity([
  465. 'title' => 'An Article',
  466. 'author_id' => null
  467. ]);
  468. $table = TableRegistry::get('Articles');
  469. $table->belongsTo('Authors');
  470. $rules = $table->rulesChecker();
  471. $rules->add($rules->existsIn('author_id', 'Authors'));
  472. $this->assertEquals($entity, $table->save($entity));
  473. $this->assertEquals([], $entity->errors('author_id'));
  474. }
  475. /**
  476. * Test ExistsIn on a new entity that doesn't have the field populated.
  477. *
  478. * This use case is important for saving records and their
  479. * associated belongsTo records in one pass.
  480. *
  481. * @return void
  482. */
  483. public function testExistsInNotNullValueNewEntity()
  484. {
  485. $entity = new Entity([
  486. 'name' => 'A Category',
  487. ]);
  488. $table = TableRegistry::get('Categories');
  489. $table->belongsTo('Categories', [
  490. 'foreignKey' => 'parent_id',
  491. 'bindingKey' => 'id',
  492. ]);
  493. $rules = $table->rulesChecker();
  494. $rules->add($rules->existsIn('parent_id', 'Categories'));
  495. $this->assertTrue($table->checkRules($entity, RulesChecker::CREATE));
  496. $this->assertEmpty($entity->errors('parent_id'));
  497. }
  498. /**
  499. * Tests exists in uses the bindingKey of the association
  500. *
  501. * @return
  502. */
  503. public function testExistsInWithBindingKey()
  504. {
  505. $entity = new Entity([
  506. 'title' => 'An Article',
  507. ]);
  508. $table = TableRegistry::get('Articles');
  509. $table->belongsTo('Authors', [
  510. 'bindingKey' => 'name',
  511. 'foreignKey' => 'title'
  512. ]);
  513. $rules = $table->rulesChecker();
  514. $rules->add($rules->existsIn('title', 'Authors'));
  515. $this->assertFalse($table->save($entity));
  516. $this->assertNotEmpty($entity->errors('title'));
  517. $entity->clean();
  518. $entity->title = 'larry';
  519. $this->assertEquals($entity, $table->save($entity));
  520. }
  521. /**
  522. * Tests existsIn with invalid associations
  523. *
  524. * @group save
  525. * @expectedException RuntimeException
  526. * @expectedExceptionMessage ExistsIn rule for 'author_id' is invalid. The 'NotValid' association is not defined.
  527. * @return void
  528. */
  529. public function testExistsInInvalidAssociation()
  530. {
  531. $entity = new Entity([
  532. 'title' => 'An Article',
  533. 'author_id' => 500
  534. ]);
  535. $table = TableRegistry::get('Articles');
  536. $table->belongsTo('Authors');
  537. $rules = $table->rulesChecker();
  538. $rules->add($rules->existsIn('author_id', 'NotValid'));
  539. $table->save($entity);
  540. }
  541. /**
  542. * Tests the checkRules save option
  543. *
  544. * @group save
  545. * @return void
  546. */
  547. public function testSkipRulesChecking()
  548. {
  549. $entity = new Entity([
  550. 'title' => 'An Article',
  551. 'author_id' => 500
  552. ]);
  553. $table = TableRegistry::get('Articles');
  554. $rules = $table->rulesChecker();
  555. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  556. $this->assertSame($entity, $table->save($entity, ['checkRules' => false]));
  557. }
  558. /**
  559. * Tests the beforeRules event
  560. *
  561. * @group save
  562. * @return void
  563. */
  564. public function testUseBeforeRules()
  565. {
  566. $entity = new Entity([
  567. 'title' => 'An Article',
  568. 'author_id' => 500
  569. ]);
  570. $table = TableRegistry::get('Articles');
  571. $rules = $table->rulesChecker();
  572. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  573. $table->eventManager()->attach(
  574. function ($event, Entity $entity, \ArrayObject $options, $operation) {
  575. $this->assertEquals(
  576. [
  577. 'atomic' => true,
  578. 'associated' => true,
  579. 'checkRules' => true,
  580. 'checkExisting' => true,
  581. '_primary' => true,
  582. ],
  583. $options->getArrayCopy()
  584. );
  585. $this->assertEquals('create', $operation);
  586. $event->stopPropagation();
  587. return true;
  588. },
  589. 'Model.beforeRules'
  590. );
  591. $this->assertSame($entity, $table->save($entity));
  592. }
  593. /**
  594. * Tests the afterRules event
  595. *
  596. * @group save
  597. * @return void
  598. */
  599. public function testUseAfterRules()
  600. {
  601. $entity = new Entity([
  602. 'title' => 'An Article',
  603. 'author_id' => 500
  604. ]);
  605. $table = TableRegistry::get('Articles');
  606. $rules = $table->rulesChecker();
  607. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  608. $table->eventManager()->attach(
  609. function ($event, Entity $entity, \ArrayObject $options, $result, $operation) {
  610. $this->assertEquals(
  611. [
  612. 'atomic' => true,
  613. 'associated' => true,
  614. 'checkRules' => true,
  615. 'checkExisting' => true,
  616. '_primary' => true,
  617. ],
  618. $options->getArrayCopy()
  619. );
  620. $this->assertEquals('create', $operation);
  621. $this->assertFalse($result);
  622. $event->stopPropagation();
  623. return true;
  624. },
  625. 'Model.afterRules'
  626. );
  627. $this->assertSame($entity, $table->save($entity));
  628. }
  629. /**
  630. * Tests that rules can be changed using the buildRules event
  631. *
  632. * @group save
  633. * @return void
  634. */
  635. public function testUseBuildRulesEvent()
  636. {
  637. $entity = new Entity([
  638. 'title' => 'An Article',
  639. 'author_id' => 500
  640. ]);
  641. $table = TableRegistry::get('Articles');
  642. $table->eventManager()->attach(function ($event, $rules) {
  643. $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
  644. }, 'Model.buildRules');
  645. $this->assertFalse($table->save($entity));
  646. }
  647. /**
  648. * Tests isUnique with untouched fields
  649. *
  650. * @group save
  651. * @return void
  652. */
  653. public function testIsUniqueWithCleanFields()
  654. {
  655. $table = TableRegistry::get('Articles');
  656. $entity = $table->get(1);
  657. $rules = $table->rulesChecker();
  658. $rules->add($rules->isUnique(['title', 'author_id'], 'Nope'));
  659. $entity->body = 'Foo';
  660. $this->assertSame($entity, $table->save($entity));
  661. $entity->title = 'Third Article';
  662. $this->assertFalse($table->save($entity));
  663. }
  664. /**
  665. * Tests isUnique rule with coflicting columns
  666. *
  667. * @group save
  668. * @return void
  669. */
  670. public function testIsUniqueAliasPrefix()
  671. {
  672. $entity = new Entity([
  673. 'title' => 'An Article',
  674. 'author_id' => 1
  675. ]);
  676. $table = TableRegistry::get('Articles');
  677. $table->belongsTo('Authors');
  678. $rules = $table->rulesChecker();
  679. $rules->add($rules->isUnique(['author_id']));
  680. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  681. $query->leftJoin(['a2' => 'authors']);
  682. });
  683. $this->assertFalse($table->save($entity));
  684. $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('author_id'));
  685. }
  686. /**
  687. * Tests the existsIn rule when passing non dirty fields
  688. *
  689. * @group save
  690. * @return void
  691. */
  692. public function testExistsInWithCleanFields()
  693. {
  694. $table = TableRegistry::get('Articles');
  695. $table->belongsTo('Authors');
  696. $rules = $table->rulesChecker();
  697. $rules->add($rules->existsIn('author_id', 'Authors'));
  698. $entity = $table->get(1);
  699. $entity->title = 'Foo';
  700. $entity->author_id = 1000;
  701. $entity->dirty('author_id', false);
  702. $this->assertSame($entity, $table->save($entity));
  703. }
  704. /**
  705. * Tests the existsIn with coflicting columns
  706. *
  707. * @group save
  708. * @return void
  709. */
  710. public function testExistsInAliasPrefix()
  711. {
  712. $entity = new Entity([
  713. 'title' => 'An Article',
  714. 'author_id' => 500
  715. ]);
  716. $table = TableRegistry::get('Articles');
  717. $table->belongsTo('Authors');
  718. $rules = $table->rulesChecker();
  719. $rules->add($rules->existsIn('author_id', 'Authors'));
  720. $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
  721. $query->leftJoin(['a2' => 'authors']);
  722. });
  723. $this->assertFalse($table->save($entity));
  724. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  725. }
  726. /**
  727. * Tests that using an array in existsIn() sets the error message correctly
  728. *
  729. * @return
  730. */
  731. public function testExistsInErrorWithArrayField()
  732. {
  733. $entity = new Entity([
  734. 'title' => 'An Article',
  735. 'author_id' => 500
  736. ]);
  737. $table = TableRegistry::get('Articles');
  738. $table->belongsTo('Authors');
  739. $rules = $table->rulesChecker();
  740. $rules->add($rules->existsIn(['author_id'], 'Authors'));
  741. $this->assertFalse($table->save($entity));
  742. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  743. }
  744. /**
  745. * Tests using rules to prevent delete operations
  746. *
  747. * @group delete
  748. * @return void
  749. */
  750. public function testDeleteRules()
  751. {
  752. $table = TableRegistry::get('Articles');
  753. $rules = $table->rulesChecker();
  754. $rules->addDelete(function ($entity) {
  755. return false;
  756. });
  757. $entity = $table->get(1);
  758. $this->assertFalse($table->delete($entity));
  759. }
  760. /**
  761. * Checks that it is possible to pass custom options to rules when saving
  762. *
  763. * @group save
  764. * @return void
  765. */
  766. public function testCustomOptionsPassingSave()
  767. {
  768. $entity = new Entity([
  769. 'name' => 'jose'
  770. ]);
  771. $table = TableRegistry::get('Authors');
  772. $rules = $table->rulesChecker();
  773. $rules->add(function ($entity, $options) {
  774. $this->assertEquals('bar', $options['foo']);
  775. $this->assertEquals('option', $options['another']);
  776. return false;
  777. }, ['another' => 'option']);
  778. $this->assertFalse($table->save($entity, ['foo' => 'bar']));
  779. }
  780. /**
  781. * Tests passing custom options to rules from delete
  782. *
  783. * @group delete
  784. * @return void
  785. */
  786. public function testCustomOptionsPassingDelete()
  787. {
  788. $table = TableRegistry::get('Articles');
  789. $rules = $table->rulesChecker();
  790. $rules->addDelete(function ($entity, $options) {
  791. $this->assertEquals('bar', $options['foo']);
  792. $this->assertEquals('option', $options['another']);
  793. return false;
  794. }, ['another' => 'option']);
  795. $entity = $table->get(1);
  796. $this->assertFalse($table->delete($entity, ['foo' => 'bar']));
  797. }
  798. /**
  799. * Test adding rules that return error string
  800. *
  801. * @group save
  802. * @return void
  803. */
  804. public function testCustomErrorMessageFromRule()
  805. {
  806. $entity = new Entity([
  807. 'name' => 'larry'
  808. ]);
  809. $table = TableRegistry::get('Authors');
  810. $rules = $table->rulesChecker();
  811. $rules->add(function () {
  812. return 'So much nope';
  813. }, ['errorField' => 'name']);
  814. $this->assertFalse($table->save($entity));
  815. $this->assertEquals(['So much nope'], $entity->errors('name'));
  816. }
  817. /**
  818. * Test adding rules with no errorField do not accept strings
  819. *
  820. * @group save
  821. * @return void
  822. */
  823. public function testCustomErrorMessageFromRuleNoErrorField()
  824. {
  825. $entity = new Entity([
  826. 'name' => 'larry'
  827. ]);
  828. $table = TableRegistry::get('Authors');
  829. $rules = $table->rulesChecker();
  830. $rules->add(function () {
  831. return 'So much nope';
  832. });
  833. $this->assertFalse($table->save($entity));
  834. $this->assertEmpty($entity->errors());
  835. }
  836. /**
  837. * Tests that using existsIn for a hasMany association will not be called
  838. * as the foreign key for the association was automatically validated already.
  839. *
  840. * @group save
  841. * @return void
  842. */
  843. public function testAvoidExistsInOnAutomaticSaving()
  844. {
  845. $entity = new \Cake\ORM\Entity([
  846. 'name' => 'Jose'
  847. ]);
  848. $entity->articles = [
  849. new \Cake\ORM\Entity([
  850. 'title' => '1',
  851. 'body' => 'A body'
  852. ]),
  853. new \Cake\ORM\Entity([
  854. 'title' => 'Another Title',
  855. 'body' => 'Another body'
  856. ])
  857. ];
  858. $table = TableRegistry::get('authors');
  859. $table->hasMany('articles');
  860. $table->association('articles')->belongsTo('authors');
  861. $checker = $table->association('articles')->target()->rulesChecker();
  862. $checker->add(function ($entity, $options) use ($checker) {
  863. $rule = $checker->existsIn('author_id', 'authors');
  864. $id = $entity->author_id;
  865. $entity->author_id = 5000;
  866. $result = $rule($entity, $options);
  867. $this->assertTrue($result);
  868. $entity->author_id = $id;
  869. return true;
  870. });
  871. $this->assertSame($entity, $table->save($entity));
  872. }
  873. /**
  874. * Tests the existsIn domain rule respects the conditions set for the associations
  875. *
  876. * @group save
  877. * @return void
  878. */
  879. public function testExistsInDomainRuleWithAssociationConditions()
  880. {
  881. $entity = new Entity([
  882. 'title' => 'An Article',
  883. 'author_id' => 1
  884. ]);
  885. $table = TableRegistry::get('Articles');
  886. $table->belongsTo('Authors', [
  887. 'conditions' => ['Authors.name !=' => 'mariano']
  888. ]);
  889. $rules = $table->rulesChecker();
  890. $rules->add($rules->existsIn('author_id', 'Authors'));
  891. $this->assertFalse($table->save($entity));
  892. $this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
  893. }
  894. /**
  895. * Tests that associated items have a count of X.
  896. *
  897. * @return void
  898. */
  899. public function testCountOfAssociatedItems()
  900. {
  901. $entity = new \Cake\ORM\Entity([
  902. 'title' => 'A Title',
  903. 'body' => 'A body'
  904. ]);
  905. $entity->tags = [
  906. new \Cake\ORM\Entity([
  907. 'name' => 'Something New'
  908. ]),
  909. new \Cake\ORM\Entity([
  910. 'name' => '100'
  911. ])
  912. ];
  913. TableRegistry::get('ArticlesTags');
  914. $table = TableRegistry::get('articles');
  915. $table->belongsToMany('tags');
  916. $rules = $table->rulesChecker();
  917. $rules->add($rules->validCount('tags', 3));
  918. $this->assertFalse($table->save($entity));
  919. $this->assertEquals($entity->errors(), [
  920. 'tags' => [
  921. '_validCount' => 'The count does not match >3'
  922. ]
  923. ]);
  924. // Testing that undesired types fail
  925. $entity->tags = null;
  926. $this->assertFalse($table->save($entity));
  927. $entity->tags = new \stdClass();
  928. $this->assertFalse($table->save($entity));
  929. $entity->tags = 'string';
  930. $this->assertFalse($table->save($entity));
  931. $entity->tags = 123456;
  932. $this->assertFalse($table->save($entity));
  933. $entity->tags = 0.512;
  934. $this->assertFalse($table->save($entity));
  935. }
  936. }