ValidatorTest.php 84 KB

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