ValidatorTest.php 98 KB

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