ValidatorTest.php 90 KB

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