ValidatorTest.php 105 KB

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