ValidatorTest.php 93 KB

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