RulesCheckerIntegrationTest.php 28 KB

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