ValidatorTest.php 93 KB

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