ValidatorTest.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  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. class ValidatorTest extends TestCase
  23. {
  24. /**
  25. * Testing you can dynamically add rules to a field
  26. *
  27. * @return void
  28. */
  29. public function testAddingRulesToField()
  30. {
  31. $validator = new Validator;
  32. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  33. $set = $validator->field('title');
  34. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  35. $this->assertCount(1, $set);
  36. $validator->add('title', 'another', ['rule' => 'alphanumeric']);
  37. $this->assertCount(2, $set);
  38. $validator->add('body', 'another', ['rule' => 'crazy']);
  39. $this->assertCount(1, $validator->field('body'));
  40. $this->assertCount(2, $validator);
  41. }
  42. /**
  43. * Testing addNested field rules
  44. *
  45. * @return void
  46. */
  47. public function testAddNestedSingle()
  48. {
  49. $validator = new Validator();
  50. $inner = new Validator();
  51. $inner->add('username', 'not-blank', ['rule' => 'notBlank']);
  52. $this->assertSame($validator, $validator->addNested('user', $inner));
  53. $this->assertCount(1, $validator->field('user'));
  54. }
  55. /**
  56. * Testing addNested connects providers
  57. *
  58. * @return void
  59. */
  60. public function testAddNestedSingleProviders()
  61. {
  62. $validator = new Validator();
  63. $validator->provider('test', $this);
  64. $inner = new Validator();
  65. $inner->add('username', 'not-blank', ['rule' => function () use ($inner, $validator) {
  66. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  67. return false;
  68. }]);
  69. $validator->addNested('user', $inner);
  70. $result = $validator->errors(['user' => ['username' => 'example']]);
  71. $this->assertNotEmpty($result, 'Validation should fail');
  72. }
  73. /**
  74. * Testing addNestedMany field rules
  75. *
  76. * @return void
  77. */
  78. public function testAddNestedMany()
  79. {
  80. $validator = new Validator();
  81. $inner = new Validator();
  82. $inner->add('comment', 'not-blank', ['rule' => 'notBlank']);
  83. $this->assertSame($validator, $validator->addNestedMany('comments', $inner));
  84. $this->assertCount(1, $validator->field('comments'));
  85. }
  86. /**
  87. * Testing addNestedMany connects providers
  88. *
  89. * @return void
  90. */
  91. public function testAddNestedManyProviders()
  92. {
  93. $validator = new Validator();
  94. $validator->provider('test', $this);
  95. $inner = new Validator();
  96. $inner->add('comment', 'not-blank', ['rule' => function () use ($inner, $validator) {
  97. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  98. return false;
  99. }]);
  100. $validator->addNestedMany('comments', $inner);
  101. $result = $validator->errors(['comments' => [['comment' => 'example']]]);
  102. $this->assertNotEmpty($result, 'Validation should fail');
  103. }
  104. /**
  105. * Tests that calling field will create a default validation set for it
  106. *
  107. * @return void
  108. */
  109. public function testFieldDefault()
  110. {
  111. $validator = new Validator;
  112. $this->assertFalse($validator->hasField('foo'));
  113. $field = $validator->field('foo');
  114. $this->assertInstanceOf('Cake\Validation\ValidationSet', $field);
  115. $this->assertCount(0, $field);
  116. $this->assertTrue($validator->hasField('foo'));
  117. }
  118. /**
  119. * Tests that field method can be used as a setter
  120. *
  121. * @return void
  122. */
  123. public function testFieldSetter()
  124. {
  125. $validator = new Validator;
  126. $validationSet = new ValidationSet;
  127. $validator->field('thing', $validationSet);
  128. $this->assertSame($validationSet, $validator->field('thing'));
  129. }
  130. /**
  131. * Tests the remove method
  132. *
  133. * @return void
  134. */
  135. public function testRemove()
  136. {
  137. $validator = new Validator;
  138. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  139. $validator->add('title', 'foo', ['rule' => 'bar']);
  140. $this->assertCount(2, $validator->field('title'));
  141. $validator->remove('title');
  142. $this->assertCount(0, $validator->field('title'));
  143. $validator->remove('title');
  144. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  145. $validator->add('title', 'foo', ['rule' => 'bar']);
  146. $this->assertCount(2, $validator->field('title'));
  147. $validator->remove('title', 'foo');
  148. $this->assertCount(1, $validator->field('title'));
  149. $this->assertNull($validator->field('title')->rule('foo'));
  150. }
  151. /**
  152. * Tests the requirePresence method
  153. *
  154. * @return void
  155. */
  156. public function testRequirePresence()
  157. {
  158. $validator = new Validator;
  159. $this->assertSame($validator, $validator->requirePresence('title'));
  160. $this->assertTrue($validator->field('title')->isPresenceRequired());
  161. $validator->requirePresence('title', false);
  162. $this->assertFalse($validator->field('title')->isPresenceRequired());
  163. $validator->requirePresence('title', 'create');
  164. $this->assertEquals('create', $validator->field('title')->isPresenceRequired());
  165. $validator->requirePresence('title', 'update');
  166. $this->assertEquals('update', $validator->field('title')->isPresenceRequired());
  167. }
  168. /**
  169. * Tests the requirePresence method
  170. *
  171. * @return void
  172. */
  173. public function testRequirePresenceAsArray()
  174. {
  175. $validator = new Validator;
  176. $validator->requirePresence(['title', 'created']);
  177. $this->assertTrue($validator->field('title')->isPresenceRequired());
  178. $this->assertTrue($validator->field('created')->isPresenceRequired());
  179. $validator->requirePresence([
  180. 'title' => [
  181. 'mode' => false
  182. ],
  183. 'content' => [
  184. 'mode' => 'update'
  185. ],
  186. 'subject'
  187. ], true);
  188. $this->assertFalse($validator->field('title')->isPresenceRequired());
  189. $this->assertEquals('update', $validator->field('content')->isPresenceRequired());
  190. $this->assertTrue($validator->field('subject')->isPresenceRequired());
  191. }
  192. /**
  193. * Tests the requirePresence failure case
  194. *
  195. * @expectedException \InvalidArgumentException
  196. * @return void
  197. */
  198. public function testRequirePresenceAsArrayFailure()
  199. {
  200. $validator = new Validator();
  201. $validator->requirePresence(['title' => 'derp', 'created' => false]);
  202. }
  203. /**
  204. * Tests the requirePresence method when passing a callback
  205. *
  206. * @return void
  207. */
  208. public function testRequirePresenceCallback()
  209. {
  210. $validator = new Validator;
  211. $require = true;
  212. $validator->requirePresence('title', function ($context) use (&$require) {
  213. $this->assertEquals([], $context['data']);
  214. $this->assertEquals([], $context['providers']);
  215. $this->assertEquals('title', $context['field']);
  216. $this->assertTrue($context['newRecord']);
  217. return $require;
  218. });
  219. $this->assertTrue($validator->isPresenceRequired('title', true));
  220. $require = false;
  221. $this->assertFalse($validator->isPresenceRequired('title', true));
  222. }
  223. /**
  224. * Tests the isPresenceRequired method
  225. *
  226. * @return void
  227. */
  228. public function testIsPresenceRequired()
  229. {
  230. $validator = new Validator;
  231. $this->assertSame($validator, $validator->requirePresence('title'));
  232. $this->assertTrue($validator->isPresenceRequired('title', true));
  233. $this->assertTrue($validator->isPresenceRequired('title', false));
  234. $validator->requirePresence('title', false);
  235. $this->assertFalse($validator->isPresenceRequired('title', true));
  236. $this->assertFalse($validator->isPresenceRequired('title', false));
  237. $validator->requirePresence('title', 'create');
  238. $this->assertTrue($validator->isPresenceRequired('title', true));
  239. $this->assertFalse($validator->isPresenceRequired('title', false));
  240. $validator->requirePresence('title', 'update');
  241. $this->assertTrue($validator->isPresenceRequired('title', false));
  242. $this->assertFalse($validator->isPresenceRequired('title', true));
  243. }
  244. /**
  245. * Tests errors generated when a field presence is required
  246. *
  247. * @return void
  248. */
  249. public function testErrorsWithPresenceRequired()
  250. {
  251. $validator = new Validator;
  252. $validator->requirePresence('title');
  253. $errors = $validator->errors(['foo' => 'something']);
  254. $expected = ['title' => ['_required' => 'This field is required']];
  255. $this->assertEquals($expected, $errors);
  256. $this->assertEmpty($validator->errors(['title' => 'bar']));
  257. $validator->requirePresence('title', false);
  258. $this->assertEmpty($validator->errors(['foo' => 'bar']));
  259. }
  260. /**
  261. * Test that errors() can work with nested data.
  262. *
  263. * @return void
  264. */
  265. public function testErrorsWithNestedFields()
  266. {
  267. $validator = new Validator();
  268. $user = new Validator();
  269. $user->add('username', 'letter', ['rule' => 'alphanumeric']);
  270. $comments = new Validator();
  271. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  272. $validator->addNested('user', $user);
  273. $validator->addNestedMany('comments', $comments);
  274. $data = [
  275. 'user' => [
  276. 'username' => 'is wrong'
  277. ],
  278. 'comments' => [
  279. ['comment' => 'is wrong']
  280. ]
  281. ];
  282. $errors = $validator->errors($data);
  283. $expected = [
  284. 'user' => [
  285. 'username' => ['letter' => 'The provided value is invalid']
  286. ],
  287. 'comments' => [
  288. 0 => ['comment' => ['letter' => 'The provided value is invalid']]
  289. ]
  290. ];
  291. $this->assertEquals($expected, $errors);
  292. }
  293. /**
  294. * Test nested fields with many, but invalid data.
  295. *
  296. * @return void
  297. */
  298. public function testErrorsWithNestedSingleInvalidType()
  299. {
  300. $validator = new Validator();
  301. $user = new Validator();
  302. $user->add('user', 'letter', ['rule' => 'alphanumeric']);
  303. $validator->addNested('user', $user);
  304. $data = [
  305. 'user' => 'a string',
  306. ];
  307. $errors = $validator->errors($data);
  308. $expected = [
  309. 'user' => ['_nested' => 'The provided value is invalid'],
  310. ];
  311. $this->assertEquals($expected, $errors);
  312. }
  313. /**
  314. * Test nested fields with many, but invalid data.
  315. *
  316. * @return void
  317. */
  318. public function testErrorsWithNestedManyInvalidType()
  319. {
  320. $validator = new Validator();
  321. $comments = new Validator();
  322. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  323. $validator->addNestedMany('comments', $comments);
  324. $data = [
  325. 'comments' => 'a string',
  326. ];
  327. $errors = $validator->errors($data);
  328. $expected = [
  329. 'comments' => ['_nested' => 'The provided value is invalid'],
  330. ];
  331. $this->assertEquals($expected, $errors);
  332. }
  333. /**
  334. * Test nested fields with many, but invalid data.
  335. *
  336. * @return void
  337. */
  338. public function testErrorsWithNestedManySomeInvalid()
  339. {
  340. $validator = new Validator();
  341. $comments = new Validator();
  342. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  343. $validator->addNestedMany('comments', $comments);
  344. $data = [
  345. 'comments' => [
  346. 'a string',
  347. ['comment' => 'letters'],
  348. ['comment' => 'more invalid']
  349. ]
  350. ];
  351. $errors = $validator->errors($data);
  352. $expected = [
  353. 'comments' => [
  354. '_nested' => 'The provided value is invalid',
  355. ],
  356. ];
  357. $this->assertEquals($expected, $errors);
  358. }
  359. /**
  360. * Tests custom error messages generated when a field presence is required
  361. *
  362. * @return void
  363. */
  364. public function testCustomErrorsWithPresenceRequired()
  365. {
  366. $validator = new Validator;
  367. $validator->requirePresence('title', true, 'Custom message');
  368. $errors = $validator->errors(['foo' => 'something']);
  369. $expected = ['title' => ['_required' => 'Custom message']];
  370. $this->assertEquals($expected, $errors);
  371. }
  372. /**
  373. * Tests custom error messages generated when a field presence is required
  374. *
  375. * @return void
  376. */
  377. public function testCustomErrorsWithPresenceRequiredAsArray()
  378. {
  379. $validator = new Validator;
  380. $validator->requirePresence(['title', 'content'], true, 'Custom message');
  381. $errors = $validator->errors(['foo' => 'something']);
  382. $expected = [
  383. 'title' => ['_required' => 'Custom message'],
  384. 'content' => ['_required' => 'Custom message']
  385. ];
  386. $this->assertEquals($expected, $errors);
  387. $validator->requirePresence([
  388. 'title' => [
  389. 'message' => 'Test message'
  390. ],
  391. 'content'
  392. ], true, 'Custom message');
  393. $errors = $validator->errors(['foo' => 'something']);
  394. $expected = [
  395. 'title' => ['_required' => 'Test message'],
  396. 'content' => ['_required' => 'Custom message']
  397. ];
  398. $this->assertEquals($expected, $errors);
  399. }
  400. /**
  401. * Tests the allowEmpty method
  402. *
  403. * @return void
  404. */
  405. public function testAllowEmpty()
  406. {
  407. $validator = new Validator;
  408. $this->assertSame($validator, $validator->allowEmpty('title'));
  409. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  410. $validator->allowEmpty('title', 'create');
  411. $this->assertEquals('create', $validator->field('title')->isEmptyAllowed());
  412. $validator->allowEmpty('title', 'update');
  413. $this->assertEquals('update', $validator->field('title')->isEmptyAllowed());
  414. }
  415. /**
  416. * Tests the allowEmpty method with date/time fields.
  417. *
  418. * @return void
  419. */
  420. public function testAllowEmptyDateTime()
  421. {
  422. $validator = new Validator;
  423. $validator->allowEmpty('created')
  424. ->add('created', 'date', ['rule' => 'date']);
  425. $data = [
  426. 'created' => [
  427. 'year' => '',
  428. 'month' => '',
  429. 'day' => ''
  430. ]
  431. ];
  432. $result = $validator->errors($data);
  433. $this->assertEmpty($result, 'No errors on empty date');
  434. $data = [
  435. 'created' => [
  436. 'year' => '',
  437. 'month' => '',
  438. 'day' => '',
  439. 'hour' => '',
  440. 'minute' => '',
  441. 'second' => '',
  442. 'meridian' => '',
  443. ]
  444. ];
  445. $result = $validator->errors($data);
  446. $this->assertEmpty($result, 'No errors on empty datetime');
  447. $data = [
  448. 'created' => [
  449. 'hour' => '',
  450. 'minute' => '',
  451. 'meridian' => '',
  452. ]
  453. ];
  454. $result = $validator->errors($data);
  455. $this->assertEmpty($result, 'No errors on empty time');
  456. }
  457. /**
  458. * Tests the allowEmpty method with file fields.
  459. *
  460. * @return void
  461. */
  462. public function testAllowEmptyFileFields()
  463. {
  464. $validator = new Validator;
  465. $validator->allowEmpty('picture')
  466. ->add('picture', 'file', ['rule' => 'uploadedFile']);
  467. $data = [
  468. 'picture' => [
  469. 'name' => '',
  470. 'type' => '',
  471. 'tmp_name' => '',
  472. 'error' => UPLOAD_ERR_NO_FILE,
  473. ]
  474. ];
  475. $result = $validator->errors($data);
  476. $this->assertEmpty($result, 'No errors on empty date');
  477. $data = [
  478. 'picture' => [
  479. 'name' => 'fake.png',
  480. 'type' => '',
  481. 'tmp_name' => '',
  482. 'error' => UPLOAD_ERR_OK,
  483. ]
  484. ];
  485. $result = $validator->errors($data);
  486. $this->assertNotEmpty($result, 'Invalid file should be caught still.');
  487. }
  488. /**
  489. * Tests the allowEmpty as array method
  490. *
  491. * @return void
  492. */
  493. public function testAllowEmptyAsArray()
  494. {
  495. $validator = new Validator;
  496. $validator->allowEmpty([
  497. 'title',
  498. 'subject',
  499. 'posted_at' => [
  500. 'when' => false,
  501. 'message' => 'Post time cannot be empty'
  502. ],
  503. 'updated_at' => [
  504. 'when' => true
  505. ],
  506. 'show_at' => [
  507. 'when' => 'update'
  508. ]
  509. ], 'create', 'Cannot be empty');
  510. $this->assertEquals('create', $validator->field('title')->isEmptyAllowed());
  511. $this->assertEquals('create', $validator->field('subject')->isEmptyAllowed());
  512. $this->assertFalse($validator->field('posted_at')->isEmptyAllowed());
  513. $this->assertTrue($validator->field('updated_at')->isEmptyAllowed());
  514. $this->assertEquals('update', $validator->field('show_at')->isEmptyAllowed());
  515. $errors = $validator->errors([
  516. 'title' => '',
  517. 'subject' => null,
  518. 'posted_at' => null,
  519. 'updated_at' => null,
  520. 'show_at' => ''
  521. ], false);
  522. $expected = [
  523. 'title' => ['_empty' => 'Cannot be empty'],
  524. 'subject' => ['_empty' => 'Cannot be empty'],
  525. 'posted_at' => ['_empty' => 'Post time cannot be empty']
  526. ];
  527. $this->assertEquals($expected, $errors);
  528. }
  529. /**
  530. * Tests the allowEmpty failure case
  531. *
  532. * @expectedException \InvalidArgumentException
  533. * @return void
  534. */
  535. public function testAllowEmptyAsArrayFailure()
  536. {
  537. $validator = new Validator();
  538. $validator->allowEmpty(['title' => 'derp', 'created' => false]);
  539. }
  540. /**
  541. * Test the notEmpty() method.
  542. *
  543. * @return void
  544. */
  545. public function testNotEmpty()
  546. {
  547. $validator = new Validator;
  548. $validator->notEmpty('title');
  549. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  550. $validator->allowEmpty('title');
  551. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  552. }
  553. /**
  554. * Tests the notEmpty as array method
  555. *
  556. * @return void
  557. */
  558. public function testNotEmptyAsArray()
  559. {
  560. $validator = new Validator;
  561. $validator->notEmpty(['title', 'created']);
  562. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  563. $this->assertFalse($validator->field('created')->isEmptyAllowed());
  564. $validator->notEmpty([
  565. 'title' => [
  566. 'when' => false
  567. ],
  568. 'content' => [
  569. 'when' => 'update'
  570. ],
  571. 'posted_at' => [
  572. 'when' => 'create'
  573. ],
  574. 'show_at' => [
  575. 'message' => 'Show date cannot be empty',
  576. 'when' => false
  577. ],
  578. 'subject'
  579. ], 'Not empty', true);
  580. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  581. $this->assertTrue($validator->isEmptyAllowed('content', true));
  582. $this->assertFalse($validator->isEmptyAllowed('content', false));
  583. $this->assertFalse($validator->isEmptyAllowed('posted_at', true));
  584. $this->assertTrue($validator->isEmptyAllowed('posted_at', false));
  585. $this->assertTrue($validator->field('subject')->isEmptyAllowed());
  586. $errors = $validator->errors([
  587. 'title' => '',
  588. 'content' => '',
  589. 'posted_at' => null,
  590. 'show_at' => null,
  591. 'subject' => ''
  592. ], false);
  593. $expected = [
  594. 'title' => ['_empty' => 'Not empty'],
  595. 'content' => ['_empty' => 'Not empty'],
  596. 'show_at' => ['_empty' => 'Show date cannot be empty']
  597. ];
  598. $this->assertEquals($expected, $errors);
  599. }
  600. /**
  601. * Tests the notEmpty failure case
  602. *
  603. * @expectedException \InvalidArgumentException
  604. * @return void
  605. */
  606. public function testNotEmptyAsArrayFailure()
  607. {
  608. $validator = new Validator();
  609. $validator->notEmpty(['title' => 'derp', 'created' => false]);
  610. }
  611. /**
  612. * Test the notEmpty() method.
  613. *
  614. * @return void
  615. */
  616. public function testNotEmptyModes()
  617. {
  618. $validator = new Validator;
  619. $validator->notEmpty('title', 'Need a title', 'create');
  620. $this->assertFalse($validator->isEmptyAllowed('title', true));
  621. $this->assertTrue($validator->isEmptyAllowed('title', false));
  622. $validator->notEmpty('title', 'Need a title', 'update');
  623. $this->assertTrue($validator->isEmptyAllowed('title', true));
  624. $this->assertFalse($validator->isEmptyAllowed('title', false));
  625. $validator->notEmpty('title', 'Need a title');
  626. $this->assertFalse($validator->isEmptyAllowed('title', true));
  627. $this->assertFalse($validator->isEmptyAllowed('title', false));
  628. $validator->notEmpty('title');
  629. $this->assertFalse($validator->isEmptyAllowed('title', true));
  630. $this->assertFalse($validator->isEmptyAllowed('title', false));
  631. }
  632. /**
  633. * Test interactions between notEmpty() and isAllowed().
  634. *
  635. * @return void
  636. */
  637. public function testNotEmptyAndIsAllowed()
  638. {
  639. $validator = new Validator;
  640. $validator->allowEmpty('title')
  641. ->notEmpty('title', 'Need it', 'update');
  642. $this->assertTrue($validator->isEmptyAllowed('title', true));
  643. $this->assertFalse($validator->isEmptyAllowed('title', false));
  644. $validator->allowEmpty('title')
  645. ->notEmpty('title');
  646. $this->assertFalse($validator->isEmptyAllowed('title', true));
  647. $this->assertFalse($validator->isEmptyAllowed('title', false));
  648. $validator->notEmpty('title')
  649. ->allowEmpty('title', 'create');
  650. $this->assertTrue($validator->isEmptyAllowed('title', true));
  651. $this->assertFalse($validator->isEmptyAllowed('title', false));
  652. }
  653. /**
  654. * Tests the allowEmpty method when passing a callback
  655. *
  656. * @return void
  657. */
  658. public function testAllowEmptyCallback()
  659. {
  660. $validator = new Validator;
  661. $allow = true;
  662. $validator->allowEmpty('title', function ($context) use (&$allow) {
  663. $this->assertEquals([], $context['data']);
  664. $this->assertEquals([], $context['providers']);
  665. $this->assertTrue($context['newRecord']);
  666. return $allow;
  667. });
  668. $this->assertTrue($validator->isEmptyAllowed('title', true));
  669. $allow = false;
  670. $this->assertFalse($validator->isEmptyAllowed('title', true));
  671. }
  672. /**
  673. * Tests the notEmpty method when passing a callback
  674. *
  675. * @return void
  676. */
  677. public function testNotEmptyCallback()
  678. {
  679. $validator = new Validator;
  680. $prevent = true;
  681. $validator->notEmpty('title', 'error message', function ($context) use (&$prevent) {
  682. $this->assertEquals([], $context['data']);
  683. $this->assertEquals([], $context['providers']);
  684. $this->assertFalse($context['newRecord']);
  685. return $prevent;
  686. });
  687. $this->assertFalse($validator->isEmptyAllowed('title', false));
  688. $prevent = false;
  689. $this->assertTrue($validator->isEmptyAllowed('title', false));
  690. }
  691. /**
  692. * Tests the isEmptyAllowed method
  693. *
  694. * @return void
  695. */
  696. public function testIsEmptyAllowed()
  697. {
  698. $validator = new Validator;
  699. $this->assertSame($validator, $validator->allowEmpty('title'));
  700. $this->assertTrue($validator->isEmptyAllowed('title', true));
  701. $this->assertTrue($validator->isEmptyAllowed('title', false));
  702. $validator->notEmpty('title');
  703. $this->assertFalse($validator->isEmptyAllowed('title', true));
  704. $this->assertFalse($validator->isEmptyAllowed('title', false));
  705. $validator->allowEmpty('title', 'create');
  706. $this->assertTrue($validator->isEmptyAllowed('title', true));
  707. $this->assertFalse($validator->isEmptyAllowed('title', false));
  708. $validator->allowEmpty('title', 'update');
  709. $this->assertTrue($validator->isEmptyAllowed('title', false));
  710. $this->assertFalse($validator->isEmptyAllowed('title', true));
  711. }
  712. /**
  713. * Tests errors generated when a field is not allowed to be empty
  714. *
  715. * @return void
  716. */
  717. public function testErrorsWithEmptyNotAllowed()
  718. {
  719. $validator = new Validator;
  720. $validator->notEmpty('title');
  721. $errors = $validator->errors(['title' => '']);
  722. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  723. $this->assertEquals($expected, $errors);
  724. $errors = $validator->errors(['title' => []]);
  725. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  726. $this->assertEquals($expected, $errors);
  727. $errors = $validator->errors(['title' => null]);
  728. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  729. $this->assertEquals($expected, $errors);
  730. $errors = $validator->errors(['title' => 0]);
  731. $this->assertEmpty($errors);
  732. $errors = $validator->errors(['title' => '0']);
  733. $this->assertEmpty($errors);
  734. $errors = $validator->errors(['title' => false]);
  735. $this->assertEmpty($errors);
  736. }
  737. /**
  738. * Tests custom error messages generated when a field is allowed to be empty
  739. *
  740. * @return void
  741. */
  742. public function testCustomErrorsWithAllowedEmpty()
  743. {
  744. $validator = new Validator;
  745. $validator->allowEmpty('title', false, 'Custom message');
  746. $errors = $validator->errors(['title' => null]);
  747. $expected = ['title' => ['_empty' => 'Custom message']];
  748. $this->assertEquals($expected, $errors);
  749. }
  750. /**
  751. * Tests custom error messages generated when a field is not allowed to be empty
  752. *
  753. * @return void
  754. */
  755. public function testCustomErrorsWithEmptyNotAllowed()
  756. {
  757. $validator = new Validator;
  758. $validator->notEmpty('title', 'Custom message');
  759. $errors = $validator->errors(['title' => '']);
  760. $expected = ['title' => ['_empty' => 'Custom message']];
  761. $this->assertEquals($expected, $errors);
  762. }
  763. /**
  764. * Tests errors generated when a field is allowed to be empty
  765. *
  766. * @return void
  767. */
  768. public function testErrorsWithEmptyAllowed()
  769. {
  770. $validator = new Validator;
  771. $validator->allowEmpty('title');
  772. $errors = $validator->errors(['title' => '']);
  773. $this->assertEmpty($errors);
  774. $errors = $validator->errors(['title' => []]);
  775. $this->assertEmpty($errors);
  776. $errors = $validator->errors(['title' => null]);
  777. $this->assertEmpty($errors);
  778. $errors = $validator->errors(['title' => 0]);
  779. $this->assertEmpty($errors);
  780. $errors = $validator->errors(['title' => 0.0]);
  781. $this->assertEmpty($errors);
  782. $errors = $validator->errors(['title' => '0']);
  783. $this->assertEmpty($errors);
  784. $errors = $validator->errors(['title' => false]);
  785. $this->assertEmpty($errors);
  786. }
  787. /**
  788. * Test the provider() method
  789. *
  790. * @return void
  791. */
  792. public function testProvider()
  793. {
  794. $validator = new Validator;
  795. $object = new \stdClass;
  796. $this->assertSame($validator, $validator->provider('foo', $object));
  797. $this->assertSame($object, $validator->provider('foo'));
  798. $this->assertNull($validator->provider('bar'));
  799. $another = new \stdClass;
  800. $this->assertSame($validator, $validator->provider('bar', $another));
  801. $this->assertSame($another, $validator->provider('bar'));
  802. $this->assertEquals(new \Cake\Validation\RulesProvider, $validator->provider('default'));
  803. }
  804. /**
  805. * Tests errors() method when using validators from the default provider, this proves
  806. * that it returns a default validation message and the custom one set in the rule
  807. *
  808. * @return void
  809. */
  810. public function testErrorsFromDefaultProvider()
  811. {
  812. $validator = new Validator;
  813. $validator
  814. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  815. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  816. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  817. $errors = $validator->errors(['email' => 'not an email!']);
  818. $expected = [
  819. 'email' => [
  820. 'alpha' => 'The provided value is invalid',
  821. 'email' => 'Y u no write email?'
  822. ]
  823. ];
  824. $this->assertEquals($expected, $errors);
  825. }
  826. /**
  827. * Tests using validation methods from different providers and returning the error
  828. * as a string
  829. *
  830. * @return void
  831. */
  832. public function testErrorsFromCustomProvider()
  833. {
  834. $validator = new Validator;
  835. $validator
  836. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  837. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  838. $thing = $this->getMockBuilder('\stdClass')
  839. ->setMethods(['isCool'])
  840. ->getMock();
  841. $thing->expects($this->once())->method('isCool')
  842. ->will($this->returnCallback(function ($data, $context) use ($thing) {
  843. $this->assertEquals('bar', $data);
  844. $expected = [
  845. 'default' => new \Cake\Validation\RulesProvider,
  846. 'thing' => $thing
  847. ];
  848. $expected = [
  849. 'newRecord' => true,
  850. 'providers' => $expected,
  851. 'data' => [
  852. 'email' => '!',
  853. 'title' => 'bar'
  854. ],
  855. 'field' => 'title'
  856. ];
  857. $this->assertEquals($expected, $context);
  858. return "That ain't cool, yo";
  859. }));
  860. $validator->provider('thing', $thing);
  861. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  862. $expected = [
  863. 'email' => ['alpha' => 'The provided value is invalid'],
  864. 'title' => ['cool' => "That ain't cool, yo"]
  865. ];
  866. $this->assertEquals($expected, $errors);
  867. }
  868. /**
  869. * Tests that it is possible to pass extra arguments to the validation function
  870. * and it still gets the providers as last argument
  871. *
  872. * @return void
  873. */
  874. public function testMethodsWithExtraArguments()
  875. {
  876. $validator = new Validator;
  877. $validator->add('title', 'cool', [
  878. 'rule' => ['isCool', 'and', 'awesome'],
  879. 'provider' => 'thing'
  880. ]);
  881. $thing = $this->getMockBuilder('\stdClass')
  882. ->setMethods(['isCool'])
  883. ->getMock();
  884. $thing->expects($this->once())->method('isCool')
  885. ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
  886. $this->assertEquals('bar', $data);
  887. $this->assertEquals('and', $a);
  888. $this->assertEquals('awesome', $b);
  889. $expected = [
  890. 'default' => new \Cake\Validation\RulesProvider,
  891. 'thing' => $thing
  892. ];
  893. $expected = [
  894. 'newRecord' => true,
  895. 'providers' => $expected,
  896. 'data' => [
  897. 'email' => '!',
  898. 'title' => 'bar'
  899. ],
  900. 'field' => 'title'
  901. ];
  902. $this->assertEquals($expected, $context);
  903. return "That ain't cool, yo";
  904. }));
  905. $validator->provider('thing', $thing);
  906. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  907. $expected = [
  908. 'title' => ['cool' => "That ain't cool, yo"]
  909. ];
  910. $this->assertEquals($expected, $errors);
  911. }
  912. /**
  913. * Tests that it is possible to use a closure as a rule
  914. *
  915. * @return void
  916. */
  917. public function testUsingClosureAsRule()
  918. {
  919. $validator = new Validator;
  920. $validator->add('name', 'myRule', [
  921. 'rule' => function ($data, $provider) {
  922. $this->assertEquals('foo', $data);
  923. return 'You fail';
  924. }
  925. ]);
  926. $expected = ['name' => ['myRule' => 'You fail']];
  927. $this->assertEquals($expected, $validator->errors(['name' => 'foo']));
  928. }
  929. /**
  930. * Tests that setting last to a rule will stop validating the rest of the rules
  931. *
  932. * @return void
  933. */
  934. public function testErrorsWithLastRule()
  935. {
  936. $validator = new Validator;
  937. $validator
  938. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  939. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  940. $errors = $validator->errors(['email' => 'not an email!']);
  941. $expected = [
  942. 'email' => [
  943. 'alpha' => 'The provided value is invalid'
  944. ]
  945. ];
  946. $this->assertEquals($expected, $errors);
  947. }
  948. /**
  949. * Tests it is possible to get validation sets for a field using an array interface
  950. *
  951. * @return void
  952. */
  953. public function testArrayAccessGet()
  954. {
  955. $validator = new Validator;
  956. $validator
  957. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  958. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  959. $this->assertSame($validator['email'], $validator->field('email'));
  960. $this->assertSame($validator['title'], $validator->field('title'));
  961. }
  962. /**
  963. * Tests it is possible to check for validation sets for a field using an array interface
  964. *
  965. * @return void
  966. */
  967. public function testArrayAccessExists()
  968. {
  969. $validator = new Validator;
  970. $validator
  971. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  972. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  973. $this->assertTrue(isset($validator['email']));
  974. $this->assertTrue(isset($validator['title']));
  975. $this->assertFalse(isset($validator['foo']));
  976. }
  977. /**
  978. * Tests it is possible to set validation rules for a field using an array interface
  979. *
  980. * @return void
  981. */
  982. public function testArrayAccessSet()
  983. {
  984. $validator = new Validator;
  985. $validator
  986. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  987. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  988. $validator['name'] = $validator->field('title');
  989. $this->assertSame($validator->field('title'), $validator->field('name'));
  990. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  991. $this->assertEquals($validator->field('email'), $validator->field('email'));
  992. }
  993. /**
  994. * Tests it is possible to unset validation rules
  995. *
  996. * @return void
  997. */
  998. public function testArrayAccessUnset()
  999. {
  1000. $validator = new Validator;
  1001. $validator
  1002. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1003. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1004. $this->assertTrue(isset($validator['title']));
  1005. unset($validator['title']);
  1006. $this->assertFalse(isset($validator['title']));
  1007. }
  1008. /**
  1009. * Tests the countable interface
  1010. *
  1011. * @return void
  1012. */
  1013. public function testCount()
  1014. {
  1015. $validator = new Validator;
  1016. $validator
  1017. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1018. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1019. $this->assertCount(2, $validator);
  1020. }
  1021. /**
  1022. * Tests adding rules via alternative syntax
  1023. *
  1024. * @return void
  1025. */
  1026. public function testAddMultiple()
  1027. {
  1028. $validator = new Validator;
  1029. $validator->add('title', [
  1030. 'notBlank' => [
  1031. 'rule' => 'notBlank'
  1032. ],
  1033. 'length' => [
  1034. 'rule' => ['minLength', 10],
  1035. 'message' => 'Titles need to be at least 10 characters long'
  1036. ]
  1037. ]);
  1038. $set = $validator->field('title');
  1039. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  1040. $this->assertCount(2, $set);
  1041. }
  1042. /**
  1043. * Integration test for compareWith validator.
  1044. *
  1045. * @return void
  1046. */
  1047. public function testCompareWithIntegration()
  1048. {
  1049. $validator = new Validator;
  1050. $validator->add('password', [
  1051. 'compare' => [
  1052. 'rule' => ['compareWith', 'password_compare']
  1053. ],
  1054. ]);
  1055. $data = [
  1056. 'password' => 'test',
  1057. 'password_compare' => 'not the same'
  1058. ];
  1059. $this->assertNotEmpty($validator->errors($data), 'Validation should fail.');
  1060. }
  1061. /**
  1062. * Test debugInfo helper method.
  1063. *
  1064. * @return void
  1065. */
  1066. public function testDebugInfo()
  1067. {
  1068. $validator = new Validator();
  1069. $validator->provider('test', $this);
  1070. $validator->add('title', 'not-empty', ['rule' => 'notEmpty']);
  1071. $validator->requirePresence('body');
  1072. $validator->allowEmpty('published');
  1073. $result = $validator->__debugInfo();
  1074. $expected = [
  1075. '_providers' => ['test'],
  1076. '_fields' => [
  1077. 'title' => [
  1078. 'isPresenceRequired' => false,
  1079. 'isEmptyAllowed' => false,
  1080. 'rules' => ['not-empty'],
  1081. ],
  1082. 'body' => [
  1083. 'isPresenceRequired' => true,
  1084. 'isEmptyAllowed' => false,
  1085. 'rules' => [],
  1086. ],
  1087. 'published' => [
  1088. 'isPresenceRequired' => false,
  1089. 'isEmptyAllowed' => true,
  1090. 'rules' => [],
  1091. ],
  1092. ],
  1093. '_presenceMessages' => [],
  1094. '_allowEmptyMessages' => [],
  1095. '_useI18n' => true,
  1096. ];
  1097. $this->assertEquals($expected, $result);
  1098. }
  1099. /**
  1100. * Tests that the 'create' and 'update' modes are preserved when using
  1101. * nested validators
  1102. *
  1103. * @return void
  1104. */
  1105. public function testNestedValidatorCreate()
  1106. {
  1107. $validator = new Validator();
  1108. $inner = new Validator();
  1109. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1110. $validator->addNested('user', $inner);
  1111. $this->assertNotEmpty($validator->errors(['user' => ['username' => 'example']], true));
  1112. $this->assertEmpty($validator->errors(['user' => ['username' => 'a']], false));
  1113. }
  1114. /**
  1115. * Tests that the 'create' and 'update' modes are preserved when using
  1116. * nested validators
  1117. *
  1118. * @return void
  1119. */
  1120. public function testNestedManyValidatorCreate()
  1121. {
  1122. $validator = new Validator();
  1123. $inner = new Validator();
  1124. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1125. $validator->addNestedMany('user', $inner);
  1126. $this->assertNotEmpty($validator->errors(['user' => [['username' => 'example']]], true));
  1127. $this->assertEmpty($validator->errors(['user' => [['username' => 'a']]], false));
  1128. }
  1129. /**
  1130. * Tests the notBlank proxy method
  1131. *
  1132. * @return void
  1133. */
  1134. public function testNotBlank()
  1135. {
  1136. $validator = new Validator();
  1137. $this->assertProxyMethod($validator, 'notBlank');
  1138. $this->assertNotEmpty($validator->errors(['username' => ' ']));
  1139. }
  1140. /**
  1141. * Tests the alphanumeric proxy method
  1142. *
  1143. * @return void
  1144. */
  1145. public function testAlphanumeric()
  1146. {
  1147. $validator = new Validator();
  1148. $this->assertProxyMethod($validator, 'alphaNumeric');
  1149. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1150. }
  1151. /**
  1152. * Tests the lengthBetween proxy method
  1153. *
  1154. * @return void
  1155. */
  1156. public function testLengthBetween()
  1157. {
  1158. $validator = new Validator();
  1159. $this->assertProxyMethod($validator, 'lengthBetween', [5, 7], [5, 7]);
  1160. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1161. }
  1162. /**
  1163. * Tests the lengthBetween proxy method
  1164. *
  1165. * @expectedException \InvalidArgumentException
  1166. * @return void
  1167. */
  1168. public function testLengthBetweenFailure()
  1169. {
  1170. $validator = new Validator();
  1171. $validator->lengthBetween('username', [7]);
  1172. }
  1173. /**
  1174. * Tests the creditCard proxy method
  1175. *
  1176. * @return void
  1177. */
  1178. public function testCreditCard()
  1179. {
  1180. $validator = new Validator();
  1181. $this->assertProxyMethod($validator, 'creditCard', 'all', ['all', true], 'cc');
  1182. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1183. }
  1184. /**
  1185. * Tests the greaterThan proxy method
  1186. *
  1187. * @return void
  1188. */
  1189. public function testGreaterThan()
  1190. {
  1191. $validator = new Validator();
  1192. $this->assertProxyMethod($validator, 'greaterThan', 5, ['>', 5], 'comparison');
  1193. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1194. }
  1195. /**
  1196. * Tests the greaterThanOrEqual proxy method
  1197. *
  1198. * @return void
  1199. */
  1200. public function testGreaterThanOrEqual()
  1201. {
  1202. $validator = new Validator();
  1203. $this->assertProxyMethod($validator, 'greaterThanOrEqual', 5, ['>=', 5], 'comparison');
  1204. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1205. }
  1206. /**
  1207. * Tests the lessThan proxy method
  1208. *
  1209. * @return void
  1210. */
  1211. public function testLessThan()
  1212. {
  1213. $validator = new Validator();
  1214. $this->assertProxyMethod($validator, 'lessThan', 5, ['<', 5], 'comparison');
  1215. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1216. }
  1217. /**
  1218. * Tests the lessThanOrEqual proxy method
  1219. *
  1220. * @return void
  1221. */
  1222. public function testLessThanOrEqual()
  1223. {
  1224. $validator = new Validator();
  1225. $this->assertProxyMethod($validator, 'lessThanOrEqual', 5, ['<=', 5], 'comparison');
  1226. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1227. }
  1228. /**
  1229. * Tests the equals proxy method
  1230. *
  1231. * @return void
  1232. */
  1233. public function testEquals()
  1234. {
  1235. $validator = new Validator();
  1236. $this->assertProxyMethod($validator, 'equals', 5, ['==', 5], 'comparison');
  1237. $this->assertEmpty($validator->errors(['username' => 5]));
  1238. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1239. }
  1240. /**
  1241. * Tests the notEquals proxy method
  1242. *
  1243. * @return void
  1244. */
  1245. public function testNotEquals()
  1246. {
  1247. $validator = new Validator();
  1248. $this->assertProxyMethod($validator, 'notEquals', 5, ['!=', 5], 'comparison');
  1249. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1250. }
  1251. /**
  1252. * Tests the sameAs proxy method
  1253. *
  1254. * @return void
  1255. */
  1256. public function testSameAs()
  1257. {
  1258. $validator = new Validator();
  1259. $this->assertProxyMethod($validator, 'sameAs', 'other', ['other'], 'compareWith');
  1260. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1261. }
  1262. /**
  1263. * Tests the containsNonAlphaNumeric proxy method
  1264. *
  1265. * @return void
  1266. */
  1267. public function testContainsNonAlphaNumeric()
  1268. {
  1269. $validator = new Validator();
  1270. $this->assertProxyMethod($validator, 'containsNonAlphaNumeric', 2, [2]);
  1271. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1272. }
  1273. /**
  1274. * Tests the date proxy method
  1275. *
  1276. * @return void
  1277. */
  1278. public function testDate()
  1279. {
  1280. $validator = new Validator();
  1281. $this->assertProxyMethod($validator, 'date', ['ymd'], [['ymd']]);
  1282. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1283. }
  1284. /**
  1285. * Tests the dateTime proxy method
  1286. *
  1287. * @return void
  1288. */
  1289. public function testDateTime()
  1290. {
  1291. $validator = new Validator();
  1292. $this->assertProxyMethod($validator, 'dateTime', ['ymd'], [['ymd']], 'datetime');
  1293. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1294. }
  1295. /**
  1296. * Tests the time proxy method
  1297. *
  1298. * @return void
  1299. */
  1300. public function testTime()
  1301. {
  1302. $validator = new Validator();
  1303. $this->assertProxyMethod($validator, 'time');
  1304. $this->assertNotEmpty($validator->errors(['username' => 'not a time']));
  1305. }
  1306. /**
  1307. * Tests the localizedTime proxy method
  1308. *
  1309. * @return void
  1310. */
  1311. public function testLocalizedTime()
  1312. {
  1313. $validator = new Validator();
  1314. $this->assertProxyMethod($validator, 'localizedTime', 'date', ['date']);
  1315. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1316. }
  1317. /**
  1318. * Tests the boolean proxy method
  1319. *
  1320. * @return void
  1321. */
  1322. public function testBoolean()
  1323. {
  1324. $validator = new Validator();
  1325. $this->assertProxyMethod($validator, 'boolean');
  1326. $this->assertNotEmpty($validator->errors(['username' => 'not a boolean']));
  1327. }
  1328. /**
  1329. * Tests the decimal proxy method
  1330. *
  1331. * @return void
  1332. */
  1333. public function testDecimal()
  1334. {
  1335. $validator = new Validator();
  1336. $this->assertProxyMethod($validator, 'decimal', 2, [2]);
  1337. $this->assertNotEmpty($validator->errors(['username' => 10.1]));
  1338. }
  1339. /**
  1340. * Tests the ip proxy methods
  1341. *
  1342. * @return void
  1343. */
  1344. public function testIps()
  1345. {
  1346. $validator = new Validator();
  1347. $this->assertProxyMethod($validator, 'ip');
  1348. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1349. $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip');
  1350. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1351. $this->assertProxyMethod($validator, 'ipv6', null, ['ipv6'], 'ip');
  1352. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1353. }
  1354. /**
  1355. * Tests the minLength proxy method
  1356. *
  1357. * @return void
  1358. */
  1359. public function testMinLength()
  1360. {
  1361. $validator = new Validator();
  1362. $this->assertProxyMethod($validator, 'minLength', 2, [2]);
  1363. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1364. }
  1365. /**
  1366. * Tests the minLengthBytes proxy method
  1367. *
  1368. * @return void
  1369. */
  1370. public function testMinLengthBytes()
  1371. {
  1372. $validator = new Validator();
  1373. $this->assertProxyMethod($validator, 'minLengthBytes', 11, [11]);
  1374. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  1375. }
  1376. /**
  1377. * Tests the maxLength proxy method
  1378. *
  1379. * @return void
  1380. */
  1381. public function testMaxLength()
  1382. {
  1383. $validator = new Validator();
  1384. $this->assertProxyMethod($validator, 'maxLength', 2, [2]);
  1385. $this->assertNotEmpty($validator->errors(['username' => 'aaa']));
  1386. }
  1387. /**
  1388. * Tests the maxLengthBytes proxy method
  1389. *
  1390. * @return void
  1391. */
  1392. public function testMaxLengthBytes()
  1393. {
  1394. $validator = new Validator();
  1395. $this->assertProxyMethod($validator, 'maxLengthBytes', 9, [9]);
  1396. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  1397. }
  1398. /**
  1399. * Tests the numeric proxy method
  1400. *
  1401. * @return void
  1402. */
  1403. public function testNumeric()
  1404. {
  1405. $validator = new Validator();
  1406. $this->assertProxyMethod($validator, 'numeric');
  1407. $this->assertEmpty($validator->errors(['username' => '22']));
  1408. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1409. }
  1410. /**
  1411. * Tests the naturalNumber proxy method
  1412. *
  1413. * @return void
  1414. */
  1415. public function testNaturalNumber()
  1416. {
  1417. $validator = new Validator();
  1418. $this->assertProxyMethod($validator, 'naturalNumber', null, [false]);
  1419. $this->assertNotEmpty($validator->errors(['username' => 0]));
  1420. }
  1421. /**
  1422. * Tests the nonNegativeInteger proxy method
  1423. *
  1424. * @return void
  1425. */
  1426. public function testNonNegativeInteger()
  1427. {
  1428. $validator = new Validator();
  1429. $this->assertProxyMethod($validator, 'nonNegativeInteger', null, [true], 'naturalNumber');
  1430. $this->assertNotEmpty($validator->errors(['username' => -1]));
  1431. }
  1432. /**
  1433. * Tests the range proxy method
  1434. *
  1435. * @return void
  1436. */
  1437. public function testRange()
  1438. {
  1439. $validator = new Validator();
  1440. $this->assertProxyMethod($validator, 'range', [1, 4], [1, 4]);
  1441. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1442. }
  1443. /**
  1444. * Tests the range failure case
  1445. *
  1446. * @expectedException \InvalidArgumentException
  1447. * @return void
  1448. */
  1449. public function testRangeFailure()
  1450. {
  1451. $validator = new Validator();
  1452. $validator->range('username', [1]);
  1453. }
  1454. /**
  1455. * Tests the url proxy method
  1456. *
  1457. * @return void
  1458. */
  1459. public function testUrl()
  1460. {
  1461. $validator = new Validator();
  1462. $this->assertProxyMethod($validator, 'url', null, [false]);
  1463. $this->assertNotEmpty($validator->errors(['username' => 'not url']));
  1464. }
  1465. /**
  1466. * Tests the urlWithProtocol proxy method
  1467. *
  1468. * @return void
  1469. */
  1470. public function testUrlWithProtocol()
  1471. {
  1472. $validator = new Validator();
  1473. $this->assertProxyMethod($validator, 'urlWithProtocol', null, [true], 'url');
  1474. $this->assertNotEmpty($validator->errors(['username' => 'google.com']));
  1475. }
  1476. /**
  1477. * Tests the inList proxy method
  1478. *
  1479. * @return void
  1480. */
  1481. public function testInList()
  1482. {
  1483. $validator = new Validator();
  1484. $this->assertProxyMethod($validator, 'inList', ['a', 'b'], [['a', 'b']]);
  1485. $this->assertNotEmpty($validator->errors(['username' => 'c']));
  1486. }
  1487. /**
  1488. * Tests the uuid proxy method
  1489. *
  1490. * @return void
  1491. */
  1492. public function testUuid()
  1493. {
  1494. $validator = new Validator();
  1495. $this->assertProxyMethod($validator, 'uuid');
  1496. $this->assertNotEmpty($validator->errors(['username' => 'not uuid']));
  1497. }
  1498. /**
  1499. * Tests the uploadedFile proxy method
  1500. *
  1501. * @return void
  1502. */
  1503. public function testUploadedFile()
  1504. {
  1505. $validator = new Validator();
  1506. $this->assertProxyMethod($validator, 'uploadedFile', ['foo' => 'bar'], [['foo' => 'bar']]);
  1507. $this->assertNotEmpty($validator->errors(['username' => []]));
  1508. }
  1509. /**
  1510. * Tests the latlog proxy methods
  1511. *
  1512. * @return void
  1513. */
  1514. public function testLatLong()
  1515. {
  1516. $validator = new Validator();
  1517. $this->assertProxyMethod($validator, 'latLong', null, [], 'geoCoordinate');
  1518. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1519. $this->assertProxyMethod($validator, 'latitude');
  1520. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1521. $this->assertProxyMethod($validator, 'longitude');
  1522. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1523. }
  1524. /**
  1525. * Tests the ascii proxy method
  1526. *
  1527. * @return void
  1528. */
  1529. public function testAscii()
  1530. {
  1531. $validator = new Validator();
  1532. $this->assertProxyMethod($validator, 'ascii');
  1533. $this->assertNotEmpty($validator->errors(['username' => 'ü']));
  1534. }
  1535. /**
  1536. * Tests the utf8 proxy methods
  1537. *
  1538. * @return void
  1539. */
  1540. public function testUtf8()
  1541. {
  1542. // Grinning face
  1543. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  1544. $validator = new Validator();
  1545. $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]);
  1546. $this->assertEmpty($validator->errors(['username' => 'ü']));
  1547. $this->assertNotEmpty($validator->errors(['username' => $extended]));
  1548. }
  1549. /**
  1550. * Test utf8extended proxy method.
  1551. *
  1552. * @return void
  1553. */
  1554. public function testUtf8Extended()
  1555. {
  1556. // Grinning face
  1557. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  1558. $validator = new Validator();
  1559. $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8');
  1560. $this->assertEmpty($validator->errors(['username' => 'ü']));
  1561. $this->assertEmpty($validator->errors(['username' => $extended]));
  1562. }
  1563. /**
  1564. * Tests the email proxy method
  1565. *
  1566. * @return void
  1567. */
  1568. public function testEmail()
  1569. {
  1570. $validator = new Validator();
  1571. $validator->email('username');
  1572. $this->assertEmpty($validator->errors(['username' => 'test@example.com']));
  1573. $this->assertNotEmpty($validator->errors(['username' => 'not an email']));
  1574. }
  1575. /**
  1576. * Tests the integer proxy method
  1577. *
  1578. * @return void
  1579. */
  1580. public function testInteger()
  1581. {
  1582. $validator = new Validator();
  1583. $this->assertProxyMethod($validator, 'integer', null, [], 'isInteger');
  1584. $this->assertNotEmpty($validator->errors(['username' => 'not integer']));
  1585. }
  1586. /**
  1587. * Tests the isArray proxy method
  1588. */
  1589. public function testIsArray()
  1590. {
  1591. $validator = new Validator();
  1592. $validator->isArray('username');
  1593. $this->assertEmpty($validator->errors(['username' => [1, 2, 3]]));
  1594. $this->assertNotEmpty($validator->errors(['username' => 'is not an array']));
  1595. }
  1596. /**
  1597. * Tests the multiple proxy method
  1598. *
  1599. * @return void
  1600. */
  1601. public function testMultiple()
  1602. {
  1603. $validator = new Validator();
  1604. $this->assertProxyMethod(
  1605. $validator,
  1606. 'multipleOptions',
  1607. ['min' => 1, 'caseInsensitive' => true],
  1608. [['min' => 1], true],
  1609. 'multiple'
  1610. );
  1611. $this->assertProxyMethod(
  1612. $validator,
  1613. 'multipleOptions',
  1614. ['min' => 1, 'caseInsensitive' => false],
  1615. [['min' => 1], false],
  1616. 'multiple'
  1617. );
  1618. $this->assertNotEmpty($validator->errors(['username' => '']));
  1619. }
  1620. /**
  1621. * Tests the hasAtLeast method
  1622. *
  1623. * @return void
  1624. */
  1625. public function testHasAtLeast()
  1626. {
  1627. $validator = new Validator();
  1628. $validator->hasAtLeast('things', 3);
  1629. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  1630. $this->assertEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  1631. $this->assertNotEmpty($validator->errors(['things' => [1, 2]]));
  1632. $this->assertNotEmpty($validator->errors(['things' => []]));
  1633. $this->assertNotEmpty($validator->errors(['things' => 'string']));
  1634. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  1635. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  1636. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  1637. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => []]]));
  1638. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => 'string']]));
  1639. }
  1640. /**
  1641. * Tests the hasAtMost method
  1642. *
  1643. * @return void
  1644. */
  1645. public function testHasAtMost()
  1646. {
  1647. $validator = new Validator();
  1648. $validator->hasAtMost('things', 3);
  1649. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  1650. $this->assertEmpty($validator->errors(['things' => [1]]));
  1651. $this->assertNotEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  1652. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  1653. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  1654. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  1655. }
  1656. /**
  1657. * Tests the regex proxy method
  1658. *
  1659. * @return void
  1660. */
  1661. public function testRegex()
  1662. {
  1663. $validator = new Validator();
  1664. $this->assertProxyMethod($validator, 'regex', '/(?<!\\S)\\d++(?!\\S)/', ['/(?<!\\S)\\d++(?!\\S)/'], 'custom');
  1665. $this->assertEmpty($validator->errors(['username' => '123']));
  1666. $this->assertNotEmpty($validator->errors(['username' => 'Foo']));
  1667. }
  1668. /**
  1669. * Tests that a rule in the Validator class exists and was configured as expected.
  1670. *
  1671. * @param Validator $validator
  1672. * @param string $method
  1673. * @param mixed $extra
  1674. * @param array $pass
  1675. * @param string|null $name
  1676. */
  1677. protected function assertProxyMethod($validator, $method, $extra = null, $pass = [], $name = null)
  1678. {
  1679. $name = $name ?: $method;
  1680. if ($extra !== null) {
  1681. $this->assertSame($validator, $validator->{$method}('username', $extra));
  1682. } else {
  1683. $this->assertSame($validator, $validator->{$method}('username'));
  1684. }
  1685. $rule = $validator->field('username')->rule($method);
  1686. $this->assertNotEmpty($rule, "Rule was not found for $method");
  1687. $this->assertNull($rule->get('message'), 'Message is present when it should not be');
  1688. $this->assertNull($rule->get('on'), 'On clause is present when it should not be');
  1689. $this->assertEquals($name, $rule->get('rule'), 'Rule name does not match');
  1690. $this->assertEquals($pass, $rule->get('pass'), 'Passed options are different');
  1691. $this->assertEquals('default', $rule->get('provider'), 'Provider does not match');
  1692. if ($extra !== null) {
  1693. $validator->{$method}('username', $extra, 'the message', 'create');
  1694. } else {
  1695. $validator->{$method}('username', 'the message', 'create');
  1696. }
  1697. $rule = $validator->field('username')->rule($method);
  1698. $this->assertEquals('the message', $rule->get('message'), 'Error messages are not the same');
  1699. $this->assertEquals('create', $rule->get('on'), 'On clause is wrong');
  1700. }
  1701. }