ValidatorTest.php 96 KB

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