ValidatorTest.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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\Validation;
  16. use Cake\TestSuite\TestCase;
  17. use Cake\Validation\ValidationSet;
  18. use Cake\Validation\Validator;
  19. /**
  20. * Tests Validator class
  21. *
  22. */
  23. class ValidatorTest extends TestCase
  24. {
  25. /**
  26. * Testing you can dynamically add rules to a field
  27. *
  28. * @return void
  29. */
  30. public function testAddingRulesToField()
  31. {
  32. $validator = new Validator;
  33. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  34. $set = $validator->field('title');
  35. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  36. $this->assertCount(1, $set);
  37. $validator->add('title', 'another', ['rule' => 'alphanumeric']);
  38. $this->assertCount(2, $set);
  39. $validator->add('body', 'another', ['rule' => 'crazy']);
  40. $this->assertCount(1, $validator->field('body'));
  41. $this->assertCount(2, $validator);
  42. }
  43. /**
  44. * Testing addNested field rules
  45. *
  46. * @return void
  47. */
  48. public function testAddNestedSingle()
  49. {
  50. $validator = new Validator();
  51. $inner = new Validator();
  52. $inner->add('username', 'not-blank', ['rule' => 'notBlank']);
  53. $this->assertSame($validator, $validator->addNested('user', $inner));
  54. $this->assertCount(1, $validator->field('user'));
  55. }
  56. /**
  57. * Testing addNested connects providers
  58. *
  59. * @return void
  60. */
  61. public function testAddNestedSingleProviders()
  62. {
  63. $validator = new Validator();
  64. $validator->provider('test', $this);
  65. $inner = new Validator();
  66. $inner->add('username', 'not-blank', ['rule' => function () use ($inner, $validator) {
  67. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  68. return false;
  69. }]);
  70. $validator->addNested('user', $inner);
  71. $result = $validator->errors(['user' => ['username' => 'example']]);
  72. $this->assertNotEmpty($result, 'Validation should fail');
  73. }
  74. /**
  75. * Testing addNestedMany field rules
  76. *
  77. * @return void
  78. */
  79. public function testAddNestedMany()
  80. {
  81. $validator = new Validator();
  82. $inner = new Validator();
  83. $inner->add('comment', 'not-blank', ['rule' => 'notBlank']);
  84. $this->assertSame($validator, $validator->addNestedMany('comments', $inner));
  85. $this->assertCount(1, $validator->field('comments'));
  86. }
  87. /**
  88. * Testing addNestedMany connects providers
  89. *
  90. * @return void
  91. */
  92. public function testAddNestedManyProviders()
  93. {
  94. $validator = new Validator();
  95. $validator->provider('test', $this);
  96. $inner = new Validator();
  97. $inner->add('comment', 'not-blank', ['rule' => function () use ($inner, $validator) {
  98. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  99. return false;
  100. }]);
  101. $validator->addNestedMany('comments', $inner);
  102. $result = $validator->errors(['comments' => [['comment' => 'example']]]);
  103. $this->assertNotEmpty($result, 'Validation should fail');
  104. }
  105. /**
  106. * Tests that calling field will create a default validation set for it
  107. *
  108. * @return void
  109. */
  110. public function testFieldDefault()
  111. {
  112. $validator = new Validator;
  113. $this->assertFalse($validator->hasField('foo'));
  114. $field = $validator->field('foo');
  115. $this->assertInstanceOf('Cake\Validation\ValidationSet', $field);
  116. $this->assertCount(0, $field);
  117. $this->assertTrue($validator->hasField('foo'));
  118. }
  119. /**
  120. * Tests that field method can be used as a setter
  121. *
  122. * @return void
  123. */
  124. public function testFieldSetter()
  125. {
  126. $validator = new Validator;
  127. $validationSet = new ValidationSet;
  128. $validator->field('thing', $validationSet);
  129. $this->assertSame($validationSet, $validator->field('thing'));
  130. }
  131. /**
  132. * Tests the remove method
  133. *
  134. * @return void
  135. */
  136. public function testRemove()
  137. {
  138. $validator = new Validator;
  139. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  140. $validator->add('title', 'foo', ['rule' => 'bar']);
  141. $this->assertCount(2, $validator->field('title'));
  142. $validator->remove('title');
  143. $this->assertCount(0, $validator->field('title'));
  144. $validator->remove('title');
  145. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  146. $validator->add('title', 'foo', ['rule' => 'bar']);
  147. $this->assertCount(2, $validator->field('title'));
  148. $validator->remove('title', 'foo');
  149. $this->assertCount(1, $validator->field('title'));
  150. $this->assertNull($validator->field('title')->rule('foo'));
  151. }
  152. /**
  153. * Tests the requirePresence method
  154. *
  155. * @return void
  156. */
  157. public function testRequirePresence()
  158. {
  159. $validator = new Validator;
  160. $this->assertSame($validator, $validator->requirePresence('title'));
  161. $this->assertTrue($validator->field('title')->isPresenceRequired());
  162. $validator->requirePresence('title', false);
  163. $this->assertFalse($validator->field('title')->isPresenceRequired());
  164. $validator->requirePresence('title', 'create');
  165. $this->assertEquals('create', $validator->field('title')->isPresenceRequired());
  166. $validator->requirePresence('title', 'update');
  167. $this->assertEquals('update', $validator->field('title')->isPresenceRequired());
  168. }
  169. /**
  170. * Tests the requirePresence method when passing a callback
  171. *
  172. * @return void
  173. */
  174. public function testRequirePresenceCallback()
  175. {
  176. $validator = new Validator;
  177. $require = true;
  178. $validator->requirePresence('title', function ($context) use (&$require) {
  179. $this->assertEquals([], $context['data']);
  180. $this->assertEquals([], $context['providers']);
  181. $this->assertEquals('title', $context['field']);
  182. $this->assertTrue($context['newRecord']);
  183. return $require;
  184. });
  185. $this->assertTrue($validator->isPresenceRequired('title', true));
  186. $require = false;
  187. $this->assertFalse($validator->isPresenceRequired('title', true));
  188. }
  189. /**
  190. * Tests the isPresenceRequired method
  191. *
  192. * @return void
  193. */
  194. public function testIsPresenceRequired()
  195. {
  196. $validator = new Validator;
  197. $this->assertSame($validator, $validator->requirePresence('title'));
  198. $this->assertTrue($validator->isPresenceRequired('title', true));
  199. $this->assertTrue($validator->isPresenceRequired('title', false));
  200. $validator->requirePresence('title', false);
  201. $this->assertFalse($validator->isPresenceRequired('title', true));
  202. $this->assertFalse($validator->isPresenceRequired('title', false));
  203. $validator->requirePresence('title', 'create');
  204. $this->assertTrue($validator->isPresenceRequired('title', true));
  205. $this->assertFalse($validator->isPresenceRequired('title', false));
  206. $validator->requirePresence('title', 'update');
  207. $this->assertTrue($validator->isPresenceRequired('title', false));
  208. $this->assertFalse($validator->isPresenceRequired('title', true));
  209. }
  210. /**
  211. * Tests errors generated when a field presence is required
  212. *
  213. * @return void
  214. */
  215. public function testErrorsWithPresenceRequired()
  216. {
  217. $validator = new Validator;
  218. $validator->requirePresence('title');
  219. $errors = $validator->errors(['foo' => 'something']);
  220. $expected = ['title' => ['_required' => 'This field is required']];
  221. $this->assertEquals($expected, $errors);
  222. $this->assertEmpty($validator->errors(['title' => 'bar']));
  223. $validator->requirePresence('title', false);
  224. $this->assertEmpty($validator->errors(['foo' => 'bar']));
  225. }
  226. /**
  227. * Test that errors() can work with nested data.
  228. *
  229. * @return void
  230. */
  231. public function testErrorsWithNestedFields()
  232. {
  233. $validator = new Validator();
  234. $user = new Validator();
  235. $user->add('username', 'letter', ['rule' => 'alphanumeric']);
  236. $comments = new Validator();
  237. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  238. $validator->addNested('user', $user);
  239. $validator->addNestedMany('comments', $comments);
  240. $data = [
  241. 'user' => [
  242. 'username' => 'is wrong'
  243. ],
  244. 'comments' => [
  245. ['comment' => 'is wrong']
  246. ]
  247. ];
  248. $errors = $validator->errors($data);
  249. $expected = [
  250. 'user' => [
  251. 'username' => ['letter' => 'The provided value is invalid']
  252. ],
  253. 'comments' => [
  254. 0 => ['comment' => ['letter' => 'The provided value is invalid']]
  255. ]
  256. ];
  257. $this->assertEquals($expected, $errors);
  258. }
  259. /**
  260. * Test nested fields with many, but invalid data.
  261. *
  262. * @return void
  263. */
  264. public function testErrorsWithNestedSingleInvalidType()
  265. {
  266. $validator = new Validator();
  267. $user = new Validator();
  268. $user->add('user', 'letter', ['rule' => 'alphanumeric']);
  269. $validator->addNested('user', $user);
  270. $data = [
  271. 'user' => 'a string',
  272. ];
  273. $errors = $validator->errors($data);
  274. $expected = [
  275. 'user' => ['_nested' => 'The provided value is invalid'],
  276. ];
  277. $this->assertEquals($expected, $errors);
  278. }
  279. /**
  280. * Test nested fields with many, but invalid data.
  281. *
  282. * @return void
  283. */
  284. public function testErrorsWithNestedManyInvalidType()
  285. {
  286. $validator = new Validator();
  287. $comments = new Validator();
  288. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  289. $validator->addNestedMany('comments', $comments);
  290. $data = [
  291. 'comments' => 'a string',
  292. ];
  293. $errors = $validator->errors($data);
  294. $expected = [
  295. 'comments' => ['_nested' => 'The provided value is invalid'],
  296. ];
  297. $this->assertEquals($expected, $errors);
  298. }
  299. /**
  300. * Test nested fields with many, but invalid data.
  301. *
  302. * @return void
  303. */
  304. public function testErrorsWithNestedManySomeInvalid()
  305. {
  306. $validator = new Validator();
  307. $comments = new Validator();
  308. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  309. $validator->addNestedMany('comments', $comments);
  310. $data = [
  311. 'comments' => [
  312. 'a string',
  313. ['comment' => 'letters'],
  314. ['comment' => 'more invalid']
  315. ]
  316. ];
  317. $errors = $validator->errors($data);
  318. $expected = [
  319. 'comments' => [
  320. '_nested' => 'The provided value is invalid',
  321. ],
  322. ];
  323. $this->assertEquals($expected, $errors);
  324. }
  325. /**
  326. * Tests custom error messages generated when a field presence is required
  327. *
  328. * @return void
  329. */
  330. public function testCustomErrorsWithPresenceRequired()
  331. {
  332. $validator = new Validator;
  333. $validator->requirePresence('title', true, 'Custom message');
  334. $errors = $validator->errors(['foo' => 'something']);
  335. $expected = ['title' => ['_required' => 'Custom message']];
  336. $this->assertEquals($expected, $errors);
  337. }
  338. /**
  339. * Tests the allowEmpty method
  340. *
  341. * @return void
  342. */
  343. public function testAllowEmpty()
  344. {
  345. $validator = new Validator;
  346. $this->assertSame($validator, $validator->allowEmpty('title'));
  347. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  348. $validator->allowEmpty('title', 'create');
  349. $this->assertEquals('create', $validator->field('title')->isEmptyAllowed());
  350. $validator->allowEmpty('title', 'update');
  351. $this->assertEquals('update', $validator->field('title')->isEmptyAllowed());
  352. }
  353. /**
  354. * Tests the allowEmpty method with date/time fields.
  355. *
  356. * @return void
  357. */
  358. public function testAllowEmptyDateTime()
  359. {
  360. $validator = new Validator;
  361. $validator->allowEmpty('created')
  362. ->add('created', 'date', ['rule' => 'date']);
  363. $data = [
  364. 'created' => [
  365. 'year' => '',
  366. 'month' => '',
  367. 'day' => ''
  368. ]
  369. ];
  370. $result = $validator->errors($data);
  371. $this->assertEmpty($result, 'No errors on empty date');
  372. $data = [
  373. 'created' => [
  374. 'year' => '',
  375. 'month' => '',
  376. 'day' => '',
  377. 'hour' => '',
  378. 'minute' => '',
  379. 'second' => '',
  380. 'meridian' => '',
  381. ]
  382. ];
  383. $result = $validator->errors($data);
  384. $this->assertEmpty($result, 'No errors on empty datetime');
  385. $data = [
  386. 'created' => [
  387. 'hour' => '',
  388. 'minute' => '',
  389. 'meridian' => '',
  390. ]
  391. ];
  392. $result = $validator->errors($data);
  393. $this->assertEmpty($result, 'No errors on empty time');
  394. }
  395. /**
  396. * Tests the allowEmpty method with file fields.
  397. *
  398. * @return void
  399. */
  400. public function testAllowEmptyFileFields()
  401. {
  402. $validator = new Validator;
  403. $validator->allowEmpty('picture')
  404. ->add('picture', 'file', ['rule' => 'uploadedFile']);
  405. $data = [
  406. 'picture' => [
  407. 'name' => '',
  408. 'type' => '',
  409. 'tmp_name' => '',
  410. 'error' => UPLOAD_ERR_NO_FILE,
  411. ]
  412. ];
  413. $result = $validator->errors($data);
  414. $this->assertEmpty($result, 'No errors on empty date');
  415. $data = [
  416. 'picture' => [
  417. 'name' => 'fake.png',
  418. 'type' => '',
  419. 'tmp_name' => '',
  420. 'error' => UPLOAD_ERR_OK,
  421. ]
  422. ];
  423. $result = $validator->errors($data);
  424. $this->assertNotEmpty($result, 'Invalid file should be caught still.');
  425. }
  426. /**
  427. * Test the notEmpty() method.
  428. *
  429. * @return void
  430. */
  431. public function testNotEmpty()
  432. {
  433. $validator = new Validator;
  434. $validator->notEmpty('title');
  435. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  436. $validator->allowEmpty('title');
  437. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  438. }
  439. /**
  440. * Test the notEmpty() method.
  441. *
  442. * @return void
  443. */
  444. public function testNotEmptyModes()
  445. {
  446. $validator = new Validator;
  447. $validator->notEmpty('title', 'Need a title', 'create');
  448. $this->assertFalse($validator->isEmptyAllowed('title', true));
  449. $this->assertTrue($validator->isEmptyAllowed('title', false));
  450. $validator->notEmpty('title', 'Need a title', 'update');
  451. $this->assertTrue($validator->isEmptyAllowed('title', true));
  452. $this->assertFalse($validator->isEmptyAllowed('title', false));
  453. $validator->notEmpty('title', 'Need a title');
  454. $this->assertFalse($validator->isEmptyAllowed('title', true));
  455. $this->assertFalse($validator->isEmptyAllowed('title', false));
  456. $validator->notEmpty('title');
  457. $this->assertFalse($validator->isEmptyAllowed('title', true));
  458. $this->assertFalse($validator->isEmptyAllowed('title', false));
  459. }
  460. /**
  461. * Test interactions between notEmpty() and isAllowed().
  462. *
  463. * @return void
  464. */
  465. public function testNotEmptyAndIsAllowed()
  466. {
  467. $validator = new Validator;
  468. $validator->allowEmpty('title')
  469. ->notEmpty('title', 'Need it', 'update');
  470. $this->assertTrue($validator->isEmptyAllowed('title', true));
  471. $this->assertFalse($validator->isEmptyAllowed('title', false));
  472. $validator->allowEmpty('title')
  473. ->notEmpty('title');
  474. $this->assertFalse($validator->isEmptyAllowed('title', true));
  475. $this->assertFalse($validator->isEmptyAllowed('title', false));
  476. $validator->notEmpty('title')
  477. ->allowEmpty('title', 'create');
  478. $this->assertTrue($validator->isEmptyAllowed('title', true));
  479. $this->assertFalse($validator->isEmptyAllowed('title', false));
  480. }
  481. /**
  482. * Tests the allowEmpty method when passing a callback
  483. *
  484. * @return void
  485. */
  486. public function testAllowEmptyCallback()
  487. {
  488. $validator = new Validator;
  489. $allow = true;
  490. $validator->allowEmpty('title', function ($context) use (&$allow) {
  491. $this->assertEquals([], $context['data']);
  492. $this->assertEquals([], $context['providers']);
  493. $this->assertTrue($context['newRecord']);
  494. return $allow;
  495. });
  496. $this->assertTrue($validator->isEmptyAllowed('title', true));
  497. $allow = false;
  498. $this->assertFalse($validator->isEmptyAllowed('title', true));
  499. }
  500. /**
  501. * Tests the notEmpty method when passing a callback
  502. *
  503. * @return void
  504. */
  505. public function testNotEmptyCallback()
  506. {
  507. $validator = new Validator;
  508. $prevent = true;
  509. $validator->notEmpty('title', 'error message', function ($context) use (&$prevent) {
  510. $this->assertEquals([], $context['data']);
  511. $this->assertEquals([], $context['providers']);
  512. $this->assertFalse($context['newRecord']);
  513. return $prevent;
  514. });
  515. $this->assertFalse($validator->isEmptyAllowed('title', false));
  516. $prevent = false;
  517. $this->assertTrue($validator->isEmptyAllowed('title', false));
  518. }
  519. /**
  520. * Tests the isEmptyAllowed method
  521. *
  522. * @return void
  523. */
  524. public function testIsEmptyAllowed()
  525. {
  526. $validator = new Validator;
  527. $this->assertSame($validator, $validator->allowEmpty('title'));
  528. $this->assertTrue($validator->isEmptyAllowed('title', true));
  529. $this->assertTrue($validator->isEmptyAllowed('title', false));
  530. $validator->notEmpty('title');
  531. $this->assertFalse($validator->isEmptyAllowed('title', true));
  532. $this->assertFalse($validator->isEmptyAllowed('title', false));
  533. $validator->allowEmpty('title', 'create');
  534. $this->assertTrue($validator->isEmptyAllowed('title', true));
  535. $this->assertFalse($validator->isEmptyAllowed('title', false));
  536. $validator->allowEmpty('title', 'update');
  537. $this->assertTrue($validator->isEmptyAllowed('title', false));
  538. $this->assertFalse($validator->isEmptyAllowed('title', true));
  539. }
  540. /**
  541. * Tests errors generated when a field is not allowed to be empty
  542. *
  543. * @return void
  544. */
  545. public function testErrorsWithEmptyNotAllowed()
  546. {
  547. $validator = new Validator;
  548. $validator->notEmpty('title');
  549. $errors = $validator->errors(['title' => '']);
  550. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  551. $this->assertEquals($expected, $errors);
  552. $errors = $validator->errors(['title' => []]);
  553. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  554. $this->assertEquals($expected, $errors);
  555. $errors = $validator->errors(['title' => null]);
  556. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  557. $this->assertEquals($expected, $errors);
  558. $errors = $validator->errors(['title' => 0]);
  559. $this->assertEmpty($errors);
  560. $errors = $validator->errors(['title' => '0']);
  561. $this->assertEmpty($errors);
  562. $errors = $validator->errors(['title' => false]);
  563. $this->assertEmpty($errors);
  564. }
  565. /**
  566. * Tests custom error mesages generated when a field is not allowed to be empty
  567. *
  568. * @return void
  569. */
  570. public function testCustomErrorsWithEmptyNotAllowed()
  571. {
  572. $validator = new Validator;
  573. $validator->notEmpty('title', 'Custom message');
  574. $errors = $validator->errors(['title' => '']);
  575. $expected = ['title' => ['_empty' => 'Custom message']];
  576. $this->assertEquals($expected, $errors);
  577. }
  578. /**
  579. * Tests errors generated when a field is allowed to be empty
  580. *
  581. * @return void
  582. */
  583. public function testErrorsWithEmptyAllowed()
  584. {
  585. $validator = new Validator;
  586. $validator->allowEmpty('title');
  587. $errors = $validator->errors(['title' => '']);
  588. $this->assertEmpty($errors);
  589. $errors = $validator->errors(['title' => []]);
  590. $this->assertEmpty($errors);
  591. $errors = $validator->errors(['title' => null]);
  592. $this->assertEmpty($errors);
  593. $errors = $validator->errors(['title' => 0]);
  594. $this->assertEmpty($errors);
  595. $errors = $validator->errors(['title' => 0.0]);
  596. $this->assertEmpty($errors);
  597. $errors = $validator->errors(['title' => '0']);
  598. $this->assertEmpty($errors);
  599. $errors = $validator->errors(['title' => false]);
  600. $this->assertEmpty($errors);
  601. }
  602. /**
  603. * Test the provider() method
  604. *
  605. * @return void
  606. */
  607. public function testProvider()
  608. {
  609. $validator = new Validator;
  610. $object = new \stdClass;
  611. $this->assertSame($validator, $validator->provider('foo', $object));
  612. $this->assertSame($object, $validator->provider('foo'));
  613. $this->assertNull($validator->provider('bar'));
  614. $another = new \stdClass;
  615. $this->assertSame($validator, $validator->provider('bar', $another));
  616. $this->assertSame($another, $validator->provider('bar'));
  617. $this->assertEquals(new \Cake\Validation\RulesProvider, $validator->provider('default'));
  618. }
  619. /**
  620. * Tests errors() method when using validators from the default provider, this proves
  621. * that it returns a default validation message and the custom one set in the rule
  622. *
  623. * @return void
  624. */
  625. public function testErrorsFromDefaultProvider()
  626. {
  627. $validator = new Validator;
  628. $validator
  629. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  630. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  631. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  632. $errors = $validator->errors(['email' => 'not an email!']);
  633. $expected = [
  634. 'email' => [
  635. 'alpha' => 'The provided value is invalid',
  636. 'email' => 'Y u no write email?'
  637. ]
  638. ];
  639. $this->assertEquals($expected, $errors);
  640. }
  641. /**
  642. * Tests using validation methods from different providers and returning the error
  643. * as a string
  644. *
  645. * @return void
  646. */
  647. public function testErrorsFromCustomProvider()
  648. {
  649. $validator = new Validator;
  650. $validator
  651. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  652. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  653. $thing = $this->getMock('\stdClass', ['isCool']);
  654. $thing->expects($this->once())->method('isCool')
  655. ->will($this->returnCallback(function ($data, $context) use ($thing) {
  656. $this->assertEquals('bar', $data);
  657. $expected = [
  658. 'default' => new \Cake\Validation\RulesProvider,
  659. 'thing' => $thing
  660. ];
  661. $expected = [
  662. 'newRecord' => true,
  663. 'providers' => $expected,
  664. 'data' => [
  665. 'email' => '!',
  666. 'title' => 'bar'
  667. ],
  668. 'field' => 'title'
  669. ];
  670. $this->assertEquals($expected, $context);
  671. return "That ain't cool, yo";
  672. }));
  673. $validator->provider('thing', $thing);
  674. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  675. $expected = [
  676. 'email' => ['alpha' => 'The provided value is invalid'],
  677. 'title' => ['cool' => "That ain't cool, yo"]
  678. ];
  679. $this->assertEquals($expected, $errors);
  680. }
  681. /**
  682. * Tests that it is possible to pass extra arguments to the validation function
  683. * and it still gets the providers as last argument
  684. *
  685. * @return void
  686. */
  687. public function testMethodsWithExtraArguments()
  688. {
  689. $validator = new Validator;
  690. $validator->add('title', 'cool', [
  691. 'rule' => ['isCool', 'and', 'awesome'],
  692. 'provider' => 'thing'
  693. ]);
  694. $thing = $this->getMock('\stdClass', ['isCool']);
  695. $thing->expects($this->once())->method('isCool')
  696. ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
  697. $this->assertEquals('bar', $data);
  698. $this->assertEquals('and', $a);
  699. $this->assertEquals('awesome', $b);
  700. $expected = [
  701. 'default' => new \Cake\Validation\RulesProvider,
  702. 'thing' => $thing
  703. ];
  704. $expected = [
  705. 'newRecord' => true,
  706. 'providers' => $expected,
  707. 'data' => [
  708. 'email' => '!',
  709. 'title' => 'bar'
  710. ],
  711. 'field' => 'title'
  712. ];
  713. $this->assertEquals($expected, $context);
  714. return "That ain't cool, yo";
  715. }));
  716. $validator->provider('thing', $thing);
  717. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  718. $expected = [
  719. 'title' => ['cool' => "That ain't cool, yo"]
  720. ];
  721. $this->assertEquals($expected, $errors);
  722. }
  723. /**
  724. * Tests that it is possible to use a closure as a rule
  725. *
  726. * @return void
  727. */
  728. public function testUsingClosureAsRule()
  729. {
  730. $validator = new Validator;
  731. $validator->add('name', 'myRule', [
  732. 'rule' => function ($data, $provider) {
  733. $this->assertEquals('foo', $data);
  734. return 'You fail';
  735. }
  736. ]);
  737. $expected = ['name' => ['myRule' => 'You fail']];
  738. $this->assertEquals($expected, $validator->errors(['name' => 'foo']));
  739. }
  740. /**
  741. * Tests that setting last to a rule will stop validating the rest of the rules
  742. *
  743. * @return void
  744. */
  745. public function testErrorsWithLastRule()
  746. {
  747. $validator = new Validator;
  748. $validator
  749. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  750. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  751. $errors = $validator->errors(['email' => 'not an email!']);
  752. $expected = [
  753. 'email' => [
  754. 'alpha' => 'The provided value is invalid'
  755. ]
  756. ];
  757. $this->assertEquals($expected, $errors);
  758. }
  759. /**
  760. * Tests it is possible to get validation sets for a field using an array interface
  761. *
  762. * @return void
  763. */
  764. public function testArrayAccessGet()
  765. {
  766. $validator = new Validator;
  767. $validator
  768. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  769. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  770. $this->assertSame($validator['email'], $validator->field('email'));
  771. $this->assertSame($validator['title'], $validator->field('title'));
  772. }
  773. /**
  774. * Tests it is possible to check for validation sets for a field using an array inteface
  775. *
  776. * @return void
  777. */
  778. public function testArrayAccessExists()
  779. {
  780. $validator = new Validator;
  781. $validator
  782. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  783. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  784. $this->assertTrue(isset($validator['email']));
  785. $this->assertTrue(isset($validator['title']));
  786. $this->assertFalse(isset($validator['foo']));
  787. }
  788. /**
  789. * Tests it is possible to set validation rules for a field using an array inteface
  790. *
  791. * @return void
  792. */
  793. public function testArrayAccessSet()
  794. {
  795. $validator = new Validator;
  796. $validator
  797. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  798. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  799. $validator['name'] = $validator->field('title');
  800. $this->assertSame($validator->field('title'), $validator->field('name'));
  801. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  802. $this->assertEquals($validator->field('email'), $validator->field('email'));
  803. }
  804. /**
  805. * Tests it is possible to unset validation rules
  806. *
  807. * @return void
  808. */
  809. public function testArrayAccessUset()
  810. {
  811. $validator = new Validator;
  812. $validator
  813. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  814. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  815. $this->assertTrue(isset($validator['title']));
  816. unset($validator['title']);
  817. $this->assertFalse(isset($validator['title']));
  818. }
  819. /**
  820. * Tests the countable interface
  821. *
  822. * @return void
  823. */
  824. public function testCount()
  825. {
  826. $validator = new Validator;
  827. $validator
  828. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  829. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  830. $this->assertCount(2, $validator);
  831. }
  832. /**
  833. * Tests adding rules via alternative syntax
  834. *
  835. * @return void
  836. */
  837. public function testAddMulitple()
  838. {
  839. $validator = new Validator;
  840. $validator->add('title', [
  841. 'notBlank' => [
  842. 'rule' => 'notBlank'
  843. ],
  844. 'length' => [
  845. 'rule' => ['minLength', 10],
  846. 'message' => 'Titles need to be at least 10 characters long'
  847. ]
  848. ]);
  849. $set = $validator->field('title');
  850. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  851. $this->assertCount(2, $set);
  852. }
  853. /**
  854. * Integration test for compareWith validator.
  855. *
  856. * @return void
  857. */
  858. public function testCompareWithIntegration()
  859. {
  860. $validator = new Validator;
  861. $validator->add('password', [
  862. 'compare' => [
  863. 'rule' => ['compareWith', 'password_compare']
  864. ],
  865. ]);
  866. $data = [
  867. 'password' => 'test',
  868. 'password_compare' => 'not the same'
  869. ];
  870. $this->assertNotEmpty($validator->errors($data), 'Validation should fail.');
  871. }
  872. /**
  873. * Test debugInfo helper method.
  874. *
  875. * @return void
  876. */
  877. public function testDebugInfo()
  878. {
  879. $validator = new Validator();
  880. $validator->provider('test', $this);
  881. $validator->add('title', 'not-empty', ['rule' => 'notEmpty']);
  882. $validator->requirePresence('body');
  883. $validator->allowEmpty('published');
  884. $result = $validator->__debugInfo();
  885. $expected = [
  886. '_providers' => ['test'],
  887. '_fields' => [
  888. 'title' => [
  889. 'isPresenceRequired' => false,
  890. 'isEmptyAllowed' => false,
  891. 'rules' => ['not-empty'],
  892. ],
  893. 'body' => [
  894. 'isPresenceRequired' => true,
  895. 'isEmptyAllowed' => false,
  896. 'rules' => [],
  897. ],
  898. 'published' => [
  899. 'isPresenceRequired' => false,
  900. 'isEmptyAllowed' => true,
  901. 'rules' => [],
  902. ],
  903. ],
  904. '_presenceMessages' => [],
  905. '_allowEmptyMessages' => [],
  906. '_useI18n' => true,
  907. ];
  908. $this->assertEquals($expected, $result);
  909. }
  910. /**
  911. * Tests that the 'create' and 'update' modes are preserved when using
  912. * nested validators
  913. *
  914. * @return void
  915. */
  916. public function testNestedValidatorCreate()
  917. {
  918. $validator = new Validator();
  919. $inner = new Validator();
  920. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  921. $validator->addNested('user', $inner);
  922. $this->assertNotEmpty($validator->errors(['user' => ['username' => 'example']], true));
  923. $this->assertEmpty($validator->errors(['user' => ['username' => 'a']], false));
  924. }
  925. /**
  926. * Tests that the 'create' and 'update' modes are preserved when using
  927. * nested validators
  928. *
  929. * @return void
  930. */
  931. public function testNestedManyValidatorCreate()
  932. {
  933. $validator = new Validator();
  934. $inner = new Validator();
  935. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  936. $validator->addNestedMany('user', $inner);
  937. $this->assertNotEmpty($validator->errors(['user' => [['username' => 'example']]], true));
  938. $this->assertEmpty($validator->errors(['user' => [['username' => 'a']]], false));
  939. }
  940. }