ValidatorTest.php 100 KB

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