ValidatorTest.php 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Validation;
  17. use Cake\TestSuite\TestCase;
  18. use Cake\Validation\RulesProvider;
  19. use Cake\Validation\Validation;
  20. use Cake\Validation\ValidationRule;
  21. use Cake\Validation\ValidationSet;
  22. use Cake\Validation\Validator;
  23. use InvalidArgumentException;
  24. use Laminas\Diactoros\UploadedFile;
  25. use stdClass;
  26. /**
  27. * Tests Validator class
  28. */
  29. class ValidatorTest extends TestCase
  30. {
  31. /**
  32. * tests getRequiredMessage
  33. */
  34. public function testGetRequiredMessage(): void
  35. {
  36. $validator = new Validator();
  37. $this->assertNull($validator->getRequiredMessage('field'));
  38. $validator = new Validator();
  39. $validator->requirePresence('field');
  40. $this->assertSame('This field is required', $validator->getRequiredMessage('field'));
  41. $validator = new Validator();
  42. $validator->requirePresence('field', true, 'Custom message');
  43. $this->assertSame('Custom message', $validator->getRequiredMessage('field'));
  44. }
  45. /**
  46. * tests getNotEmptyMessage
  47. */
  48. public function testGetNotEmptyMessage(): void
  49. {
  50. $validator = new Validator();
  51. $this->assertNull($validator->getNotEmptyMessage('field'));
  52. $validator = new Validator();
  53. $validator->requirePresence('field');
  54. $this->assertSame('This field cannot be left empty', $validator->getNotEmptyMessage('field'));
  55. $validator = new Validator();
  56. $validator->notEmptyString('field', 'Custom message');
  57. $this->assertSame('Custom message', $validator->getNotEmptyMessage('field'));
  58. $validator = new Validator();
  59. $validator->notBlank('field', 'Cannot be blank');
  60. $this->assertSame('Cannot be blank', $validator->getNotEmptyMessage('field'));
  61. $validator = new Validator();
  62. $validator->notEmptyString('field', 'Cannot be empty');
  63. $validator->notBlank('field', 'Cannot be blank');
  64. $this->assertSame('Cannot be blank', $validator->getNotEmptyMessage('field'));
  65. }
  66. /**
  67. * Testing you can dynamically add rules to a field
  68. */
  69. public function testAddingRulesToField(): void
  70. {
  71. $validator = new Validator();
  72. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  73. $set = $validator->field('title');
  74. $this->assertInstanceOf(ValidationSet::class, $set);
  75. $this->assertCount(1, $set);
  76. $validator->add('title', 'another', ['rule' => 'alphanumeric']);
  77. $this->assertCount(2, $set);
  78. $validator->add('body', 'another', ['rule' => 'crazy']);
  79. $this->assertCount(1, $validator->field('body'));
  80. $this->assertCount(2, $validator);
  81. $validator->add('email', 'notBlank');
  82. $result = $validator->field('email')->rule('notBlank')->get('rule');
  83. $this->assertSame('notBlank', $result);
  84. $rule = new ValidationRule([]);
  85. $validator->add('field', 'myrule', $rule);
  86. $result = $validator->field('field')->rule('myrule');
  87. $this->assertSame($rule, $result);
  88. }
  89. /**
  90. * Testing addNested field rules
  91. */
  92. public function testAddNestedSingle(): void
  93. {
  94. $validator = new Validator();
  95. $inner = new Validator();
  96. $inner->add('username', 'not-blank', ['rule' => 'notBlank']);
  97. $this->assertSame($validator, $validator->addNested('user', $inner));
  98. $this->assertCount(1, $validator->field('user'));
  99. }
  100. /**
  101. * Testing addNested connects providers
  102. */
  103. public function testAddNestedSingleProviders(): void
  104. {
  105. $validator = new Validator();
  106. $validator->setProvider('test', $this);
  107. $inner = new Validator();
  108. $inner->add('username', 'not-blank', ['rule' => function () use ($inner, $validator) {
  109. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  110. return false;
  111. }]);
  112. $validator->addNested('user', $inner);
  113. $result = $validator->validate(['user' => ['username' => 'example']]);
  114. $this->assertNotEmpty($result, 'Validation should fail');
  115. }
  116. /**
  117. * Testing addNested with extra `$message` and `$when` params
  118. */
  119. public function testAddNestedWithExtra(): void
  120. {
  121. $inner = new Validator();
  122. $inner->requirePresence('username');
  123. $validator = new Validator();
  124. $validator->addNested('user', $inner, 'errors found', 'create');
  125. $this->assertCount(1, $validator->field('user'));
  126. $rule = $validator->field('user')->rule(Validator::NESTED);
  127. $this->assertSame('create', $rule->get('on'));
  128. $errors = $validator->validate(['user' => 'string']);
  129. $this->assertArrayHasKey('user', $errors);
  130. $this->assertArrayHasKey(Validator::NESTED, $errors['user']);
  131. $this->assertSame('errors found', $errors['user'][Validator::NESTED]);
  132. $errors = $validator->validate(['user' => ['key' => 'value']]);
  133. $this->assertArrayHasKey('user', $errors);
  134. $this->assertArrayHasKey(Validator::NESTED, $errors['user']);
  135. $this->assertEmpty($validator->validate(['user' => ['key' => 'value']], false));
  136. }
  137. /**
  138. * Testing addNestedMany field rules
  139. */
  140. public function testAddNestedMany(): void
  141. {
  142. $validator = new Validator();
  143. $inner = new Validator();
  144. $inner->add('comment', 'not-blank', ['rule' => 'notBlank']);
  145. $this->assertSame($validator, $validator->addNestedMany('comments', $inner));
  146. $this->assertCount(1, $validator->field('comments'));
  147. }
  148. /**
  149. * Testing addNestedMany connects providers
  150. */
  151. public function testAddNestedManyProviders(): void
  152. {
  153. $validator = new Validator();
  154. $validator->setProvider('test', $this);
  155. $inner = new Validator();
  156. $inner->add('comment', 'not-blank', ['rule' => function () use ($inner, $validator) {
  157. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  158. return false;
  159. }]);
  160. $validator->addNestedMany('comments', $inner);
  161. $result = $validator->validate(['comments' => [['comment' => 'example']]]);
  162. $this->assertNotEmpty($result, 'Validation should fail');
  163. }
  164. /**
  165. * Testing addNestedMany with extra `$message` and `$when` params
  166. */
  167. public function testAddNestedManyWithExtra(): void
  168. {
  169. $inner = new Validator();
  170. $inner->requirePresence('body');
  171. $validator = new Validator();
  172. $validator->addNestedMany('comments', $inner, 'errors found', 'create');
  173. $this->assertCount(1, $validator->field('comments'));
  174. $rule = $validator->field('comments')->rule(Validator::NESTED);
  175. $this->assertSame('create', $rule->get('on'));
  176. $errors = $validator->validate(['comments' => 'string']);
  177. $this->assertArrayHasKey('comments', $errors);
  178. $this->assertArrayHasKey(Validator::NESTED, $errors['comments']);
  179. $this->assertSame('errors found', $errors['comments'][Validator::NESTED]);
  180. $errors = $validator->validate(['comments' => ['string']]);
  181. $this->assertArrayHasKey('comments', $errors);
  182. $this->assertArrayHasKey(Validator::NESTED, $errors['comments']);
  183. $this->assertSame('errors found', $errors['comments'][Validator::NESTED]);
  184. $errors = $validator->validate(['comments' => [['body' => null]]]);
  185. $this->assertArrayHasKey('comments', $errors);
  186. $this->assertArrayHasKey(Validator::NESTED, $errors['comments']);
  187. $this->assertEmpty($validator->validate(['comments' => [['body' => null]]], false));
  188. }
  189. /**
  190. * Tests that calling field will create a default validation set for it
  191. */
  192. public function testFieldDefault(): void
  193. {
  194. $validator = new Validator();
  195. $this->assertFalse($validator->hasField('foo'));
  196. $field = $validator->field('foo');
  197. $this->assertInstanceOf(ValidationSet::class, $field);
  198. $this->assertCount(0, $field);
  199. $this->assertTrue($validator->hasField('foo'));
  200. }
  201. /**
  202. * Tests that field method can be used as a setter
  203. */
  204. public function testFieldSetter(): void
  205. {
  206. $validator = new Validator();
  207. $validationSet = new ValidationSet();
  208. $validator->field('thing', $validationSet);
  209. $this->assertSame($validationSet, $validator->field('thing'));
  210. }
  211. /**
  212. * Tests the remove method
  213. */
  214. public function testRemove(): void
  215. {
  216. $validator = new Validator();
  217. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  218. $validator->add('title', 'foo', ['rule' => 'bar']);
  219. $this->assertCount(2, $validator->field('title'));
  220. $validator->remove('title');
  221. $this->assertCount(0, $validator->field('title'));
  222. $validator->remove('title');
  223. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  224. $validator->add('title', 'foo', ['rule' => 'bar']);
  225. $this->assertCount(2, $validator->field('title'));
  226. $validator->remove('title', 'foo');
  227. $this->assertCount(1, $validator->field('title'));
  228. $this->assertNull($validator->field('title')->rule('foo'));
  229. }
  230. /**
  231. * Tests the requirePresence method
  232. */
  233. public function testRequirePresence(): void
  234. {
  235. $validator = new Validator();
  236. $this->assertSame($validator, $validator->requirePresence('title'));
  237. $this->assertTrue($validator->field('title')->isPresenceRequired());
  238. $validator->requirePresence('title', false);
  239. $this->assertFalse($validator->field('title')->isPresenceRequired());
  240. $validator->requirePresence('title', 'create');
  241. $this->assertSame('create', $validator->field('title')->isPresenceRequired());
  242. $validator->requirePresence('title', 'update');
  243. $this->assertSame('update', $validator->field('title')->isPresenceRequired());
  244. }
  245. /**
  246. * Tests the requirePresence method with an array
  247. */
  248. public function testRequirePresenceAsArray(): void
  249. {
  250. $validator = new Validator();
  251. $validator->requirePresence(['title', 'created']);
  252. $this->assertTrue($validator->field('title')->isPresenceRequired());
  253. $this->assertTrue($validator->field('created')->isPresenceRequired());
  254. $validator->requirePresence([
  255. 'title' => [
  256. 'mode' => false,
  257. ],
  258. 'content' => [
  259. 'mode' => 'update',
  260. ],
  261. 'subject',
  262. ], true);
  263. $this->assertFalse($validator->field('title')->isPresenceRequired());
  264. $this->assertSame('update', $validator->field('content')->isPresenceRequired());
  265. $this->assertTrue($validator->field('subject')->isPresenceRequired());
  266. }
  267. /**
  268. * Tests the requirePresence method with an array containing an integer key
  269. */
  270. public function testRequirePresenceAsArrayWithIntegerKey(): void
  271. {
  272. $validator = new Validator();
  273. $validator->requirePresence([
  274. 0,
  275. 1 => [
  276. 'mode' => false,
  277. ],
  278. 'another_field',
  279. ]);
  280. $this->assertTrue($validator->field('0')->isPresenceRequired());
  281. $this->assertFalse($validator->field('1')->isPresenceRequired());
  282. }
  283. /**
  284. * Tests the requirePresence method when passing a callback
  285. */
  286. public function testRequirePresenceCallback(): void
  287. {
  288. $validator = new Validator();
  289. $require = true;
  290. $validator->requirePresence('title', function ($context) use (&$require) {
  291. $this->assertEquals([], $context['data']);
  292. $this->assertEquals([], $context['providers']);
  293. $this->assertSame('title', $context['field']);
  294. $this->assertTrue($context['newRecord']);
  295. return $require;
  296. });
  297. $this->assertTrue($validator->isPresenceRequired('title', true));
  298. // phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable
  299. $require = false;
  300. $this->assertFalse($validator->isPresenceRequired('title', true));
  301. }
  302. /**
  303. * Tests the isPresenceRequired method
  304. */
  305. public function testIsPresenceRequired(): void
  306. {
  307. $validator = new Validator();
  308. $this->assertSame($validator, $validator->requirePresence('title'));
  309. $this->assertTrue($validator->isPresenceRequired('title', true));
  310. $this->assertTrue($validator->isPresenceRequired('title', false));
  311. $validator->requirePresence('title', false);
  312. $this->assertFalse($validator->isPresenceRequired('title', true));
  313. $this->assertFalse($validator->isPresenceRequired('title', false));
  314. $validator->requirePresence('title', 'create');
  315. $this->assertTrue($validator->isPresenceRequired('title', true));
  316. $this->assertFalse($validator->isPresenceRequired('title', false));
  317. $validator->requirePresence('title', 'update');
  318. $this->assertTrue($validator->isPresenceRequired('title', false));
  319. $this->assertFalse($validator->isPresenceRequired('title', true));
  320. }
  321. /**
  322. * Tests errors generated when a field presence is required
  323. */
  324. public function testErrorsWithPresenceRequired(): void
  325. {
  326. $validator = new Validator();
  327. $validator->requirePresence('title');
  328. $errors = $validator->validate(['foo' => 'something']);
  329. $expected = ['title' => ['_required' => 'This field is required']];
  330. $this->assertEquals($expected, $errors);
  331. $this->assertEmpty($validator->validate(['title' => 'bar']));
  332. $validator->requirePresence('title', false);
  333. $this->assertEmpty($validator->validate(['foo' => 'bar']));
  334. }
  335. /**
  336. * Test that validation on a certain condition generate errors
  337. */
  338. public function testErrorsWithPresenceRequiredOnCreate(): void
  339. {
  340. $validator = new Validator();
  341. $validator->requirePresence('id', 'update');
  342. $validator->allowEmptyString('id', 'create');
  343. $validator->requirePresence('title');
  344. $data = [
  345. 'title' => 'Example title',
  346. ];
  347. $expected = [];
  348. $result = $validator->validate($data);
  349. $this->assertEquals($expected, $result);
  350. }
  351. /**
  352. * Test that validate() can work with nested data.
  353. */
  354. public function testErrorsWithNestedFields(): void
  355. {
  356. $validator = new Validator();
  357. $user = new Validator();
  358. $user->add('username', 'letter', ['rule' => 'alphanumeric']);
  359. $comments = new Validator();
  360. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  361. $validator->addNested('user', $user);
  362. $validator->addNestedMany('comments', $comments);
  363. $data = [
  364. 'user' => [
  365. 'username' => 'is wrong',
  366. ],
  367. 'comments' => [
  368. ['comment' => 'is wrong'],
  369. ],
  370. ];
  371. $errors = $validator->validate($data);
  372. $expected = [
  373. 'user' => [
  374. 'username' => ['letter' => 'The provided value is invalid'],
  375. ],
  376. 'comments' => [
  377. 0 => ['comment' => ['letter' => 'The provided value is invalid']],
  378. ],
  379. ];
  380. $this->assertEquals($expected, $errors);
  381. }
  382. /**
  383. * Test nested fields with many, but invalid data.
  384. */
  385. public function testErrorsWithNestedSingleInvalidType(): void
  386. {
  387. $validator = new Validator();
  388. $user = new Validator();
  389. $user->add('user', 'letter', ['rule' => 'alphanumeric']);
  390. $validator->addNested('user', $user);
  391. $data = [
  392. 'user' => 'a string',
  393. ];
  394. $errors = $validator->validate($data);
  395. $expected = [
  396. 'user' => ['_nested' => 'The provided value is invalid'],
  397. ];
  398. $this->assertEquals($expected, $errors);
  399. }
  400. /**
  401. * Test nested fields with many, but invalid data.
  402. */
  403. public function testErrorsWithNestedManyInvalidType(): void
  404. {
  405. $validator = new Validator();
  406. $comments = new Validator();
  407. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  408. $validator->addNestedMany('comments', $comments);
  409. $data = [
  410. 'comments' => 'a string',
  411. ];
  412. $errors = $validator->validate($data);
  413. $expected = [
  414. 'comments' => ['_nested' => 'The provided value is invalid'],
  415. ];
  416. $this->assertEquals($expected, $errors);
  417. }
  418. /**
  419. * Test nested fields with many, but invalid data.
  420. */
  421. public function testErrorsWithNestedManySomeInvalid(): void
  422. {
  423. $validator = new Validator();
  424. $comments = new Validator();
  425. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  426. $validator->addNestedMany('comments', $comments);
  427. $data = [
  428. 'comments' => [
  429. 'a string',
  430. ['comment' => 'letters'],
  431. ['comment' => 'more invalid'],
  432. ],
  433. ];
  434. $errors = $validator->validate($data);
  435. $expected = [
  436. 'comments' => [
  437. '_nested' => 'The provided value is invalid',
  438. ],
  439. ];
  440. $this->assertEquals($expected, $errors);
  441. }
  442. /**
  443. * Tests custom error messages generated when a field presence is required
  444. */
  445. public function testCustomErrorsWithPresenceRequired(): void
  446. {
  447. $validator = new Validator();
  448. $validator->requirePresence('title', true, 'Custom message');
  449. $errors = $validator->validate(['foo' => 'something']);
  450. $expected = ['title' => ['_required' => 'Custom message']];
  451. $this->assertEquals($expected, $errors);
  452. }
  453. /**
  454. * Tests custom error messages generated when a field presence is required
  455. */
  456. public function testCustomErrorsWithPresenceRequiredAsArray(): void
  457. {
  458. $validator = new Validator();
  459. $validator->requirePresence(['title', 'content'], true, 'Custom message');
  460. $errors = $validator->validate(['foo' => 'something']);
  461. $expected = [
  462. 'title' => ['_required' => 'Custom message'],
  463. 'content' => ['_required' => 'Custom message'],
  464. ];
  465. $this->assertEquals($expected, $errors);
  466. $validator->requirePresence([
  467. 'title' => [
  468. 'message' => 'Test message',
  469. ],
  470. 'content',
  471. ], true, 'Custom message');
  472. $errors = $validator->validate(['foo' => 'something']);
  473. $expected = [
  474. 'title' => ['_required' => 'Test message'],
  475. 'content' => ['_required' => 'Custom message'],
  476. ];
  477. $this->assertEquals($expected, $errors);
  478. }
  479. /**
  480. * Tests the testAllowEmptyFor method
  481. */
  482. public function testAllowEmptyFor(): void
  483. {
  484. $validator = new Validator();
  485. $validator
  486. ->allowEmptyFor('title')
  487. ->minLength('title', 5, 'Min. length 5 chars');
  488. $results = $validator->validate(['title' => null]);
  489. $this->assertSame([], $results);
  490. $results = $validator->validate(['title' => '']);
  491. $this->assertSame(['title' => ['minLength' => 'Min. length 5 chars']], $results);
  492. $results = $validator->validate(['title' => 0]);
  493. $this->assertSame(['title' => ['minLength' => 'Min. length 5 chars']], $results);
  494. $results = $validator->validate(['title' => []]);
  495. $this->assertSame(['title' => ['minLength' => 'Min. length 5 chars']], $results);
  496. $validator
  497. ->allowEmptyFor('name', Validator::EMPTY_STRING)
  498. ->minLength('name', 5, 'Min. length 5 chars');
  499. $results = $validator->validate(['name' => null]);
  500. $this->assertSame([], $results);
  501. $results = $validator->validate(['name' => '']);
  502. $this->assertSame([], $results);
  503. $results = $validator->validate(['name' => 0]);
  504. $this->assertSame(['name' => ['minLength' => 'Min. length 5 chars']], $results);
  505. $results = $validator->validate(['name' => []]);
  506. $this->assertSame(['name' => ['minLength' => 'Min. length 5 chars']], $results);
  507. }
  508. /**
  509. * Tests the allowEmpty method
  510. */
  511. public function testAllowEmpty(): void
  512. {
  513. $validator = new Validator();
  514. $this->assertSame($validator, $validator->allowEmptyString('title'));
  515. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  516. $validator->allowEmptyString('title', null, 'create');
  517. $this->assertSame('create', $validator->field('title')->isEmptyAllowed());
  518. $validator->allowEmptyString('title', null, 'update');
  519. $this->assertSame('update', $validator->field('title')->isEmptyAllowed());
  520. }
  521. /**
  522. * Tests the allowEmpty method with date/time fields.
  523. */
  524. public function testAllowEmptyWithDateTimeFields(): void
  525. {
  526. $validator = new Validator();
  527. $validator->allowEmptyDate('created')
  528. ->add('created', 'date', ['rule' => 'date']);
  529. $data = [
  530. 'created' => [
  531. 'year' => '',
  532. 'month' => '',
  533. 'day' => '',
  534. ],
  535. ];
  536. $result = $validator->validate($data);
  537. $this->assertEmpty($result, 'No errors on empty date');
  538. $data = [
  539. 'created' => [
  540. 'year' => '',
  541. 'month' => '',
  542. 'day' => '',
  543. 'hour' => '',
  544. 'minute' => '',
  545. 'second' => '',
  546. 'meridian' => '',
  547. ],
  548. ];
  549. $result = $validator->validate($data);
  550. $this->assertEmpty($result, 'No errors on empty datetime');
  551. $validator->allowEmptyTime('created');
  552. $data = [
  553. 'created' => [
  554. 'hour' => '',
  555. 'minute' => '',
  556. 'meridian' => '',
  557. ],
  558. ];
  559. $result = $validator->validate($data);
  560. $this->assertEmpty($result, 'No errors on empty time');
  561. }
  562. /**
  563. * Tests the allowEmpty method with file fields.
  564. */
  565. public function testAllowEmptyWithFileFields(): void
  566. {
  567. $validator = new Validator();
  568. $validator->allowEmptyFile('picture')
  569. ->add('picture', 'file', ['rule' => 'uploadedFile']);
  570. $data = [
  571. 'picture' => new UploadedFile(
  572. '',
  573. 0,
  574. UPLOAD_ERR_NO_FILE
  575. ),
  576. ];
  577. $result = $validator->validate($data);
  578. $this->assertEmpty($result, 'No errors on empty file');
  579. }
  580. /**
  581. * Tests the allowEmptyString method
  582. */
  583. public function testAllowEmptyString(): void
  584. {
  585. $validator = new Validator();
  586. $validator->allowEmptyString('title')
  587. ->scalar('title');
  588. $this->assertTrue($validator->isEmptyAllowed('title', true));
  589. $this->assertTrue($validator->isEmptyAllowed('title', false));
  590. $data = [
  591. 'title' => '',
  592. ];
  593. $this->assertEmpty($validator->validate($data));
  594. $data = [
  595. 'title' => null,
  596. ];
  597. $this->assertEmpty($validator->validate($data));
  598. $data = [
  599. 'title' => [],
  600. ];
  601. $this->assertNotEmpty($validator->validate($data));
  602. $validator = new Validator();
  603. $validator->allowEmptyString('title', 'message', 'update');
  604. $this->assertFalse($validator->isEmptyAllowed('title', true));
  605. $this->assertTrue($validator->isEmptyAllowed('title', false));
  606. $data = [
  607. 'title' => null,
  608. ];
  609. $expected = [
  610. 'title' => ['_empty' => 'message'],
  611. ];
  612. $this->assertSame($expected, $validator->validate($data, true));
  613. $this->assertEmpty($validator->validate($data, false));
  614. }
  615. /**
  616. * Test allowEmptyString with callback
  617. */
  618. public function testAllowEmptyStringCallbackWhen(): void
  619. {
  620. $validator = new Validator();
  621. $validator->allowEmptyString(
  622. 'title',
  623. 'very required',
  624. function ($context) {
  625. return $context['data']['otherField'] === true;
  626. }
  627. )
  628. ->scalar('title');
  629. $data = [
  630. 'title' => '',
  631. 'otherField' => false,
  632. ];
  633. $this->assertNotEmpty($validator->validate($data));
  634. $data = [
  635. 'title' => '',
  636. 'otherField' => true,
  637. ];
  638. $this->assertEmpty($validator->validate($data));
  639. }
  640. /**
  641. * Tests the notEmptyArray method
  642. */
  643. public function testNotEmptyArray(): void
  644. {
  645. $validator = new Validator();
  646. $validator->notEmptyArray('items', 'not empty');
  647. $this->assertFalse($validator->field('items')->isEmptyAllowed());
  648. $error = [
  649. 'items' => ['_empty' => 'not empty'],
  650. ];
  651. $data = ['items' => ''];
  652. $result = $validator->validate($data);
  653. $this->assertSame($error, $result);
  654. $data = ['items' => null];
  655. $result = $validator->validate($data);
  656. $this->assertSame($error, $result);
  657. $data = ['items' => []];
  658. $result = $validator->validate($data);
  659. $this->assertSame($error, $result);
  660. $data = [
  661. 'items' => [1],
  662. ];
  663. $result = $validator->validate($data);
  664. $this->assertEmpty($result);
  665. }
  666. /**
  667. * Tests the allowEmptyFile method
  668. */
  669. public function testAllowEmptyFile(): void
  670. {
  671. $validator = new Validator();
  672. $validator->allowEmptyFile('photo')
  673. ->uploadedFile('photo', []);
  674. $this->assertTrue($validator->field('photo')->isEmptyAllowed());
  675. $data = [
  676. 'photo' => null,
  677. ];
  678. $result = $validator->validate($data);
  679. $this->assertEmpty($result);
  680. $data = [
  681. 'photo' => [],
  682. ];
  683. $expected = [
  684. 'photo' => [
  685. 'uploadedFile' => 'The provided value must be an uploaded file',
  686. ],
  687. ];
  688. $result = $validator->validate($data);
  689. $this->assertSame($expected, $result);
  690. $data = [
  691. 'photo' => '',
  692. ];
  693. $result = $validator->validate($data);
  694. $this->assertSame($expected, $result);
  695. $data = ['photo' => []];
  696. $result = $validator->validate($data);
  697. $this->assertSame($expected, $result);
  698. $validator = new Validator();
  699. $validator->allowEmptyFile('photo', 'message', 'update');
  700. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  701. $this->assertTrue($validator->isEmptyAllowed('photo', false));
  702. $data = [
  703. 'photo' => null,
  704. ];
  705. $expected = [
  706. 'photo' => ['_empty' => 'message'],
  707. ];
  708. $this->assertSame($expected, $validator->validate($data, true));
  709. $this->assertEmpty($validator->validate($data, false));
  710. }
  711. /**
  712. * Tests the notEmptyFile method
  713. */
  714. public function testNotEmptyFile(): void
  715. {
  716. $validator = new Validator();
  717. $validator->notEmptyFile('photo', 'required field');
  718. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  719. $this->assertFalse($validator->isEmptyAllowed('photo', false));
  720. $error = ['photo' => ['_empty' => 'required field']];
  721. $data = ['photo' => null];
  722. $this->assertSame($error, $validator->validate($data));
  723. // Empty string and empty array don't trigger errors
  724. // as rejecting them here would mean accepting them in
  725. // allowEmptyFile() which is not desirable.
  726. $data = ['photo' => ''];
  727. $this->assertEmpty($validator->validate($data));
  728. $data = ['photo' => []];
  729. $this->assertEmpty($validator->validate($data));
  730. $data = [
  731. 'photo' => [
  732. 'name' => '',
  733. 'type' => '',
  734. 'tmp_name' => '',
  735. 'error' => UPLOAD_ERR_FORM_SIZE,
  736. ],
  737. ];
  738. $this->assertEmpty($validator->validate($data));
  739. }
  740. /**
  741. * Test notEmptyFile with update mode.
  742. *
  743. * @retrn void
  744. */
  745. public function testNotEmptyFileUpdate(): void
  746. {
  747. $validator = new Validator();
  748. $validator->notEmptyArray('photo', 'message', 'update');
  749. $this->assertTrue($validator->isEmptyAllowed('photo', true));
  750. $this->assertFalse($validator->isEmptyAllowed('photo', false));
  751. $data = ['photo' => null];
  752. $expected = [
  753. 'photo' => ['_empty' => 'message'],
  754. ];
  755. $this->assertEmpty($validator->validate($data, true));
  756. $this->assertSame($expected, $validator->validate($data, false));
  757. }
  758. /**
  759. * Tests the allowEmptyDate method
  760. */
  761. public function testAllowEmptyDate(): void
  762. {
  763. $validator = new Validator();
  764. $validator->allowEmptyDate('date')
  765. ->date('date');
  766. $this->assertTrue($validator->field('date')->isEmptyAllowed());
  767. $data = [
  768. 'date' => [
  769. 'year' => '',
  770. 'month' => '',
  771. 'day' => '',
  772. ],
  773. ];
  774. $result = $validator->validate($data);
  775. $this->assertEmpty($result);
  776. $data = [
  777. 'date' => '',
  778. ];
  779. $result = $validator->validate($data);
  780. $this->assertEmpty($result);
  781. $data = [
  782. 'date' => null,
  783. ];
  784. $result = $validator->validate($data);
  785. $this->assertEmpty($result);
  786. $data = ['date' => []];
  787. $result = $validator->validate($data);
  788. $this->assertEmpty($result);
  789. }
  790. /**
  791. * test allowEmptyDate() with an update condition
  792. */
  793. public function testAllowEmptyDateUpdate(): void
  794. {
  795. $validator = new Validator();
  796. $validator->allowEmptyArray('date', 'be valid', 'update');
  797. $this->assertFalse($validator->isEmptyAllowed('date', true));
  798. $this->assertTrue($validator->isEmptyAllowed('date', false));
  799. $data = [
  800. 'date' => null,
  801. ];
  802. $expected = [
  803. 'date' => ['_empty' => 'be valid'],
  804. ];
  805. $this->assertSame($expected, $validator->validate($data, true));
  806. $this->assertEmpty($validator->validate($data, false));
  807. }
  808. /**
  809. * Tests the notEmptyDate method
  810. */
  811. public function testNotEmptyDate(): void
  812. {
  813. $validator = new Validator();
  814. $validator->notEmptyDate('date', 'required field');
  815. $this->assertFalse($validator->isEmptyAllowed('date', true));
  816. $this->assertFalse($validator->isEmptyAllowed('date', false));
  817. $error = ['date' => ['_empty' => 'required field']];
  818. $data = [
  819. 'date' => [
  820. 'year' => '',
  821. 'month' => '',
  822. 'day' => '',
  823. ],
  824. ];
  825. $result = $validator->validate($data);
  826. $this->assertSame($error, $result);
  827. $data = ['date' => ''];
  828. $result = $validator->validate($data);
  829. $this->assertSame($error, $result);
  830. $data = ['date' => null];
  831. $result = $validator->validate($data);
  832. $this->assertSame($error, $result);
  833. $data = ['date' => []];
  834. $result = $validator->validate($data);
  835. $this->assertSame($error, $result);
  836. $data = [
  837. 'date' => [
  838. 'year' => 2019,
  839. 'month' => 2,
  840. 'day' => 17,
  841. ],
  842. ];
  843. $result = $validator->validate($data);
  844. $this->assertEmpty($result);
  845. }
  846. /**
  847. * Test notEmptyDate with update mode
  848. */
  849. public function testNotEmptyDateUpdate(): void
  850. {
  851. $validator = new Validator();
  852. $validator->notEmptyDate('date', 'message', 'update');
  853. $this->assertTrue($validator->isEmptyAllowed('date', true));
  854. $this->assertFalse($validator->isEmptyAllowed('date', false));
  855. $data = ['date' => null];
  856. $expected = ['date' => ['_empty' => 'message']];
  857. $this->assertSame($expected, $validator->validate($data, false));
  858. $this->assertEmpty($validator->validate($data, true));
  859. }
  860. /**
  861. * Tests the allowEmptyTime method
  862. */
  863. public function testAllowEmptyTime(): void
  864. {
  865. $validator = new Validator();
  866. $validator->allowEmptyTime('time')
  867. ->time('time');
  868. $this->assertTrue($validator->field('time')->isEmptyAllowed());
  869. $data = [
  870. 'time' => [
  871. 'hour' => '',
  872. 'minute' => '',
  873. 'second' => '',
  874. ],
  875. ];
  876. $result = $validator->validate($data);
  877. $this->assertEmpty($result);
  878. $data = [
  879. 'time' => '',
  880. ];
  881. $result = $validator->validate($data);
  882. $this->assertEmpty($result);
  883. $data = [
  884. 'time' => null,
  885. ];
  886. $result = $validator->validate($data);
  887. $this->assertEmpty($result);
  888. $data = ['time' => []];
  889. $result = $validator->validate($data);
  890. $this->assertEmpty($result);
  891. }
  892. /**
  893. * test allowEmptyTime with condition
  894. */
  895. public function testAllowEmptyTimeCondition(): void
  896. {
  897. $validator = new Validator();
  898. $validator->allowEmptyTime('time', 'valid time', 'update');
  899. $this->assertFalse($validator->isEmptyAllowed('time', true));
  900. $this->assertTrue($validator->isEmptyAllowed('time', false));
  901. $data = [
  902. 'time' => null,
  903. ];
  904. $expected = [
  905. 'time' => ['_empty' => 'valid time'],
  906. ];
  907. $this->assertSame($expected, $validator->validate($data, true));
  908. $this->assertEmpty($validator->validate($data, false));
  909. }
  910. /**
  911. * Tests the notEmptyTime method
  912. */
  913. public function testNotEmptyTime(): void
  914. {
  915. $validator = new Validator();
  916. $validator->notEmptyTime('time', 'required field');
  917. $this->assertFalse($validator->isEmptyAllowed('time', true));
  918. $this->assertFalse($validator->isEmptyAllowed('time', false));
  919. $error = ['time' => ['_empty' => 'required field']];
  920. $data = [
  921. 'time' => [
  922. 'hour' => '',
  923. 'minute' => '',
  924. 'second' => '',
  925. ],
  926. ];
  927. $result = $validator->validate($data);
  928. $this->assertSame($error, $result);
  929. $data = ['time' => ''];
  930. $result = $validator->validate($data);
  931. $this->assertSame($error, $result);
  932. $data = ['time' => null];
  933. $result = $validator->validate($data);
  934. $this->assertSame($error, $result);
  935. $data = ['time' => []];
  936. $result = $validator->validate($data);
  937. $this->assertSame($error, $result);
  938. $data = ['time' => ['hour' => 12, 'minute' => 12, 'second' => 12]];
  939. $result = $validator->validate($data);
  940. $this->assertEmpty($result);
  941. }
  942. /**
  943. * Test notEmptyTime with update mode
  944. */
  945. public function testNotEmptyTimeUpdate(): void
  946. {
  947. $validator = new Validator();
  948. $validator->notEmptyTime('time', 'message', 'update');
  949. $this->assertTrue($validator->isEmptyAllowed('time', true));
  950. $this->assertFalse($validator->isEmptyAllowed('time', false));
  951. $data = ['time' => null];
  952. $expected = ['time' => ['_empty' => 'message']];
  953. $this->assertEmpty($validator->validate($data, true));
  954. $this->assertSame($expected, $validator->validate($data, false));
  955. }
  956. /**
  957. * Tests the allowEmptyDateTime method
  958. */
  959. public function testAllowEmptyDateTime(): void
  960. {
  961. $validator = new Validator();
  962. $validator->allowEmptyDate('published')
  963. ->dateTime('published');
  964. $this->assertTrue($validator->field('published')->isEmptyAllowed());
  965. $data = [
  966. 'published' => [
  967. 'year' => '',
  968. 'month' => '',
  969. 'day' => '',
  970. 'hour' => '',
  971. 'minute' => '',
  972. 'second' => '',
  973. ],
  974. ];
  975. $result = $validator->validate($data);
  976. $this->assertEmpty($result);
  977. $data = [
  978. 'published' => '',
  979. ];
  980. $result = $validator->validate($data);
  981. $this->assertEmpty($result);
  982. $data = [
  983. 'published' => null,
  984. ];
  985. $result = $validator->validate($data);
  986. $this->assertEmpty($result);
  987. $data = ['published' => []];
  988. $this->assertEmpty($validator->validate($data));
  989. }
  990. /**
  991. * test allowEmptyDateTime with a condition
  992. */
  993. public function testAllowEmptyDateTimeCondition(): void
  994. {
  995. $validator = new Validator();
  996. $validator->allowEmptyDateTime('published', 'datetime required', 'update');
  997. $this->assertFalse($validator->isEmptyAllowed('published', true));
  998. $this->assertTrue($validator->isEmptyAllowed('published', false));
  999. $data = [
  1000. 'published' => null,
  1001. ];
  1002. $expected = [
  1003. 'published' => ['_empty' => 'datetime required'],
  1004. ];
  1005. $this->assertSame($expected, $validator->validate($data, true));
  1006. $this->assertEmpty($validator->validate($data, false));
  1007. }
  1008. /**
  1009. * Tests the notEmptyDateTime method
  1010. */
  1011. public function testNotEmptyDateTime(): void
  1012. {
  1013. $validator = new Validator();
  1014. $validator->notEmptyDateTime('published', 'required field');
  1015. $this->assertFalse($validator->isEmptyAllowed('published', true));
  1016. $this->assertFalse($validator->isEmptyAllowed('published', false));
  1017. $error = ['published' => ['_empty' => 'required field']];
  1018. $data = [
  1019. 'published' => [
  1020. 'year' => '',
  1021. 'month' => '',
  1022. 'day' => '',
  1023. 'hour' => '',
  1024. 'minute' => '',
  1025. 'second' => '',
  1026. ],
  1027. ];
  1028. $result = $validator->validate($data);
  1029. $this->assertSame($error, $result);
  1030. $data = ['published' => ''];
  1031. $result = $validator->validate($data);
  1032. $this->assertSame($error, $result);
  1033. $data = ['published' => null];
  1034. $result = $validator->validate($data);
  1035. $this->assertSame($error, $result);
  1036. $data = ['published' => []];
  1037. $this->assertSame($error, $validator->validate($data));
  1038. $data = [
  1039. 'published' => [
  1040. 'year' => '2018',
  1041. 'month' => '2',
  1042. 'day' => '17',
  1043. 'hour' => '14',
  1044. 'minute' => '32',
  1045. 'second' => '33',
  1046. ],
  1047. ];
  1048. $this->assertEmpty($validator->validate($data));
  1049. }
  1050. /**
  1051. * Test notEmptyDateTime with update mode
  1052. */
  1053. public function testNotEmptyDateTimeUpdate(): void
  1054. {
  1055. $validator = new Validator();
  1056. $validator->notEmptyDateTime('published', 'message', 'update');
  1057. $this->assertTrue($validator->isEmptyAllowed('published', true));
  1058. $this->assertFalse($validator->isEmptyAllowed('published', false));
  1059. $data = ['published' => null];
  1060. $expected = ['published' => ['_empty' => 'message']];
  1061. $this->assertSame($expected, $validator->validate($data, false));
  1062. $this->assertEmpty($validator->validate($data, true));
  1063. }
  1064. /**
  1065. * Test the notEmpty() method.
  1066. */
  1067. public function testNotEmpty(): void
  1068. {
  1069. $validator = new Validator();
  1070. $validator->notEmptyString('title');
  1071. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  1072. $validator->allowEmptyString('title');
  1073. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  1074. }
  1075. /**
  1076. * Test the notEmpty() method.
  1077. */
  1078. public function testNotEmptyModes(): void
  1079. {
  1080. $validator = new Validator();
  1081. $validator->notEmptyString('title', 'Need a title', 'create');
  1082. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1083. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1084. $validator->notEmptyString('title', 'Need a title', 'update');
  1085. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1086. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1087. $validator->notEmptyString('title', 'Need a title');
  1088. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1089. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1090. $validator->notEmptyString('title');
  1091. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1092. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1093. }
  1094. /**
  1095. * Test interactions between notEmpty() and isAllowed().
  1096. */
  1097. public function testNotEmptyAndIsAllowed(): void
  1098. {
  1099. $validator = new Validator();
  1100. $validator->allowEmptyString('title')
  1101. ->notEmptyString('title', 'Need it', 'update');
  1102. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1103. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1104. $validator->allowEmptyString('title')
  1105. ->notEmptyString('title');
  1106. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1107. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1108. $validator->notEmptyString('title')
  1109. ->allowEmptyString('title', null, 'create');
  1110. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1111. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1112. }
  1113. /**
  1114. * Tests the allowEmpty method when passing a callback
  1115. */
  1116. public function testAllowEmptyCallback(): void
  1117. {
  1118. $validator = new Validator();
  1119. $allow = true;
  1120. $validator->allowEmptyString('title', null, function ($context) use (&$allow) {
  1121. $this->assertEquals([], $context['data']);
  1122. $this->assertEquals([], $context['providers']);
  1123. $this->assertTrue($context['newRecord']);
  1124. return $allow;
  1125. });
  1126. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1127. // phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable
  1128. $allow = false;
  1129. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1130. }
  1131. /**
  1132. * Tests the notEmpty method when passing a callback
  1133. */
  1134. public function testNotEmptyCallback(): void
  1135. {
  1136. $validator = new Validator();
  1137. $prevent = true;
  1138. $validator->notEmptyString('title', 'error message', function ($context) use (&$prevent) {
  1139. $this->assertEquals([], $context['data']);
  1140. $this->assertEquals([], $context['providers']);
  1141. $this->assertFalse($context['newRecord']);
  1142. return $prevent;
  1143. });
  1144. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1145. // phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable
  1146. $prevent = false;
  1147. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1148. }
  1149. /**
  1150. * Tests the isEmptyAllowed method
  1151. */
  1152. public function testIsEmptyAllowed(): void
  1153. {
  1154. $validator = new Validator();
  1155. $this->assertSame($validator, $validator->allowEmptyString('title'));
  1156. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1157. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1158. $validator->notEmptyString('title');
  1159. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1160. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1161. $validator->allowEmptyString('title', null, 'create');
  1162. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1163. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1164. $validator->allowEmptyString('title', null, 'update');
  1165. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1166. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1167. }
  1168. /**
  1169. * Tests errors generated when a field is not allowed to be empty
  1170. */
  1171. public function testErrorsWithEmptyNotAllowed(): void
  1172. {
  1173. $validator = new Validator();
  1174. $validator->notEmptyString('title');
  1175. $errors = $validator->validate(['title' => '']);
  1176. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1177. $this->assertEquals($expected, $errors);
  1178. $errors = $validator->validate(['title' => null]);
  1179. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1180. $this->assertEquals($expected, $errors);
  1181. $errors = $validator->validate(['title' => 0]);
  1182. $this->assertEmpty($errors);
  1183. $errors = $validator->validate(['title' => '0']);
  1184. $this->assertEmpty($errors);
  1185. $errors = $validator->validate(['title' => false]);
  1186. $this->assertEmpty($errors);
  1187. }
  1188. /**
  1189. * Tests custom error messages generated when a field is allowed to be empty
  1190. */
  1191. public function testCustomErrorsWithAllowedEmpty(): void
  1192. {
  1193. $validator = new Validator();
  1194. $validator->allowEmptyString('title', 'Custom message', false);
  1195. $errors = $validator->validate(['title' => null]);
  1196. $expected = ['title' => ['_empty' => 'Custom message']];
  1197. $this->assertEquals($expected, $errors);
  1198. }
  1199. /**
  1200. * Tests custom error messages generated when a field is not allowed to be empty
  1201. */
  1202. public function testCustomErrorsWithEmptyNotAllowed(): void
  1203. {
  1204. $validator = new Validator();
  1205. $validator->notEmptyString('title', 'Custom message');
  1206. $errors = $validator->validate(['title' => '']);
  1207. $expected = ['title' => ['_empty' => 'Custom message']];
  1208. $this->assertEquals($expected, $errors);
  1209. }
  1210. /**
  1211. * Tests errors generated when a field is allowed to be empty
  1212. */
  1213. public function testErrorsWithEmptyAllowed(): void
  1214. {
  1215. $validator = new Validator();
  1216. $validator->allowEmptyString('title');
  1217. $errors = $validator->validate(['title' => '']);
  1218. $this->assertEmpty($errors);
  1219. $errors = $validator->validate(['title' => []]);
  1220. $this->assertEmpty($errors);
  1221. $errors = $validator->validate(['title' => null]);
  1222. $this->assertEmpty($errors);
  1223. $errors = $validator->validate(['title' => 0]);
  1224. $this->assertEmpty($errors);
  1225. $errors = $validator->validate(['title' => 0.0]);
  1226. $this->assertEmpty($errors);
  1227. $errors = $validator->validate(['title' => '0']);
  1228. $this->assertEmpty($errors);
  1229. $errors = $validator->validate(['title' => false]);
  1230. $this->assertEmpty($errors);
  1231. }
  1232. /**
  1233. * Test the provider() method
  1234. */
  1235. public function testProvider(): void
  1236. {
  1237. $validator = new Validator();
  1238. $object = new stdClass();
  1239. $this->assertSame($validator, $validator->setProvider('foo', $object));
  1240. $this->assertSame($object, $validator->getProvider('foo'));
  1241. $this->assertNull($validator->getProvider('bar'));
  1242. $another = new stdClass();
  1243. $this->assertSame($validator, $validator->setProvider('bar', $another));
  1244. $this->assertSame($another, $validator->getProvider('bar'));
  1245. $this->assertEquals(new RulesProvider(), $validator->getProvider('default'));
  1246. }
  1247. /**
  1248. * Tests validate() method when using validators from the default provider, this proves
  1249. * that it returns a default validation message and the custom one set in the rule
  1250. */
  1251. public function testErrorsFromDefaultProvider(): void
  1252. {
  1253. $validator = new Validator();
  1254. $validator
  1255. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1256. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  1257. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1258. $errors = $validator->validate(['email' => 'not an email!']);
  1259. $expected = [
  1260. 'email' => [
  1261. 'alpha' => 'The provided value is invalid',
  1262. 'email' => 'Y u no write email?',
  1263. ],
  1264. ];
  1265. $this->assertEquals($expected, $errors);
  1266. }
  1267. /**
  1268. * Tests using validation methods from different providers and returning the error
  1269. * as a string
  1270. */
  1271. public function testErrorsFromCustomProvider(): void
  1272. {
  1273. $validator = new Validator();
  1274. $validator
  1275. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1276. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1277. $thing = $this->getMockBuilder('\stdClass')
  1278. ->addMethods(['isCool'])
  1279. ->getMock();
  1280. $thing->expects($this->once())->method('isCool')
  1281. ->willReturnCallback(function ($data, $context) use ($thing) {
  1282. $this->assertSame('bar', $data);
  1283. $expected = [
  1284. 'default' => new RulesProvider(),
  1285. 'thing' => $thing,
  1286. ];
  1287. $expected = [
  1288. 'newRecord' => true,
  1289. 'providers' => $expected,
  1290. 'data' => [
  1291. 'email' => '!',
  1292. 'title' => 'bar',
  1293. ],
  1294. 'field' => 'title',
  1295. ];
  1296. $this->assertEquals($expected, $context);
  1297. return "That ain't cool, yo";
  1298. });
  1299. $validator->setProvider('thing', $thing);
  1300. $errors = $validator->validate(['email' => '!', 'title' => 'bar']);
  1301. $expected = [
  1302. 'email' => ['alpha' => 'The provided value is invalid'],
  1303. 'title' => ['cool' => "That ain't cool, yo"],
  1304. ];
  1305. $this->assertEquals($expected, $errors);
  1306. }
  1307. /**
  1308. * Tests that it is possible to pass extra arguments to the validation function
  1309. * and it still gets the providers as last argument
  1310. */
  1311. public function testMethodsWithExtraArguments(): void
  1312. {
  1313. $validator = new Validator();
  1314. $validator->add('title', 'cool', [
  1315. 'rule' => ['isCool', 'and', 'awesome'],
  1316. 'provider' => 'thing',
  1317. ]);
  1318. $thing = $this->getMockBuilder('\stdClass')
  1319. ->addMethods(['isCool'])
  1320. ->getMock();
  1321. $thing->expects($this->once())->method('isCool')
  1322. ->willReturnCallback(function ($data, $a, $b, $context) use ($thing) {
  1323. $this->assertSame('bar', $data);
  1324. $this->assertSame('and', $a);
  1325. $this->assertSame('awesome', $b);
  1326. $expected = [
  1327. 'default' => new RulesProvider(),
  1328. 'thing' => $thing,
  1329. ];
  1330. $expected = [
  1331. 'newRecord' => true,
  1332. 'providers' => $expected,
  1333. 'data' => [
  1334. 'email' => '!',
  1335. 'title' => 'bar',
  1336. ],
  1337. 'field' => 'title',
  1338. ];
  1339. $this->assertEquals($expected, $context);
  1340. return "That ain't cool, yo";
  1341. });
  1342. $validator->setProvider('thing', $thing);
  1343. $errors = $validator->validate(['email' => '!', 'title' => 'bar']);
  1344. $expected = [
  1345. 'title' => ['cool' => "That ain't cool, yo"],
  1346. ];
  1347. $this->assertEquals($expected, $errors);
  1348. }
  1349. /**
  1350. * Tests that it is possible to use a closure as a rule
  1351. */
  1352. public function testUsingClosureAsRule(): void
  1353. {
  1354. $validator = new Validator();
  1355. $validator->add('name', 'myRule', [
  1356. 'rule' => function ($data, $provider) {
  1357. $this->assertSame('foo', $data);
  1358. return 'You fail';
  1359. },
  1360. ]);
  1361. $expected = ['name' => ['myRule' => 'You fail']];
  1362. $this->assertEquals($expected, $validator->validate(['name' => 'foo']));
  1363. }
  1364. /**
  1365. * Tests that setting last globally will stop validating the rest of the rules
  1366. */
  1367. public function testErrorsWithLastRuleGlobal(): void
  1368. {
  1369. $validator = new Validator();
  1370. $validator->setStopOnFailure()
  1371. ->notBlank('email', 'Fill something in!')
  1372. ->email('email', false, 'Y u no write email?');
  1373. $errors = $validator->validate(['email' => '']);
  1374. $expected = [
  1375. 'email' => [
  1376. 'notBlank' => 'Fill something in!',
  1377. ],
  1378. ];
  1379. $this->assertEquals($expected, $errors);
  1380. }
  1381. /**
  1382. * Tests that setting last to a rule will stop validating the rest of the rules
  1383. */
  1384. public function testErrorsWithLastRule(): void
  1385. {
  1386. $validator = new Validator();
  1387. $validator
  1388. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  1389. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1390. $errors = $validator->validate(['email' => 'not an email!']);
  1391. $expected = [
  1392. 'email' => [
  1393. 'alpha' => 'The provided value is invalid',
  1394. ],
  1395. ];
  1396. $this->assertEquals($expected, $errors);
  1397. }
  1398. /**
  1399. * Tests it is possible to get validation sets for a field using an array interface
  1400. */
  1401. public function testArrayAccessGet(): void
  1402. {
  1403. $validator = new Validator();
  1404. $validator
  1405. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1406. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1407. $this->assertSame($validator['email'], $validator->field('email'));
  1408. $this->assertSame($validator['title'], $validator->field('title'));
  1409. }
  1410. /**
  1411. * Tests direct usage the offsetGet method with an integer field name
  1412. */
  1413. public function testOffsetGetWithIntegerFieldName(): void
  1414. {
  1415. $validator = new Validator();
  1416. $validator
  1417. ->add('0', 'alpha', ['rule' => 'alphanumeric']);
  1418. $this->assertSame($validator->offsetGet(0), $validator->field('0'));
  1419. }
  1420. /**
  1421. * Tests it is possible to check for validation sets for a field using an array interface
  1422. */
  1423. public function testArrayAccessExists(): void
  1424. {
  1425. $validator = new Validator();
  1426. $validator
  1427. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1428. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1429. $this->assertArrayHasKey('email', $validator);
  1430. $this->assertArrayHasKey('title', $validator);
  1431. $this->assertArrayNotHasKey('foo', $validator);
  1432. }
  1433. /**
  1434. * Tests it is possible to set validation rules for a field using an array interface
  1435. */
  1436. public function testArrayAccessSet(): void
  1437. {
  1438. $validator = new Validator();
  1439. $validator
  1440. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1441. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1442. $validator['name'] = $validator->field('title');
  1443. $this->assertSame($validator->field('title'), $validator->field('name'));
  1444. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  1445. $this->assertEquals($validator->field('email'), $validator->field('email'));
  1446. }
  1447. /**
  1448. * Tests it is possible to unset validation rules
  1449. */
  1450. public function testArrayAccessUnset(): void
  1451. {
  1452. $validator = new Validator();
  1453. $validator
  1454. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1455. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1456. $this->assertArrayHasKey('title', $validator);
  1457. unset($validator['title']);
  1458. $this->assertArrayNotHasKey('title', $validator);
  1459. }
  1460. /**
  1461. * Tests the countable interface
  1462. */
  1463. public function testCount(): void
  1464. {
  1465. $validator = new Validator();
  1466. $validator
  1467. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1468. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1469. $this->assertCount(2, $validator);
  1470. }
  1471. /**
  1472. * Tests adding rules via alternative syntax
  1473. */
  1474. public function testAddMultiple(): void
  1475. {
  1476. $validator = new Validator();
  1477. $validator->add('title', [
  1478. 'notBlank' => [
  1479. 'rule' => 'notBlank',
  1480. ],
  1481. 'length' => [
  1482. 'rule' => ['minLength', 10],
  1483. 'message' => 'Titles need to be at least 10 characters long',
  1484. ],
  1485. ]);
  1486. $set = $validator->field('title');
  1487. $this->assertInstanceOf(ValidationSet::class, $set);
  1488. $this->assertCount(2, $set);
  1489. }
  1490. /**
  1491. * Tests adding rules via alternative syntax and numeric keys
  1492. */
  1493. public function testAddMultipleNumericKeyArraysInvalid(): void
  1494. {
  1495. $this->expectException(InvalidArgumentException::class);
  1496. $this->expectExceptionMessage('You cannot add validation rules without a `name` key. Update rules array to have string keys.');
  1497. $validator = new Validator();
  1498. $validator->add('title', [
  1499. [
  1500. 'rule' => 'notBlank',
  1501. ],
  1502. [
  1503. 'rule' => ['minLength', 10],
  1504. 'message' => 'Titles need to be at least 10 characters long',
  1505. ],
  1506. ]);
  1507. }
  1508. /**
  1509. * Integration test for compareWith validator.
  1510. */
  1511. public function testCompareWithIntegration(): void
  1512. {
  1513. $validator = new Validator();
  1514. $validator->add('password', [
  1515. 'compare' => [
  1516. 'rule' => ['compareWith', 'password_compare'],
  1517. ],
  1518. ]);
  1519. $data = [
  1520. 'password' => 'test',
  1521. 'password_compare' => 'not the same',
  1522. ];
  1523. $this->assertNotEmpty($validator->validate($data), 'Validation should fail.');
  1524. }
  1525. /**
  1526. * Test debugInfo helper method.
  1527. */
  1528. public function testDebugInfo(): void
  1529. {
  1530. $validator = new Validator();
  1531. $validator->setProvider('test', $this);
  1532. $validator->add('title', 'not-empty', ['rule' => 'notBlank']);
  1533. $validator->requirePresence('body');
  1534. $validator->allowEmptyString('published');
  1535. $result = $validator->__debugInfo();
  1536. $expected = [
  1537. '_providers' => ['test'],
  1538. '_fields' => [
  1539. 'title' => [
  1540. 'isPresenceRequired' => false,
  1541. 'isEmptyAllowed' => false,
  1542. 'rules' => ['not-empty'],
  1543. ],
  1544. 'body' => [
  1545. 'isPresenceRequired' => true,
  1546. 'isEmptyAllowed' => false,
  1547. 'rules' => [],
  1548. ],
  1549. 'published' => [
  1550. 'isPresenceRequired' => false,
  1551. 'isEmptyAllowed' => true,
  1552. 'rules' => [],
  1553. ],
  1554. ],
  1555. '_presenceMessages' => [],
  1556. '_allowEmptyMessages' => [],
  1557. '_allowEmptyFlags' => [
  1558. 'published' => Validator::EMPTY_STRING,
  1559. ],
  1560. '_useI18n' => true,
  1561. '_stopOnFailure' => false,
  1562. ];
  1563. $this->assertEquals($expected, $result);
  1564. }
  1565. /**
  1566. * Tests that the 'create' and 'update' modes are preserved when using
  1567. * nested validators
  1568. */
  1569. public function testNestedValidatorCreate(): void
  1570. {
  1571. $validator = new Validator();
  1572. $inner = new Validator();
  1573. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1574. $validator->addNested('user', $inner);
  1575. $this->assertNotEmpty($validator->validate(['user' => ['username' => 'example']], true));
  1576. $this->assertEmpty($validator->validate(['user' => ['username' => 'a']], false));
  1577. }
  1578. /**
  1579. * Tests that the 'create' and 'update' modes are preserved when using
  1580. * nested validators
  1581. */
  1582. public function testNestedManyValidatorCreate(): void
  1583. {
  1584. $validator = new Validator();
  1585. $inner = new Validator();
  1586. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1587. $validator->addNestedMany('user', $inner);
  1588. $this->assertNotEmpty($validator->validate(['user' => [['username' => 'example']]], true));
  1589. $this->assertEmpty($validator->validate(['user' => [['username' => 'a']]], false));
  1590. }
  1591. /**
  1592. * Tests the notBlank proxy method
  1593. */
  1594. public function testNotBlank(): void
  1595. {
  1596. $validator = new Validator();
  1597. $this->assertProxyMethod($validator, 'notBlank');
  1598. $this->assertNotEmpty($validator->validate(['username' => ' ']));
  1599. }
  1600. /**
  1601. * Tests the alphanumeric proxy method
  1602. */
  1603. public function testAlphanumeric(): void
  1604. {
  1605. $validator = new Validator();
  1606. $this->assertProxyMethod($validator, 'alphaNumeric');
  1607. $this->assertNotEmpty($validator->validate(['username' => '$']));
  1608. }
  1609. /**
  1610. * Tests the notalphanumeric proxy method
  1611. */
  1612. public function testNotAlphanumeric(): void
  1613. {
  1614. $validator = new Validator();
  1615. $this->assertProxyMethod($validator, 'notAlphaNumeric');
  1616. $this->assertEmpty($validator->validate(['username' => '$']));
  1617. }
  1618. /**
  1619. * Tests the asciialphanumeric proxy method
  1620. */
  1621. public function testAsciiAlphanumeric(): void
  1622. {
  1623. $validator = new Validator();
  1624. $this->assertProxyMethod($validator, 'asciiAlphaNumeric');
  1625. $this->assertNotEmpty($validator->validate(['username' => '$']));
  1626. }
  1627. /**
  1628. * Tests the notalphanumeric proxy method
  1629. */
  1630. public function testNotAsciiAlphanumeric(): void
  1631. {
  1632. $validator = new Validator();
  1633. $this->assertProxyMethod($validator, 'notAsciiAlphaNumeric');
  1634. $this->assertEmpty($validator->validate(['username' => '$']));
  1635. }
  1636. /**
  1637. * Tests the lengthBetween proxy method
  1638. */
  1639. public function testLengthBetween(): void
  1640. {
  1641. $validator = new Validator();
  1642. $this->assertProxyMethod($validator, 'lengthBetween', [5, 7], [5, 7]);
  1643. $this->assertNotEmpty($validator->validate(['username' => 'foo']));
  1644. }
  1645. /**
  1646. * Tests the lengthBetween proxy method
  1647. */
  1648. public function testLengthBetweenFailure(): void
  1649. {
  1650. $this->expectException(InvalidArgumentException::class);
  1651. $validator = new Validator();
  1652. $validator->lengthBetween('username', [7]);
  1653. }
  1654. /**
  1655. * Tests the creditCard proxy method
  1656. */
  1657. public function testCreditCard(): void
  1658. {
  1659. $validator = new Validator();
  1660. $this->assertProxyMethod($validator, 'creditCard', 'all', ['all', true], 'creditCard');
  1661. $this->assertNotEmpty($validator->validate(['username' => 'foo']));
  1662. }
  1663. /**
  1664. * Tests the greaterThan proxy method
  1665. */
  1666. public function testGreaterThan(): void
  1667. {
  1668. $validator = new Validator();
  1669. $this->assertProxyMethod($validator, 'greaterThan', 5, [Validation::COMPARE_GREATER, 5], 'comparison');
  1670. $this->assertNotEmpty($validator->validate(['username' => 2]));
  1671. }
  1672. /**
  1673. * Tests the greaterThanOrEqual proxy method
  1674. */
  1675. public function testGreaterThanOrEqual(): void
  1676. {
  1677. $validator = new Validator();
  1678. $this->assertProxyMethod($validator, 'greaterThanOrEqual', 5, [Validation::COMPARE_GREATER_OR_EQUAL, 5], 'comparison');
  1679. $this->assertNotEmpty($validator->validate(['username' => 2]));
  1680. }
  1681. /**
  1682. * Tests the lessThan proxy method
  1683. */
  1684. public function testLessThan(): void
  1685. {
  1686. $validator = new Validator();
  1687. $this->assertProxyMethod($validator, 'lessThan', 5, [Validation::COMPARE_LESS, 5], 'comparison');
  1688. $this->assertNotEmpty($validator->validate(['username' => 5]));
  1689. }
  1690. /**
  1691. * Tests the lessThanOrEqual proxy method
  1692. */
  1693. public function testLessThanOrEqual(): void
  1694. {
  1695. $validator = new Validator();
  1696. $this->assertProxyMethod($validator, 'lessThanOrEqual', 5, [Validation::COMPARE_LESS_OR_EQUAL, 5], 'comparison');
  1697. $this->assertNotEmpty($validator->validate(['username' => 6]));
  1698. }
  1699. /**
  1700. * Tests the equals proxy method
  1701. */
  1702. public function testEquals(): void
  1703. {
  1704. $validator = new Validator();
  1705. $this->assertProxyMethod($validator, 'equals', 5, [Validation::COMPARE_EQUAL, 5], 'comparison');
  1706. $this->assertEmpty($validator->validate(['username' => 5]));
  1707. $this->assertNotEmpty($validator->validate(['username' => 6]));
  1708. }
  1709. /**
  1710. * Tests the notEquals proxy method
  1711. */
  1712. public function testNotEquals(): void
  1713. {
  1714. $validator = new Validator();
  1715. $this->assertProxyMethod($validator, 'notEquals', 5, [Validation::COMPARE_NOT_EQUAL, 5], 'comparison');
  1716. $this->assertNotEmpty($validator->validate(['username' => 5]));
  1717. }
  1718. /**
  1719. * Tests the sameAs proxy method
  1720. */
  1721. public function testSameAs(): void
  1722. {
  1723. $validator = new Validator();
  1724. $this->assertProxyMethod($validator, 'sameAs', 'other', ['other', Validation::COMPARE_SAME], 'compareFields');
  1725. $this->assertNotEmpty($validator->validate(['username' => 'foo']));
  1726. $this->assertNotEmpty($validator->validate(['username' => 1, 'other' => '1']));
  1727. }
  1728. /**
  1729. * Tests the notSameAs proxy method
  1730. */
  1731. public function testNotSameAs(): void
  1732. {
  1733. $validator = new Validator();
  1734. $this->assertProxyMethod($validator, 'notSameAs', 'other', ['other', Validation::COMPARE_NOT_SAME], 'compareFields');
  1735. $this->assertNotEmpty($validator->validate(['username' => 'foo', 'other' => 'foo']));
  1736. }
  1737. /**
  1738. * Tests the equalToField proxy method
  1739. */
  1740. public function testEqualToField(): void
  1741. {
  1742. $validator = new Validator();
  1743. $this->assertProxyMethod($validator, 'equalToField', 'other', ['other', Validation::COMPARE_EQUAL], 'compareFields');
  1744. $this->assertNotEmpty($validator->validate(['username' => 'foo']));
  1745. $this->assertNotEmpty($validator->validate(['username' => 'foo', 'other' => 'bar']));
  1746. }
  1747. /**
  1748. * Tests the notEqualToField proxy method
  1749. */
  1750. public function testNotEqualToField(): void
  1751. {
  1752. $validator = new Validator();
  1753. $this->assertProxyMethod($validator, 'notEqualToField', 'other', ['other', Validation::COMPARE_NOT_EQUAL], 'compareFields');
  1754. $this->assertNotEmpty($validator->validate(['username' => 'foo', 'other' => 'foo']));
  1755. }
  1756. /**
  1757. * Tests the greaterThanField proxy method
  1758. */
  1759. public function testGreaterThanField(): void
  1760. {
  1761. $validator = new Validator();
  1762. $this->assertProxyMethod($validator, 'greaterThanField', 'other', ['other', Validation::COMPARE_GREATER], 'compareFields');
  1763. $this->assertNotEmpty($validator->validate(['username' => 1, 'other' => 1]));
  1764. $this->assertNotEmpty($validator->validate(['username' => 1, 'other' => 2]));
  1765. }
  1766. /**
  1767. * Tests the greaterThanOrEqualToField proxy method
  1768. */
  1769. public function testGreaterThanOrEqualToField(): void
  1770. {
  1771. $validator = new Validator();
  1772. $this->assertProxyMethod($validator, 'greaterThanOrEqualToField', 'other', ['other', Validation::COMPARE_GREATER_OR_EQUAL], 'compareFields');
  1773. $this->assertNotEmpty($validator->validate(['username' => 1, 'other' => 2]));
  1774. }
  1775. /**
  1776. * Tests the lessThanField proxy method
  1777. */
  1778. public function testLessThanField(): void
  1779. {
  1780. $validator = new Validator();
  1781. $this->assertProxyMethod($validator, 'lessThanField', 'other', ['other', Validation::COMPARE_LESS], 'compareFields');
  1782. $this->assertNotEmpty($validator->validate(['username' => 1, 'other' => 1]));
  1783. $this->assertNotEmpty($validator->validate(['username' => 2, 'other' => 1]));
  1784. }
  1785. /**
  1786. * Tests the lessThanOrEqualToField proxy method
  1787. */
  1788. public function testLessThanOrEqualToField(): void
  1789. {
  1790. $validator = new Validator();
  1791. $this->assertProxyMethod($validator, 'lessThanOrEqualToField', 'other', ['other', Validation::COMPARE_LESS_OR_EQUAL], 'compareFields');
  1792. $this->assertNotEmpty($validator->validate(['username' => 2, 'other' => 1]));
  1793. }
  1794. /**
  1795. * Tests the date proxy method
  1796. */
  1797. public function testDate(): void
  1798. {
  1799. $validator = new Validator();
  1800. $this->assertProxyMethod($validator, 'date', ['ymd'], [['ymd']]);
  1801. $this->assertNotEmpty($validator->validate(['username' => 'not a date']));
  1802. }
  1803. /**
  1804. * Tests the dateTime proxy method
  1805. */
  1806. public function testDateTime(): void
  1807. {
  1808. $validator = new Validator();
  1809. $this->assertProxyMethod($validator, 'dateTime', ['ymd'], [['ymd']], 'datetime');
  1810. $this->assertNotEmpty($validator->validate(['username' => 'not a date']));
  1811. $validator = (new Validator())->dateTime('thedate', ['iso8601']);
  1812. $this->assertEmpty($validator->validate(['thedate' => '2020-05-01T12:34:56Z']));
  1813. }
  1814. /**
  1815. * Tests the time proxy method
  1816. */
  1817. public function testTime(): void
  1818. {
  1819. $validator = new Validator();
  1820. $this->assertProxyMethod($validator, 'time');
  1821. $this->assertNotEmpty($validator->validate(['username' => 'not a time']));
  1822. }
  1823. /**
  1824. * Tests the localizedTime proxy method
  1825. */
  1826. public function testLocalizedTime(): void
  1827. {
  1828. $validator = new Validator();
  1829. $this->assertProxyMethod($validator, 'localizedTime', 'date', ['date']);
  1830. $this->assertNotEmpty($validator->validate(['username' => 'not a date']));
  1831. }
  1832. /**
  1833. * Tests the boolean proxy method
  1834. */
  1835. public function testBoolean(): void
  1836. {
  1837. $validator = new Validator();
  1838. $this->assertProxyMethod($validator, 'boolean');
  1839. $this->assertNotEmpty($validator->validate(['username' => 'not a boolean']));
  1840. }
  1841. /**
  1842. * Tests the decimal proxy method
  1843. */
  1844. public function testDecimal(): void
  1845. {
  1846. $validator = new Validator();
  1847. $this->assertProxyMethod($validator, 'decimal', 2, [2]);
  1848. $this->assertNotEmpty($validator->validate(['username' => 10.1]));
  1849. }
  1850. /**
  1851. * Tests the IP proxy methods
  1852. */
  1853. public function testIps(): void
  1854. {
  1855. $validator = new Validator();
  1856. $this->assertProxyMethod($validator, 'ip');
  1857. $this->assertNotEmpty($validator->validate(['username' => 'not ip']));
  1858. $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip');
  1859. $this->assertNotEmpty($validator->validate(['username' => 'not ip']));
  1860. $this->assertProxyMethod($validator, 'ipv6', null, ['ipv6'], 'ip');
  1861. $this->assertNotEmpty($validator->validate(['username' => 'not ip']));
  1862. }
  1863. /**
  1864. * Tests the minLength proxy method
  1865. */
  1866. public function testMinLength(): void
  1867. {
  1868. $validator = new Validator();
  1869. $this->assertProxyMethod($validator, 'minLength', 2, [2]);
  1870. $this->assertNotEmpty($validator->validate(['username' => 'a']));
  1871. }
  1872. /**
  1873. * Tests the minLengthBytes proxy method
  1874. */
  1875. public function testMinLengthBytes(): void
  1876. {
  1877. $validator = new Validator();
  1878. $this->assertProxyMethod($validator, 'minLengthBytes', 11, [11]);
  1879. $this->assertNotEmpty($validator->validate(['username' => 'ÆΔΩЖÇ']));
  1880. }
  1881. /**
  1882. * Tests the maxLength proxy method
  1883. */
  1884. public function testMaxLength(): void
  1885. {
  1886. $validator = new Validator();
  1887. $this->assertProxyMethod($validator, 'maxLength', 2, [2]);
  1888. $this->assertNotEmpty($validator->validate(['username' => 'aaa']));
  1889. }
  1890. /**
  1891. * Tests the maxLengthBytes proxy method
  1892. */
  1893. public function testMaxLengthBytes(): void
  1894. {
  1895. $validator = new Validator();
  1896. $this->assertProxyMethod($validator, 'maxLengthBytes', 9, [9]);
  1897. $this->assertNotEmpty($validator->validate(['username' => 'ÆΔΩЖÇ']));
  1898. }
  1899. /**
  1900. * Tests the numeric proxy method
  1901. */
  1902. public function testNumeric(): void
  1903. {
  1904. $validator = new Validator();
  1905. $this->assertProxyMethod($validator, 'numeric');
  1906. $this->assertEmpty($validator->validate(['username' => '22']));
  1907. $this->assertNotEmpty($validator->validate(['username' => 'a']));
  1908. }
  1909. /**
  1910. * Tests the naturalNumber proxy method
  1911. */
  1912. public function testNaturalNumber(): void
  1913. {
  1914. $validator = new Validator();
  1915. $this->assertProxyMethod($validator, 'naturalNumber', null, [false]);
  1916. $this->assertNotEmpty($validator->validate(['username' => 0]));
  1917. }
  1918. /**
  1919. * Tests the nonNegativeInteger proxy method
  1920. */
  1921. public function testNonNegativeInteger(): void
  1922. {
  1923. $validator = new Validator();
  1924. $this->assertProxyMethod($validator, 'nonNegativeInteger', null, [true], 'naturalNumber');
  1925. $this->assertNotEmpty($validator->validate(['username' => -1]));
  1926. }
  1927. /**
  1928. * Tests the range proxy method
  1929. */
  1930. public function testRange(): void
  1931. {
  1932. $validator = new Validator();
  1933. $this->assertProxyMethod($validator, 'range', [1, 4], [1, 4]);
  1934. $this->assertNotEmpty($validator->validate(['username' => 5]));
  1935. }
  1936. /**
  1937. * Tests the range failure case
  1938. */
  1939. public function testRangeFailure(): void
  1940. {
  1941. $this->expectException(InvalidArgumentException::class);
  1942. $validator = new Validator();
  1943. $validator->range('username', [1]);
  1944. }
  1945. /**
  1946. * Tests the url proxy method
  1947. */
  1948. public function testUrl(): void
  1949. {
  1950. $validator = new Validator();
  1951. $this->assertProxyMethod($validator, 'url', null, [false]);
  1952. $this->assertNotEmpty($validator->validate(['username' => 'not url']));
  1953. }
  1954. /**
  1955. * Tests the urlWithProtocol proxy method
  1956. */
  1957. public function testUrlWithProtocol(): void
  1958. {
  1959. $validator = new Validator();
  1960. $this->assertProxyMethod($validator, 'urlWithProtocol', null, [true], 'url');
  1961. $this->assertNotEmpty($validator->validate(['username' => 'google.com']));
  1962. }
  1963. /**
  1964. * Tests the inList proxy method
  1965. */
  1966. public function testInList(): void
  1967. {
  1968. $validator = new Validator();
  1969. $this->assertProxyMethod($validator, 'inList', ['a', 'b'], [['a', 'b']]);
  1970. $this->assertNotEmpty($validator->validate(['username' => 'c']));
  1971. }
  1972. /**
  1973. * Tests the uuid proxy method
  1974. */
  1975. public function testUuid(): void
  1976. {
  1977. $validator = new Validator();
  1978. $this->assertProxyMethod($validator, 'uuid');
  1979. $this->assertNotEmpty($validator->validate(['username' => 'not uuid']));
  1980. }
  1981. /**
  1982. * Tests the uploadedFile proxy method
  1983. */
  1984. public function testUploadedFile(): void
  1985. {
  1986. $validator = new Validator();
  1987. $this->assertProxyMethod($validator, 'uploadedFile', ['foo' => 'bar'], [['foo' => 'bar']]);
  1988. $this->assertNotEmpty($validator->validate(['username' => []]));
  1989. }
  1990. /**
  1991. * Tests the latlog proxy methods
  1992. */
  1993. public function testLatLong(): void
  1994. {
  1995. $validator = new Validator();
  1996. $this->assertProxyMethod($validator, 'latLong', null, [], 'geoCoordinate');
  1997. $this->assertNotEmpty($validator->validate(['username' => 2000]));
  1998. $this->assertProxyMethod($validator, 'latitude');
  1999. $this->assertNotEmpty($validator->validate(['username' => 2000]));
  2000. $this->assertProxyMethod($validator, 'longitude');
  2001. $this->assertNotEmpty($validator->validate(['username' => 2000]));
  2002. }
  2003. /**
  2004. * Tests the ascii proxy method
  2005. */
  2006. public function testAscii(): void
  2007. {
  2008. $validator = new Validator();
  2009. $this->assertProxyMethod($validator, 'ascii');
  2010. $this->assertNotEmpty($validator->validate(['username' => 'ü']));
  2011. }
  2012. /**
  2013. * Tests the utf8 proxy methods
  2014. */
  2015. public function testUtf8(): void
  2016. {
  2017. // Grinning face
  2018. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2019. $validator = new Validator();
  2020. $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]);
  2021. $this->assertEmpty($validator->validate(['username' => 'ü']));
  2022. $this->assertNotEmpty($validator->validate(['username' => $extended]));
  2023. }
  2024. /**
  2025. * Test utf8extended proxy method.
  2026. */
  2027. public function testUtf8Extended(): void
  2028. {
  2029. // Grinning face
  2030. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2031. $validator = new Validator();
  2032. $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8');
  2033. $this->assertEmpty($validator->validate(['username' => 'ü']));
  2034. $this->assertEmpty($validator->validate(['username' => $extended]));
  2035. }
  2036. /**
  2037. * Tests the email proxy method
  2038. */
  2039. public function testEmail(): void
  2040. {
  2041. $validator = new Validator();
  2042. $validator->email('username');
  2043. $this->assertEmpty($validator->validate(['username' => 'test@example.com']));
  2044. $this->assertNotEmpty($validator->validate(['username' => 'not an email']));
  2045. }
  2046. /**
  2047. * Tests the integer proxy method
  2048. */
  2049. public function testInteger(): void
  2050. {
  2051. $validator = new Validator();
  2052. $this->assertProxyMethod($validator, 'integer', null, [], 'isInteger');
  2053. $this->assertNotEmpty($validator->validate(['username' => 'not integer']));
  2054. }
  2055. /**
  2056. * Tests the array proxy method
  2057. */
  2058. public function testArray(): void
  2059. {
  2060. $validator = new Validator();
  2061. $validator->array('username');
  2062. $this->assertEmpty($validator->validate(['username' => [1, 2, 3]]));
  2063. $this->assertSame(
  2064. ['username' => ['array' => 'The provided value must be an array']],
  2065. $validator->validate(['username' => 'is not an array'])
  2066. );
  2067. }
  2068. /**
  2069. * Tests the scalar proxy method
  2070. */
  2071. public function testScalar(): void
  2072. {
  2073. $validator = new Validator();
  2074. $validator->scalar('username');
  2075. $this->assertEmpty($validator->validate(['username' => 'scalar']));
  2076. $this->assertSame(
  2077. ['username' => ['scalar' => 'The provided value must be scalar']],
  2078. $validator->validate(['username' => ['array']])
  2079. );
  2080. }
  2081. /**
  2082. * Tests the hexColor proxy method
  2083. */
  2084. public function testHexColor(): void
  2085. {
  2086. $validator = new Validator();
  2087. $this->assertProxyMethod($validator, 'hexColor');
  2088. $this->assertEmpty($validator->validate(['username' => '#FFFFFF']));
  2089. $this->assertNotEmpty($validator->validate(['username' => 'FFFFFF']));
  2090. }
  2091. /**
  2092. * Tests the multiple proxy method
  2093. */
  2094. public function testMultiple(): void
  2095. {
  2096. $validator = new Validator();
  2097. $this->assertProxyMethod(
  2098. $validator,
  2099. 'multipleOptions',
  2100. ['min' => 1, 'caseInsensitive' => true],
  2101. [['min' => 1], true],
  2102. 'multiple'
  2103. );
  2104. $this->assertProxyMethod(
  2105. $validator,
  2106. 'multipleOptions',
  2107. ['min' => 1, 'caseInsensitive' => false],
  2108. [['min' => 1], false],
  2109. 'multiple'
  2110. );
  2111. $this->assertNotEmpty($validator->validate(['username' => '']));
  2112. }
  2113. /**
  2114. * Tests the hasAtLeast method
  2115. */
  2116. public function testHasAtLeast(): void
  2117. {
  2118. $validator = new Validator();
  2119. $validator->hasAtLeast('things', 3);
  2120. $this->assertEmpty($validator->validate(['things' => [1, 2, 3]]));
  2121. $this->assertEmpty($validator->validate(['things' => [1, 2, 3, 4]]));
  2122. $this->assertNotEmpty($validator->validate(['things' => [1, 2]]));
  2123. $this->assertNotEmpty($validator->validate(['things' => []]));
  2124. $this->assertNotEmpty($validator->validate(['things' => 'string']));
  2125. $this->assertEmpty($validator->validate(['things' => ['_ids' => [1, 2, 3]]]));
  2126. $this->assertEmpty($validator->validate(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2127. $this->assertNotEmpty($validator->validate(['things' => ['_ids' => [1, 2]]]));
  2128. $this->assertNotEmpty($validator->validate(['things' => ['_ids' => []]]));
  2129. $this->assertNotEmpty($validator->validate(['things' => ['_ids' => 'string']]));
  2130. }
  2131. /**
  2132. * Tests the hasAtMost method
  2133. */
  2134. public function testHasAtMost(): void
  2135. {
  2136. $validator = new Validator();
  2137. $validator->hasAtMost('things', 3);
  2138. $this->assertEmpty($validator->validate(['things' => [1, 2, 3]]));
  2139. $this->assertEmpty($validator->validate(['things' => [1]]));
  2140. $this->assertNotEmpty($validator->validate(['things' => [1, 2, 3, 4]]));
  2141. $this->assertEmpty($validator->validate(['things' => ['_ids' => [1, 2, 3]]]));
  2142. $this->assertEmpty($validator->validate(['things' => ['_ids' => [1, 2]]]));
  2143. $this->assertNotEmpty($validator->validate(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2144. }
  2145. /**
  2146. * Tests the regex proxy method
  2147. */
  2148. public function testRegex(): void
  2149. {
  2150. $validator = new Validator();
  2151. $this->assertProxyMethod($validator, 'regex', '/(?<!\\S)\\d++(?!\\S)/', ['/(?<!\\S)\\d++(?!\\S)/'], 'custom');
  2152. $this->assertEmpty($validator->validate(['username' => '123']));
  2153. $this->assertNotEmpty($validator->validate(['username' => 'Foo']));
  2154. }
  2155. /**
  2156. * Tests the validate method with an integer key
  2157. */
  2158. public function testValidateWithIntegerKey(): void
  2159. {
  2160. $validator = new Validator();
  2161. $validator->requirePresence('0');
  2162. $errors = $validator->validate([1 => 'Not integer zero']);
  2163. $expected = ['0' => ['_required' => 'This field is required']];
  2164. $this->assertEquals($expected, $errors);
  2165. }
  2166. /**
  2167. * Tests that a rule in the Validator class exists and was configured as expected.
  2168. *
  2169. * @param Validator $validator
  2170. * @param string $method
  2171. * @param mixed $extra
  2172. * @param array $pass
  2173. * @param string|null $name
  2174. */
  2175. protected function assertProxyMethod($validator, $method, $extra = null, $pass = [], $name = null): void
  2176. {
  2177. $name = $name ?: $method;
  2178. if ($extra !== null) {
  2179. $this->assertSame($validator, $validator->{$method}('username', $extra));
  2180. } else {
  2181. $this->assertSame($validator, $validator->{$method}('username'));
  2182. }
  2183. $rule = $validator->field('username')->rule($method);
  2184. $this->assertNotEmpty($rule, "Rule was not found for $method");
  2185. $this->assertNotNull($rule->get('message'), 'Message is not present when it should be');
  2186. $this->assertNull($rule->get('on'), 'On clause is present when it should not be');
  2187. $this->assertSame($name, $rule->get('rule'), 'Rule name does not match');
  2188. $this->assertEquals($pass, $rule->get('pass'), 'Passed options are different');
  2189. $this->assertSame('default', $rule->get('provider'), 'Provider does not match');
  2190. if ($extra !== null) {
  2191. $validator->{$method}('username', $extra, 'the message', 'create');
  2192. } else {
  2193. $validator->{$method}('username', 'the message', 'create');
  2194. }
  2195. $rule = $validator->field('username')->rule($method);
  2196. $this->assertSame('the message', $rule->get('message'), 'Error messages are not the same');
  2197. $this->assertSame('create', $rule->get('on'), 'On clause is wrong');
  2198. }
  2199. /**
  2200. * Testing adding DefaultProvider
  2201. */
  2202. public function testAddingDefaultProvider(): void
  2203. {
  2204. $validator = new Validator();
  2205. $this->assertEmpty($validator->providers(), 'Providers should be empty');
  2206. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2207. $validator = new Validator();
  2208. $this->assertEquals($validator->providers(), ['test-provider'], 'Default provider `test-provider` is missing');
  2209. }
  2210. /**
  2211. * Testing getting DefaultProvider(s)
  2212. */
  2213. public function testGetDefaultProvider(): void
  2214. {
  2215. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2216. $this->assertEquals(Validator::getDefaultProvider('test-provider'), 'MyNameSpace\Validation\MyProvider', 'Default provider `test-provider` is missing');
  2217. $this->assertNull(Validator::getDefaultProvider('invalid-provider'), 'Default provider (`invalid-provider`) should be missing');
  2218. Validator::addDefaultProvider('test-provider2', 'MyNameSpace\Validation\MySecondProvider');
  2219. $this->assertEquals(Validator::getDefaultProviders(), ['test-provider', 'test-provider2'], 'Default providers incorrect');
  2220. }
  2221. }