ValidatorTest.php 61 KB

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