ValidatorTest.php 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136
  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. ->scalar('title');
  729. $data = [
  730. 'title' => '',
  731. 'otherField' => false,
  732. ];
  733. $this->assertNotEmpty($validator->errors($data));
  734. $data = [
  735. 'title' => '',
  736. 'otherField' => true,
  737. ];
  738. $this->assertEmpty($validator->errors($data));
  739. }
  740. /**
  741. * Same as testAllowEmptyDateUpdateDeprecatedArguments but without message
  742. *
  743. * @return void
  744. */
  745. public function testAllowEmptyStringDeprecatedArgumentsWithoutMessage()
  746. {
  747. $validator = new Validator();
  748. $this->deprecated(function () use ($validator) {
  749. $validator->allowEmptyString('title', 'update');
  750. });
  751. $this->assertFalse($validator->isEmptyAllowed('title', true));
  752. $this->assertTrue($validator->isEmptyAllowed('title', false));
  753. $data = [
  754. 'title' => null,
  755. ];
  756. $expected = [
  757. 'title' => ['_empty' => 'This field cannot be left empty'],
  758. ];
  759. $this->assertSame($expected, $validator->errors($data, true));
  760. $this->assertEmpty($validator->errors($data, false));
  761. }
  762. /**
  763. * Tests the notEmptyString method
  764. *
  765. * @return void
  766. */
  767. public function testNotEmptyString()
  768. {
  769. $validator = new Validator();
  770. $validator->notEmptyString('title', 'not empty');
  771. $this->assertFalse($validator->isEmptyAllowed('title', true));
  772. $this->assertFalse($validator->isEmptyAllowed('title', false));
  773. $data = ['title' => '0'];
  774. $this->assertEmpty($validator->errors($data));
  775. $data = ['title' => 0];
  776. $this->assertEmpty($validator->errors($data), 'empty ok on create');
  777. $this->assertEmpty($validator->errors($data, false), 'empty ok on update');
  778. $data = ['title' => []];
  779. $this->assertEmpty($validator->errors($data), 'empty array is no good');
  780. $expected = [
  781. 'title' => ['_empty' => 'not empty'],
  782. ];
  783. $data = ['title' => ''];
  784. $this->assertSame($expected, $validator->errors($data, true));
  785. }
  786. /**
  787. * Test notEmptyString with explicit create.
  788. *
  789. * @return void
  790. */
  791. public function testNotEmptyStringCreate()
  792. {
  793. $validator = new Validator();
  794. $validator->notEmptyString('title', 'message', 'create');
  795. $this->assertFalse($validator->isEmptyAllowed('title', true));
  796. $this->assertTrue($validator->isEmptyAllowed('title', false));
  797. $expected = [
  798. 'title' => ['_empty' => 'message'],
  799. ];
  800. $data = ['title' => null];
  801. $this->assertSame($expected, $validator->errors($data, true));
  802. $data = ['title' => ''];
  803. $this->assertSame($expected, $validator->errors($data, true));
  804. $data = ['title' => ''];
  805. $this->assertEmpty($validator->errors($data, false), 'empty allowed on update');
  806. }
  807. /**
  808. * Test notEmptyString with callback
  809. *
  810. * @return void
  811. */
  812. public function testNotEmptyStringCallbackWhen()
  813. {
  814. $validator = new Validator();
  815. $validator->notEmptyString('title', 'message', function ($context) {
  816. if (!isset($context['data']['emptyOk'])) {
  817. return true;
  818. }
  819. return $context['data']['emptyOk'];
  820. });
  821. $error = [
  822. 'title' => ['_empty' => 'message'],
  823. ];
  824. $data = ['title' => ''];
  825. $this->assertSame($error, $validator->errors($data));
  826. $data = ['title' => '', 'emptyOk' => false];
  827. $this->assertEmpty($validator->errors($data));
  828. $data = ['title' => '', 'emptyOk' => true];
  829. $this->assertSame($error, $validator->errors($data));
  830. }
  831. /**
  832. * Tests the allowEmptyArray method
  833. *
  834. * @return void
  835. */
  836. public function testAllowEmptyArray()
  837. {
  838. $validator = new Validator();
  839. $validator->allowEmptyArray('items')
  840. ->hasAtMost('items', 3);
  841. $this->assertTrue($validator->field('items')->isEmptyAllowed());
  842. $data = [
  843. 'items' => '',
  844. ];
  845. $result = $validator->errors($data);
  846. $this->assertEmpty($result);
  847. $data = [
  848. 'items' => null,
  849. ];
  850. $result = $validator->errors($data);
  851. $this->assertEmpty($result);
  852. $data = [
  853. 'items' => [],
  854. ];
  855. $result = $validator->errors($data);
  856. $this->assertEmpty($result);
  857. $data = [
  858. 'items' => [1, 2, 3, 4, 5],
  859. ];
  860. $expected = [
  861. 'items' => [
  862. 'hasAtMost' => 'The provided value is invalid',
  863. ],
  864. ];
  865. $result = $validator->errors($data);
  866. $this->assertSame($expected, $result);
  867. }
  868. /**
  869. * Test allowEmptyArray with update mode
  870. *
  871. * @return void
  872. */
  873. public function testAllowEmptyArrayUpdate()
  874. {
  875. $validator = new Validator();
  876. $validator->allowEmptyArray('items', 'message', 'update');
  877. $this->assertFalse($validator->isEmptyAllowed('items', true));
  878. $this->assertTrue($validator->isEmptyAllowed('items', false));
  879. $data = [
  880. 'items' => null,
  881. ];
  882. $expected = [
  883. 'items' => ['_empty' => 'message'],
  884. ];
  885. $this->assertSame($expected, $validator->errors($data, true));
  886. $this->assertEmpty($validator->errors($data, false));
  887. }
  888. /**
  889. * Test allowEmptyArray with update mode
  890. *
  891. * @return void
  892. */
  893. public function testAllowEmptyArrayUpdateDeprecatedOrder()
  894. {
  895. $validator = new Validator();
  896. $this->deprecated(function () use ($validator) {
  897. $validator->allowEmptyArray('items', 'update', 'message');
  898. });
  899. $this->assertFalse($validator->isEmptyAllowed('items', true));
  900. $this->assertTrue($validator->isEmptyAllowed('items', false));
  901. $data = [
  902. 'items' => null,
  903. ];
  904. $expected = [
  905. 'items' => ['_empty' => 'message'],
  906. ];
  907. $this->assertSame($expected, $validator->errors($data, true));
  908. $this->assertEmpty($validator->errors($data, false));
  909. }
  910. /**
  911. * Tests the notEmptyArray method
  912. *
  913. * @return void
  914. */
  915. public function testNotEmptyArray()
  916. {
  917. $validator = new Validator();
  918. $validator->notEmptyArray('items', 'not empty');
  919. $this->assertFalse($validator->field('items')->isEmptyAllowed());
  920. $error = [
  921. 'items' => ['_empty' => 'not empty'],
  922. ];
  923. $data = ['items' => ''];
  924. $result = $validator->errors($data);
  925. $this->assertSame($error, $result);
  926. $data = ['items' => null];
  927. $result = $validator->errors($data);
  928. $this->assertSame($error, $result);
  929. $data = ['items' => []];
  930. $result = $validator->errors($data);
  931. $this->assertSame($error, $result);
  932. $data = [
  933. 'items' => [1],
  934. ];
  935. $result = $validator->errors($data);
  936. $this->assertEmpty($result);
  937. }
  938. /**
  939. * Tests the allowEmptyFile method
  940. *
  941. * @return void
  942. */
  943. public function testAllowEmptyFile()
  944. {
  945. $validator = new Validator();
  946. $validator->allowEmptyFile('photo')
  947. ->uploadedFile('photo', []);
  948. $this->assertTrue($validator->field('photo')->isEmptyAllowed());
  949. $data = [
  950. 'photo' => [
  951. 'name' => '',
  952. 'type' => '',
  953. 'tmp_name' => '',
  954. 'error' => UPLOAD_ERR_NO_FILE,
  955. ],
  956. ];
  957. $result = $validator->errors($data);
  958. $this->assertEmpty($result);
  959. $data = [
  960. 'photo' => null,
  961. ];
  962. $result = $validator->errors($data);
  963. $this->assertEmpty($result);
  964. $data = [
  965. 'photo' => [
  966. 'name' => '',
  967. 'type' => '',
  968. 'tmp_name' => '',
  969. 'error' => UPLOAD_ERR_FORM_SIZE,
  970. ],
  971. ];
  972. $expected = [
  973. 'photo' => [
  974. 'uploadedFile' => 'The provided value is invalid',
  975. ],
  976. ];
  977. $result = $validator->errors($data);
  978. $this->assertSame($expected, $result);
  979. $data = [
  980. 'photo' => '',
  981. ];
  982. $expected = [
  983. 'photo' => [
  984. 'uploadedFile' => 'The provided value is invalid',
  985. ],
  986. ];
  987. $result = $validator->errors($data);
  988. $this->assertSame($expected, $result);
  989. $data = ['photo' => []];
  990. $result = $validator->errors($data);
  991. $this->assertSame($expected, $result);
  992. $validator = new Validator();
  993. $validator->allowEmptyFile('photo', 'message', 'update');
  994. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  995. $this->assertTrue($validator->isEmptyAllowed('photo', false));
  996. $data = [
  997. 'photo' => null,
  998. ];
  999. $expected = [
  1000. 'photo' => ['_empty' => 'message'],
  1001. ];
  1002. $this->assertSame($expected, $validator->errors($data, true));
  1003. $this->assertEmpty($validator->errors($data, false));
  1004. }
  1005. /**
  1006. * Test deprecated argument order for allowEmptyFile
  1007. *
  1008. * @return void
  1009. */
  1010. public function testAllowEmptyFileDeprecated()
  1011. {
  1012. $validator = new Validator();
  1013. $this->deprecated(function () use ($validator) {
  1014. $validator->allowEmptyFile('photo', 'update', 'message');
  1015. });
  1016. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  1017. $this->assertTrue($validator->isEmptyAllowed('photo', false));
  1018. $data = [
  1019. 'photo' => null,
  1020. ];
  1021. $expected = [
  1022. 'photo' => ['_empty' => 'message'],
  1023. ];
  1024. $this->assertSame($expected, $validator->errors($data, true));
  1025. $this->assertEmpty($validator->errors($data, false));
  1026. }
  1027. /**
  1028. * Tests the notEmptyFile method
  1029. *
  1030. * @return void
  1031. */
  1032. public function testNotEmptyFile()
  1033. {
  1034. $validator = new Validator();
  1035. $validator->notEmptyFile('photo', 'required field');
  1036. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  1037. $this->assertFalse($validator->isEmptyAllowed('photo', false));
  1038. $data = [
  1039. 'photo' => [
  1040. 'name' => '',
  1041. 'type' => '',
  1042. 'tmp_name' => '',
  1043. 'error' => UPLOAD_ERR_NO_FILE,
  1044. ],
  1045. ];
  1046. $error = ['photo' => ['_empty' => 'required field']];
  1047. $this->assertSame($error, $validator->errors($data));
  1048. $data = ['photo' => null];
  1049. $this->assertSame($error, $validator->errors($data));
  1050. // Empty string and empty array don't trigger errors
  1051. // as rejecting them here would mean accepting them in
  1052. // allowEmptyFile() which is not desirable.
  1053. $data = ['photo' => ''];
  1054. $this->assertEmpty($validator->errors($data));
  1055. $data = ['photo' => []];
  1056. $this->assertEmpty($validator->errors($data));
  1057. $data = [
  1058. 'photo' => [
  1059. 'name' => '',
  1060. 'type' => '',
  1061. 'tmp_name' => '',
  1062. 'error' => UPLOAD_ERR_FORM_SIZE,
  1063. ],
  1064. ];
  1065. $this->assertEmpty($validator->errors($data));
  1066. }
  1067. /**
  1068. * Test notEmptyFile with update mode.
  1069. *
  1070. * @retrn void
  1071. */
  1072. public function testNotEmptyFileUpdate()
  1073. {
  1074. $validator = new Validator();
  1075. $validator->notEmptyArray('photo', 'message', 'update');
  1076. $this->assertTrue($validator->isEmptyAllowed('photo', true));
  1077. $this->assertFalse($validator->isEmptyAllowed('photo', false));
  1078. $data = ['photo' => null];
  1079. $expected = [
  1080. 'photo' => ['_empty' => 'message'],
  1081. ];
  1082. $this->assertEmpty($validator->errors($data, true));
  1083. $this->assertSame($expected, $validator->errors($data, false));
  1084. }
  1085. /**
  1086. * Tests the allowEmptyDate method
  1087. *
  1088. * @return void
  1089. */
  1090. public function testAllowEmptyDate()
  1091. {
  1092. $validator = new Validator();
  1093. $validator->allowEmptyDate('date')
  1094. ->date('date');
  1095. $this->assertTrue($validator->field('date')->isEmptyAllowed());
  1096. $data = [
  1097. 'date' => [
  1098. 'year' => '',
  1099. 'month' => '',
  1100. 'day' => '',
  1101. ],
  1102. ];
  1103. $result = $validator->errors($data);
  1104. $this->assertEmpty($result);
  1105. $data = [
  1106. 'date' => '',
  1107. ];
  1108. $result = $validator->errors($data);
  1109. $this->assertEmpty($result);
  1110. $data = [
  1111. 'date' => null,
  1112. ];
  1113. $result = $validator->errors($data);
  1114. $this->assertEmpty($result);
  1115. $data = ['date' => []];
  1116. $result = $validator->errors($data);
  1117. $this->assertEmpty($result);
  1118. }
  1119. /**
  1120. * test allowEmptyDate() with an update condition
  1121. *
  1122. * @return void
  1123. */
  1124. public function testAllowEmptyDateUpdate()
  1125. {
  1126. $validator = new Validator();
  1127. $validator->allowEmptyArray('date', 'be valid', 'update');
  1128. $this->assertFalse($validator->isEmptyAllowed('date', true));
  1129. $this->assertTrue($validator->isEmptyAllowed('date', false));
  1130. $data = [
  1131. 'date' => null,
  1132. ];
  1133. $expected = [
  1134. 'date' => ['_empty' => 'be valid'],
  1135. ];
  1136. $this->assertSame($expected, $validator->errors($data, true));
  1137. $this->assertEmpty($validator->errors($data, false));
  1138. }
  1139. /**
  1140. * test allowEmptyDate() with an update condition
  1141. *
  1142. * @return void
  1143. */
  1144. public function testAllowEmptyDateUpdateDeprecatedArguments()
  1145. {
  1146. $validator = new Validator();
  1147. $this->deprecated(function () use ($validator) {
  1148. $validator->allowEmptyArray('date', 'update', 'be valid');
  1149. });
  1150. $this->assertFalse($validator->isEmptyAllowed('date', true));
  1151. $this->assertTrue($validator->isEmptyAllowed('date', false));
  1152. $data = [
  1153. 'date' => null,
  1154. ];
  1155. $expected = [
  1156. 'date' => ['_empty' => 'be valid'],
  1157. ];
  1158. $this->assertSame($expected, $validator->errors($data, true));
  1159. $this->assertEmpty($validator->errors($data, false));
  1160. }
  1161. /**
  1162. * Tests the notEmptyDate method
  1163. *
  1164. * @return void
  1165. */
  1166. public function testNotEmptyDate()
  1167. {
  1168. $validator = new Validator();
  1169. $validator->notEmptyDate('date', 'required field');
  1170. $this->assertFalse($validator->isEmptyAllowed('date', true));
  1171. $this->assertFalse($validator->isEmptyAllowed('date', false));
  1172. $error = ['date' => ['_empty' => 'required field']];
  1173. $data = [
  1174. 'date' => [
  1175. 'year' => '',
  1176. 'month' => '',
  1177. 'day' => '',
  1178. ],
  1179. ];
  1180. $result = $validator->errors($data);
  1181. $this->assertSame($error, $result);
  1182. $data = ['date' => ''];
  1183. $result = $validator->errors($data);
  1184. $this->assertSame($error, $result);
  1185. $data = ['date' => null];
  1186. $result = $validator->errors($data);
  1187. $this->assertSame($error, $result);
  1188. $data = ['date' => []];
  1189. $result = $validator->errors($data);
  1190. $this->assertSame($error, $result);
  1191. $data = [
  1192. 'date' => [
  1193. 'year' => 2019,
  1194. 'month' => 2,
  1195. 'day' => 17,
  1196. ],
  1197. ];
  1198. $result = $validator->errors($data);
  1199. $this->assertEmpty($result);
  1200. }
  1201. /**
  1202. * Test notEmptyDate with update mode
  1203. *
  1204. * @return void
  1205. */
  1206. public function testNotEmptyDateUpdate()
  1207. {
  1208. $validator = new Validator();
  1209. $validator->notEmptyDate('date', 'message', 'update');
  1210. $this->assertTrue($validator->isEmptyAllowed('date', true));
  1211. $this->assertFalse($validator->isEmptyAllowed('date', false));
  1212. $data = ['date' => null];
  1213. $expected = ['date' => ['_empty' => 'message']];
  1214. $this->assertSame($expected, $validator->errors($data, false));
  1215. $this->assertEmpty($validator->errors($data, true));
  1216. }
  1217. /**
  1218. * Tests the allowEmptyTime method
  1219. *
  1220. * @return void
  1221. */
  1222. public function testAllowEmptyTime()
  1223. {
  1224. $validator = new Validator();
  1225. $validator->allowEmptyTime('time')
  1226. ->time('time');
  1227. $this->assertTrue($validator->field('time')->isEmptyAllowed());
  1228. $data = [
  1229. 'time' => [
  1230. 'hour' => '',
  1231. 'minute' => '',
  1232. 'second' => '',
  1233. ],
  1234. ];
  1235. $result = $validator->errors($data);
  1236. $this->assertEmpty($result);
  1237. $data = [
  1238. 'time' => '',
  1239. ];
  1240. $result = $validator->errors($data);
  1241. $this->assertEmpty($result);
  1242. $data = [
  1243. 'time' => null,
  1244. ];
  1245. $result = $validator->errors($data);
  1246. $this->assertEmpty($result);
  1247. $data = ['time' => []];
  1248. $result = $validator->errors($data);
  1249. $this->assertEmpty($result);
  1250. }
  1251. /**
  1252. * test allowEmptyTime with condition
  1253. *
  1254. * @return void
  1255. */
  1256. public function testAllowEmptyTimeCondition()
  1257. {
  1258. $validator = new Validator();
  1259. $validator->allowEmptyTime('time', 'valid time', 'update');
  1260. $this->assertFalse($validator->isEmptyAllowed('time', true));
  1261. $this->assertTrue($validator->isEmptyAllowed('time', false));
  1262. $data = [
  1263. 'time' => null,
  1264. ];
  1265. $expected = [
  1266. 'time' => ['_empty' => 'valid time'],
  1267. ];
  1268. $this->assertSame($expected, $validator->errors($data, true));
  1269. $this->assertEmpty($validator->errors($data, false));
  1270. }
  1271. /**
  1272. * test allowEmptyTime with deprecated argument order
  1273. *
  1274. * @return void
  1275. */
  1276. public function testAllowEmptyTimeConditionDeprecated()
  1277. {
  1278. $validator = new Validator();
  1279. $this->deprecated(function () use ($validator) {
  1280. $validator->allowEmptyTime('time', 'update', 'valid time');
  1281. });
  1282. $this->assertFalse($validator->isEmptyAllowed('time', true));
  1283. $this->assertTrue($validator->isEmptyAllowed('time', false));
  1284. $data = [
  1285. 'time' => null,
  1286. ];
  1287. $expected = [
  1288. 'time' => ['_empty' => 'valid time'],
  1289. ];
  1290. $this->assertSame($expected, $validator->errors($data, true));
  1291. $this->assertEmpty($validator->errors($data, false));
  1292. }
  1293. /**
  1294. * Tests the notEmptyTime method
  1295. *
  1296. * @return void
  1297. */
  1298. public function testNotEmptyTime()
  1299. {
  1300. $validator = new Validator();
  1301. $validator->notEmptyTime('time', 'required field');
  1302. $this->assertFalse($validator->isEmptyAllowed('time', true));
  1303. $this->assertFalse($validator->isEmptyAllowed('time', false));
  1304. $error = ['time' => ['_empty' => 'required field']];
  1305. $data = [
  1306. 'time' => [
  1307. 'hour' => '',
  1308. 'minute' => '',
  1309. 'second' => '',
  1310. ],
  1311. ];
  1312. $result = $validator->errors($data);
  1313. $this->assertSame($error, $result);
  1314. $data = ['time' => ''];
  1315. $result = $validator->errors($data);
  1316. $this->assertSame($error, $result);
  1317. $data = ['time' => null];
  1318. $result = $validator->errors($data);
  1319. $this->assertSame($error, $result);
  1320. $data = ['time' => []];
  1321. $result = $validator->errors($data);
  1322. $this->assertSame($error, $result);
  1323. $data = ['time' => ['hour' => 12, 'minute' => 12, 'second' => 12]];
  1324. $result = $validator->errors($data);
  1325. $this->assertEmpty($result);
  1326. }
  1327. /**
  1328. * Test notEmptyTime with update mode
  1329. *
  1330. * @return void
  1331. */
  1332. public function testNotEmptyTimeUpdate()
  1333. {
  1334. $validator = new Validator();
  1335. $validator->notEmptyTime('time', 'message', 'update');
  1336. $this->assertTrue($validator->isEmptyAllowed('time', true));
  1337. $this->assertFalse($validator->isEmptyAllowed('time', false));
  1338. $data = ['time' => null];
  1339. $expected = ['time' => ['_empty' => 'message']];
  1340. $this->assertEmpty($validator->errors($data, true));
  1341. $this->assertSame($expected, $validator->errors($data, false));
  1342. }
  1343. /**
  1344. * Tests the allowEmptyDateTime method
  1345. *
  1346. * @return void
  1347. */
  1348. public function testAllowEmptyDateTime()
  1349. {
  1350. $validator = new Validator();
  1351. $validator->allowEmptyDate('published')
  1352. ->dateTime('published');
  1353. $this->assertTrue($validator->field('published')->isEmptyAllowed());
  1354. $data = [
  1355. 'published' => [
  1356. 'year' => '',
  1357. 'month' => '',
  1358. 'day' => '',
  1359. 'hour' => '',
  1360. 'minute' => '',
  1361. 'second' => '',
  1362. ],
  1363. ];
  1364. $result = $validator->errors($data);
  1365. $this->assertEmpty($result);
  1366. $data = [
  1367. 'published' => '',
  1368. ];
  1369. $result = $validator->errors($data);
  1370. $this->assertEmpty($result);
  1371. $data = [
  1372. 'published' => null,
  1373. ];
  1374. $result = $validator->errors($data);
  1375. $this->assertEmpty($result);
  1376. $data = ['published' => []];
  1377. $this->assertEmpty($validator->errors($data));
  1378. }
  1379. /**
  1380. * test allowEmptyDateTime with a condition
  1381. *
  1382. * @return void
  1383. */
  1384. public function testAllowEmptyDateTimeCondition()
  1385. {
  1386. $validator = new Validator();
  1387. $validator->allowEmptyDateTime('published', 'datetime required', 'update');
  1388. $this->assertFalse($validator->isEmptyAllowed('published', true));
  1389. $this->assertTrue($validator->isEmptyAllowed('published', false));
  1390. $data = [
  1391. 'published' => null,
  1392. ];
  1393. $expected = [
  1394. 'published' => ['_empty' => 'datetime required'],
  1395. ];
  1396. $this->assertSame($expected, $validator->errors($data, true));
  1397. $this->assertEmpty($validator->errors($data, false));
  1398. }
  1399. /**
  1400. * test allowEmptyDateTime with deprecated argument order
  1401. *
  1402. * @return void
  1403. */
  1404. public function testAllowEmptyDateTimeDeprecated()
  1405. {
  1406. $validator = new Validator();
  1407. $this->deprecated(function () use ($validator) {
  1408. $validator->allowEmptyDateTime('published', 'datetime required', 'update');
  1409. });
  1410. $this->assertFalse($validator->isEmptyAllowed('published', true));
  1411. $this->assertTrue($validator->isEmptyAllowed('published', false));
  1412. $data = [
  1413. 'published' => null,
  1414. ];
  1415. $expected = [
  1416. 'published' => ['_empty' => 'datetime required'],
  1417. ];
  1418. $this->assertSame($expected, $validator->errors($data, true));
  1419. $this->assertEmpty($validator->errors($data, false));
  1420. }
  1421. /**
  1422. * Tests the notEmptyDateTime method
  1423. *
  1424. * @return void
  1425. */
  1426. public function testNotEmptyDateTime()
  1427. {
  1428. $validator = new Validator();
  1429. $validator->notEmptyDateTime('published', 'required field');
  1430. $this->assertFalse($validator->isEmptyAllowed('published', true));
  1431. $this->assertFalse($validator->isEmptyAllowed('published', false));
  1432. $error = ['published' => ['_empty' => 'required field']];
  1433. $data = [
  1434. 'published' => [
  1435. 'year' => '',
  1436. 'month' => '',
  1437. 'day' => '',
  1438. 'hour' => '',
  1439. 'minute' => '',
  1440. 'second' => '',
  1441. ],
  1442. ];
  1443. $result = $validator->errors($data);
  1444. $this->assertSame($error, $result);
  1445. $data = ['published' => ''];
  1446. $result = $validator->errors($data);
  1447. $this->assertSame($error, $result);
  1448. $data = ['published' => null];
  1449. $result = $validator->errors($data);
  1450. $this->assertSame($error, $result);
  1451. $data = ['published' => []];
  1452. $this->assertSame($error, $validator->errors($data));
  1453. $data = [
  1454. 'published' => [
  1455. 'year' => '2018',
  1456. 'month' => '2',
  1457. 'day' => '17',
  1458. 'hour' => '14',
  1459. 'minute' => '32',
  1460. 'second' => '33',
  1461. ],
  1462. ];
  1463. $this->assertEmpty($validator->errors($data));
  1464. }
  1465. /**
  1466. * Test notEmptyDateTime with update mode
  1467. *
  1468. * @return voi
  1469. */
  1470. public function testNotEmptyDateTimeUpdate()
  1471. {
  1472. $validator = new Validator();
  1473. $validator->notEmptyDatetime('published', 'message', 'update');
  1474. $this->assertTrue($validator->isEmptyAllowed('published', true));
  1475. $this->assertFalse($validator->isEmptyAllowed('published', false));
  1476. $data = ['published' => null];
  1477. $expected = ['published' => ['_empty' => 'message']];
  1478. $this->assertSame($expected, $validator->errors($data, false));
  1479. $this->assertEmpty($validator->errors($data, true));
  1480. }
  1481. /**
  1482. * Test the notEmpty() method.
  1483. *
  1484. * @return void
  1485. */
  1486. public function testNotEmpty()
  1487. {
  1488. $validator = new Validator();
  1489. $validator->notEmpty('title');
  1490. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  1491. $validator->allowEmpty('title');
  1492. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  1493. }
  1494. /**
  1495. * Tests the notEmpty as array method
  1496. *
  1497. * @return void
  1498. */
  1499. public function testNotEmptyAsArray()
  1500. {
  1501. $validator = new Validator();
  1502. $validator->notEmpty(['title', 'created']);
  1503. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  1504. $this->assertFalse($validator->field('created')->isEmptyAllowed());
  1505. $validator->notEmpty([
  1506. 'title' => [
  1507. 'when' => false,
  1508. ],
  1509. 'content' => [
  1510. 'when' => 'update',
  1511. ],
  1512. 'posted_at' => [
  1513. 'when' => 'create',
  1514. ],
  1515. 'show_at' => [
  1516. 'message' => 'Show date cannot be empty',
  1517. 'when' => false,
  1518. ],
  1519. 'subject',
  1520. ], 'Not empty', true);
  1521. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  1522. $this->assertTrue($validator->isEmptyAllowed('content', true));
  1523. $this->assertFalse($validator->isEmptyAllowed('content', false));
  1524. $this->assertFalse($validator->isEmptyAllowed('posted_at', true));
  1525. $this->assertTrue($validator->isEmptyAllowed('posted_at', false));
  1526. $this->assertTrue($validator->field('subject')->isEmptyAllowed());
  1527. $errors = $validator->errors([
  1528. 'title' => '',
  1529. 'content' => '',
  1530. 'posted_at' => null,
  1531. 'show_at' => null,
  1532. 'subject' => '',
  1533. ], false);
  1534. $expected = [
  1535. 'title' => ['_empty' => 'Not empty'],
  1536. 'content' => ['_empty' => 'Not empty'],
  1537. 'show_at' => ['_empty' => 'Show date cannot be empty'],
  1538. ];
  1539. $this->assertEquals($expected, $errors);
  1540. }
  1541. /**
  1542. * Tests the notEmpty failure case
  1543. *
  1544. * @return void
  1545. */
  1546. public function testNotEmptyAsArrayFailure()
  1547. {
  1548. $this->expectException(\InvalidArgumentException::class);
  1549. $validator = new Validator();
  1550. $validator->notEmpty(['title' => 'derp', 'created' => false]);
  1551. }
  1552. /**
  1553. * Test the notEmpty() method.
  1554. *
  1555. * @return void
  1556. */
  1557. public function testNotEmptyModes()
  1558. {
  1559. $validator = new Validator();
  1560. $validator->notEmpty('title', 'Need a title', 'create');
  1561. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1562. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1563. $validator->notEmpty('title', 'Need a title', 'update');
  1564. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1565. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1566. $validator->notEmpty('title', 'Need a title');
  1567. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1568. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1569. $validator->notEmpty('title');
  1570. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1571. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1572. }
  1573. /**
  1574. * Test interactions between notEmpty() and isAllowed().
  1575. *
  1576. * @return void
  1577. */
  1578. public function testNotEmptyAndIsAllowed()
  1579. {
  1580. $validator = new Validator();
  1581. $validator->allowEmpty('title')
  1582. ->notEmpty('title', 'Need it', 'update');
  1583. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1584. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1585. $validator->allowEmpty('title')
  1586. ->notEmpty('title');
  1587. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1588. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1589. $validator->notEmpty('title')
  1590. ->allowEmpty('title', 'create');
  1591. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1592. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1593. }
  1594. /**
  1595. * Tests the allowEmpty method when passing a callback
  1596. *
  1597. * @return void
  1598. */
  1599. public function testAllowEmptyCallback()
  1600. {
  1601. $validator = new Validator();
  1602. $allow = true;
  1603. $validator->allowEmpty('title', function ($context) use (&$allow) {
  1604. $this->assertEquals([], $context['data']);
  1605. $this->assertEquals([], $context['providers']);
  1606. $this->assertTrue($context['newRecord']);
  1607. return $allow;
  1608. });
  1609. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1610. $allow = false;
  1611. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1612. }
  1613. /**
  1614. * Tests the notEmpty method when passing a callback
  1615. *
  1616. * @return void
  1617. */
  1618. public function testNotEmptyCallback()
  1619. {
  1620. $validator = new Validator();
  1621. $prevent = true;
  1622. $validator->notEmpty('title', 'error message', function ($context) use (&$prevent) {
  1623. $this->assertEquals([], $context['data']);
  1624. $this->assertEquals([], $context['providers']);
  1625. $this->assertFalse($context['newRecord']);
  1626. return $prevent;
  1627. });
  1628. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1629. $prevent = false;
  1630. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1631. }
  1632. /**
  1633. * Tests the isEmptyAllowed method
  1634. *
  1635. * @return void
  1636. */
  1637. public function testIsEmptyAllowed()
  1638. {
  1639. $validator = new Validator();
  1640. $this->assertSame($validator, $validator->allowEmpty('title'));
  1641. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1642. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1643. $validator->notEmpty('title');
  1644. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1645. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1646. $validator->allowEmpty('title', 'create');
  1647. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1648. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1649. $validator->allowEmpty('title', 'update');
  1650. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1651. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1652. }
  1653. /**
  1654. * Tests errors generated when a field is not allowed to be empty
  1655. *
  1656. * @return void
  1657. */
  1658. public function testErrorsWithEmptyNotAllowed()
  1659. {
  1660. $validator = new Validator();
  1661. $validator->notEmpty('title');
  1662. $errors = $validator->errors(['title' => '']);
  1663. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1664. $this->assertEquals($expected, $errors);
  1665. $errors = $validator->errors(['title' => []]);
  1666. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1667. $this->assertEquals($expected, $errors);
  1668. $errors = $validator->errors(['title' => null]);
  1669. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1670. $this->assertEquals($expected, $errors);
  1671. $errors = $validator->errors(['title' => 0]);
  1672. $this->assertEmpty($errors);
  1673. $errors = $validator->errors(['title' => '0']);
  1674. $this->assertEmpty($errors);
  1675. $errors = $validator->errors(['title' => false]);
  1676. $this->assertEmpty($errors);
  1677. }
  1678. /**
  1679. * Tests custom error messages generated when a field is allowed to be empty
  1680. *
  1681. * @return void
  1682. */
  1683. public function testCustomErrorsWithAllowedEmpty()
  1684. {
  1685. $validator = new Validator();
  1686. $validator->allowEmpty('title', false, 'Custom message');
  1687. $errors = $validator->errors(['title' => null]);
  1688. $expected = ['title' => ['_empty' => 'Custom message']];
  1689. $this->assertEquals($expected, $errors);
  1690. }
  1691. /**
  1692. * Tests custom error messages generated when a field is not allowed to be empty
  1693. *
  1694. * @return void
  1695. */
  1696. public function testCustomErrorsWithEmptyNotAllowed()
  1697. {
  1698. $validator = new Validator();
  1699. $validator->notEmpty('title', 'Custom message');
  1700. $errors = $validator->errors(['title' => '']);
  1701. $expected = ['title' => ['_empty' => 'Custom message']];
  1702. $this->assertEquals($expected, $errors);
  1703. }
  1704. /**
  1705. * Tests errors generated when a field is allowed to be empty
  1706. *
  1707. * @return void
  1708. */
  1709. public function testErrorsWithEmptyAllowed()
  1710. {
  1711. $validator = new Validator();
  1712. $validator->allowEmpty('title');
  1713. $errors = $validator->errors(['title' => '']);
  1714. $this->assertEmpty($errors);
  1715. $errors = $validator->errors(['title' => []]);
  1716. $this->assertEmpty($errors);
  1717. $errors = $validator->errors(['title' => null]);
  1718. $this->assertEmpty($errors);
  1719. $errors = $validator->errors(['title' => 0]);
  1720. $this->assertEmpty($errors);
  1721. $errors = $validator->errors(['title' => 0.0]);
  1722. $this->assertEmpty($errors);
  1723. $errors = $validator->errors(['title' => '0']);
  1724. $this->assertEmpty($errors);
  1725. $errors = $validator->errors(['title' => false]);
  1726. $this->assertEmpty($errors);
  1727. }
  1728. /**
  1729. * Test the provider() method
  1730. *
  1731. * @return void
  1732. */
  1733. public function testProvider()
  1734. {
  1735. $validator = new Validator();
  1736. $object = new \stdClass();
  1737. $this->assertSame($validator, $validator->setProvider('foo', $object));
  1738. $this->assertSame($object, $validator->getProvider('foo'));
  1739. $this->assertNull($validator->getProvider('bar'));
  1740. $another = new \stdClass();
  1741. $this->assertSame($validator, $validator->setProvider('bar', $another));
  1742. $this->assertSame($another, $validator->getProvider('bar'));
  1743. $this->assertEquals(new \Cake\Validation\RulesProvider(), $validator->getProvider('default'));
  1744. }
  1745. /**
  1746. * Tests errors() method when using validators from the default provider, this proves
  1747. * that it returns a default validation message and the custom one set in the rule
  1748. *
  1749. * @return void
  1750. */
  1751. public function testErrorsFromDefaultProvider()
  1752. {
  1753. $validator = new Validator();
  1754. $validator
  1755. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1756. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  1757. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1758. $errors = $validator->errors(['email' => 'not an email!']);
  1759. $expected = [
  1760. 'email' => [
  1761. 'alpha' => 'The provided value is invalid',
  1762. 'email' => 'Y u no write email?',
  1763. ],
  1764. ];
  1765. $this->assertEquals($expected, $errors);
  1766. }
  1767. /**
  1768. * Tests using validation methods from different providers and returning the error
  1769. * as a string
  1770. *
  1771. * @return void
  1772. */
  1773. public function testErrorsFromCustomProvider()
  1774. {
  1775. $validator = new Validator();
  1776. $validator
  1777. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1778. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1779. $thing = $this->getMockBuilder('\stdClass')
  1780. ->setMethods(['isCool'])
  1781. ->getMock();
  1782. $thing->expects($this->once())->method('isCool')
  1783. ->will($this->returnCallback(function ($data, $context) use ($thing) {
  1784. $this->assertEquals('bar', $data);
  1785. $expected = [
  1786. 'default' => new \Cake\Validation\RulesProvider(),
  1787. 'thing' => $thing,
  1788. ];
  1789. $expected = [
  1790. 'newRecord' => true,
  1791. 'providers' => $expected,
  1792. 'data' => [
  1793. 'email' => '!',
  1794. 'title' => 'bar',
  1795. ],
  1796. 'field' => 'title',
  1797. ];
  1798. $this->assertEquals($expected, $context);
  1799. return "That ain't cool, yo";
  1800. }));
  1801. $validator->setProvider('thing', $thing);
  1802. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  1803. $expected = [
  1804. 'email' => ['alpha' => 'The provided value is invalid'],
  1805. 'title' => ['cool' => "That ain't cool, yo"],
  1806. ];
  1807. $this->assertEquals($expected, $errors);
  1808. }
  1809. /**
  1810. * Tests that it is possible to pass extra arguments to the validation function
  1811. * and it still gets the providers as last argument
  1812. *
  1813. * @return void
  1814. */
  1815. public function testMethodsWithExtraArguments()
  1816. {
  1817. $validator = new Validator();
  1818. $validator->add('title', 'cool', [
  1819. 'rule' => ['isCool', 'and', 'awesome'],
  1820. 'provider' => 'thing',
  1821. ]);
  1822. $thing = $this->getMockBuilder('\stdClass')
  1823. ->setMethods(['isCool'])
  1824. ->getMock();
  1825. $thing->expects($this->once())->method('isCool')
  1826. ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
  1827. $this->assertEquals('bar', $data);
  1828. $this->assertEquals('and', $a);
  1829. $this->assertEquals('awesome', $b);
  1830. $expected = [
  1831. 'default' => new \Cake\Validation\RulesProvider(),
  1832. 'thing' => $thing,
  1833. ];
  1834. $expected = [
  1835. 'newRecord' => true,
  1836. 'providers' => $expected,
  1837. 'data' => [
  1838. 'email' => '!',
  1839. 'title' => 'bar',
  1840. ],
  1841. 'field' => 'title',
  1842. ];
  1843. $this->assertEquals($expected, $context);
  1844. return "That ain't cool, yo";
  1845. }));
  1846. $validator->setProvider('thing', $thing);
  1847. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  1848. $expected = [
  1849. 'title' => ['cool' => "That ain't cool, yo"],
  1850. ];
  1851. $this->assertEquals($expected, $errors);
  1852. }
  1853. /**
  1854. * Tests that it is possible to use a closure as a rule
  1855. *
  1856. * @return void
  1857. */
  1858. public function testUsingClosureAsRule()
  1859. {
  1860. $validator = new Validator();
  1861. $validator->add('name', 'myRule', [
  1862. 'rule' => function ($data, $provider) {
  1863. $this->assertEquals('foo', $data);
  1864. return 'You fail';
  1865. },
  1866. ]);
  1867. $expected = ['name' => ['myRule' => 'You fail']];
  1868. $this->assertEquals($expected, $validator->errors(['name' => 'foo']));
  1869. }
  1870. /**
  1871. * Tests that setting last to a rule will stop validating the rest of the rules
  1872. *
  1873. * @return void
  1874. */
  1875. public function testErrorsWithLastRule()
  1876. {
  1877. $validator = new Validator();
  1878. $validator
  1879. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  1880. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1881. $errors = $validator->errors(['email' => 'not an email!']);
  1882. $expected = [
  1883. 'email' => [
  1884. 'alpha' => 'The provided value is invalid',
  1885. ],
  1886. ];
  1887. $this->assertEquals($expected, $errors);
  1888. }
  1889. /**
  1890. * Tests it is possible to get validation sets for a field using an array interface
  1891. *
  1892. * @return void
  1893. */
  1894. public function testArrayAccessGet()
  1895. {
  1896. $validator = new Validator();
  1897. $validator
  1898. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1899. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1900. $this->assertSame($validator['email'], $validator->field('email'));
  1901. $this->assertSame($validator['title'], $validator->field('title'));
  1902. }
  1903. /**
  1904. * Tests it is possible to check for validation sets for a field using an array interface
  1905. *
  1906. * @return void
  1907. */
  1908. public function testArrayAccessExists()
  1909. {
  1910. $validator = new Validator();
  1911. $validator
  1912. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1913. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1914. $this->assertArrayHasKey('email', $validator);
  1915. $this->assertArrayHasKey('title', $validator);
  1916. $this->assertArrayNotHasKey('foo', $validator);
  1917. }
  1918. /**
  1919. * Tests it is possible to set validation rules for a field using an array interface
  1920. *
  1921. * @return void
  1922. */
  1923. public function testArrayAccessSet()
  1924. {
  1925. $validator = new Validator();
  1926. $validator
  1927. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1928. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1929. $validator['name'] = $validator->field('title');
  1930. $this->assertSame($validator->field('title'), $validator->field('name'));
  1931. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  1932. $this->assertEquals($validator->field('email'), $validator->field('email'));
  1933. }
  1934. /**
  1935. * Tests it is possible to unset validation rules
  1936. *
  1937. * @return void
  1938. */
  1939. public function testArrayAccessUnset()
  1940. {
  1941. $validator = new Validator();
  1942. $validator
  1943. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1944. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1945. $this->assertArrayHasKey('title', $validator);
  1946. unset($validator['title']);
  1947. $this->assertArrayNotHasKey('title', $validator);
  1948. }
  1949. /**
  1950. * Tests the countable interface
  1951. *
  1952. * @return void
  1953. */
  1954. public function testCount()
  1955. {
  1956. $validator = new Validator();
  1957. $validator
  1958. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1959. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1960. $this->assertCount(2, $validator);
  1961. }
  1962. /**
  1963. * Tests adding rules via alternative syntax
  1964. *
  1965. * @return void
  1966. */
  1967. public function testAddMultiple()
  1968. {
  1969. $validator = new Validator();
  1970. $validator->add('title', [
  1971. 'notBlank' => [
  1972. 'rule' => 'notBlank',
  1973. ],
  1974. 'length' => [
  1975. 'rule' => ['minLength', 10],
  1976. 'message' => 'Titles need to be at least 10 characters long',
  1977. ],
  1978. ]);
  1979. $set = $validator->field('title');
  1980. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  1981. $this->assertCount(2, $set);
  1982. }
  1983. /**
  1984. * Integration test for compareWith validator.
  1985. *
  1986. * @return void
  1987. */
  1988. public function testCompareWithIntegration()
  1989. {
  1990. $validator = new Validator();
  1991. $validator->add('password', [
  1992. 'compare' => [
  1993. 'rule' => ['compareWith', 'password_compare'],
  1994. ],
  1995. ]);
  1996. $data = [
  1997. 'password' => 'test',
  1998. 'password_compare' => 'not the same',
  1999. ];
  2000. $this->assertNotEmpty($validator->errors($data), 'Validation should fail.');
  2001. }
  2002. /**
  2003. * Test debugInfo helper method.
  2004. *
  2005. * @return void
  2006. */
  2007. public function testDebugInfo()
  2008. {
  2009. $validator = new Validator();
  2010. $validator->setProvider('test', $this);
  2011. $validator->add('title', 'not-empty', ['rule' => 'notBlank']);
  2012. $validator->requirePresence('body');
  2013. $validator->allowEmpty('published');
  2014. $result = $validator->__debugInfo();
  2015. $expected = [
  2016. '_providers' => ['test'],
  2017. '_fields' => [
  2018. 'title' => [
  2019. 'isPresenceRequired' => false,
  2020. 'isEmptyAllowed' => false,
  2021. 'rules' => ['not-empty'],
  2022. ],
  2023. 'body' => [
  2024. 'isPresenceRequired' => true,
  2025. 'isEmptyAllowed' => false,
  2026. 'rules' => [],
  2027. ],
  2028. 'published' => [
  2029. 'isPresenceRequired' => false,
  2030. 'isEmptyAllowed' => true,
  2031. 'rules' => [],
  2032. ],
  2033. ],
  2034. '_presenceMessages' => [],
  2035. '_allowEmptyMessages' => [],
  2036. '_allowEmptyFlags' => [],
  2037. '_useI18n' => true,
  2038. ];
  2039. $this->assertEquals($expected, $result);
  2040. }
  2041. /**
  2042. * Tests that the 'create' and 'update' modes are preserved when using
  2043. * nested validators
  2044. *
  2045. * @return void
  2046. */
  2047. public function testNestedValidatorCreate()
  2048. {
  2049. $validator = new Validator();
  2050. $inner = new Validator();
  2051. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  2052. $validator->addNested('user', $inner);
  2053. $this->assertNotEmpty($validator->errors(['user' => ['username' => 'example']], true));
  2054. $this->assertEmpty($validator->errors(['user' => ['username' => 'a']], false));
  2055. }
  2056. /**
  2057. * Tests that the 'create' and 'update' modes are preserved when using
  2058. * nested validators
  2059. *
  2060. * @return void
  2061. */
  2062. public function testNestedManyValidatorCreate()
  2063. {
  2064. $validator = new Validator();
  2065. $inner = new Validator();
  2066. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  2067. $validator->addNestedMany('user', $inner);
  2068. $this->assertNotEmpty($validator->errors(['user' => [['username' => 'example']]], true));
  2069. $this->assertEmpty($validator->errors(['user' => [['username' => 'a']]], false));
  2070. }
  2071. /**
  2072. * Tests the notBlank proxy method
  2073. *
  2074. * @return void
  2075. */
  2076. public function testNotBlank()
  2077. {
  2078. $validator = new Validator();
  2079. $this->assertProxyMethod($validator, 'notBlank');
  2080. $this->assertNotEmpty($validator->errors(['username' => ' ']));
  2081. }
  2082. /**
  2083. * Tests the alphanumeric proxy method
  2084. *
  2085. * @return void
  2086. */
  2087. public function testAlphanumeric()
  2088. {
  2089. $validator = new Validator();
  2090. $this->assertProxyMethod($validator, 'alphaNumeric');
  2091. $this->assertNotEmpty($validator->errors(['username' => '$']));
  2092. }
  2093. /**
  2094. * Tests the lengthBetween proxy method
  2095. *
  2096. * @return void
  2097. */
  2098. public function testLengthBetween()
  2099. {
  2100. $validator = new Validator();
  2101. $this->assertProxyMethod($validator, 'lengthBetween', [5, 7], [5, 7]);
  2102. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  2103. }
  2104. /**
  2105. * Tests the lengthBetween proxy method
  2106. *
  2107. * @return void
  2108. */
  2109. public function testLengthBetweenFailure()
  2110. {
  2111. $this->expectException(\InvalidArgumentException::class);
  2112. $validator = new Validator();
  2113. $validator->lengthBetween('username', [7]);
  2114. }
  2115. /**
  2116. * Tests the creditCard proxy method
  2117. *
  2118. * @return void
  2119. */
  2120. public function testCreditCard()
  2121. {
  2122. $validator = new Validator();
  2123. $this->assertProxyMethod($validator, 'creditCard', 'all', ['all', true], 'creditCard');
  2124. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  2125. }
  2126. /**
  2127. * Tests the greaterThan proxy method
  2128. *
  2129. * @return void
  2130. */
  2131. public function testGreaterThan()
  2132. {
  2133. $validator = new Validator();
  2134. $this->assertProxyMethod($validator, 'greaterThan', 5, [Validation::COMPARE_GREATER, 5], 'comparison');
  2135. $this->assertNotEmpty($validator->errors(['username' => 2]));
  2136. }
  2137. /**
  2138. * Tests the greaterThanOrEqual proxy method
  2139. *
  2140. * @return void
  2141. */
  2142. public function testGreaterThanOrEqual()
  2143. {
  2144. $validator = new Validator();
  2145. $this->assertProxyMethod($validator, 'greaterThanOrEqual', 5, [Validation::COMPARE_GREATER_OR_EQUAL, 5], 'comparison');
  2146. $this->assertNotEmpty($validator->errors(['username' => 2]));
  2147. }
  2148. /**
  2149. * Tests the lessThan proxy method
  2150. *
  2151. * @return void
  2152. */
  2153. public function testLessThan()
  2154. {
  2155. $validator = new Validator();
  2156. $this->assertProxyMethod($validator, 'lessThan', 5, [Validation::COMPARE_LESS, 5], 'comparison');
  2157. $this->assertNotEmpty($validator->errors(['username' => 5]));
  2158. }
  2159. /**
  2160. * Tests the lessThanOrEqual proxy method
  2161. *
  2162. * @return void
  2163. */
  2164. public function testLessThanOrEqual()
  2165. {
  2166. $validator = new Validator();
  2167. $this->assertProxyMethod($validator, 'lessThanOrEqual', 5, [Validation::COMPARE_LESS_OR_EQUAL, 5], 'comparison');
  2168. $this->assertNotEmpty($validator->errors(['username' => 6]));
  2169. }
  2170. /**
  2171. * Tests the equals proxy method
  2172. *
  2173. * @return void
  2174. */
  2175. public function testEquals()
  2176. {
  2177. $validator = new Validator();
  2178. $this->assertProxyMethod($validator, 'equals', 5, [Validation::COMPARE_EQUAL, 5], 'comparison');
  2179. $this->assertEmpty($validator->errors(['username' => 5]));
  2180. $this->assertNotEmpty($validator->errors(['username' => 6]));
  2181. }
  2182. /**
  2183. * Tests the notEquals proxy method
  2184. *
  2185. * @return void
  2186. */
  2187. public function testNotEquals()
  2188. {
  2189. $validator = new Validator();
  2190. $this->assertProxyMethod($validator, 'notEquals', 5, [Validation::COMPARE_NOT_EQUAL, 5], 'comparison');
  2191. $this->assertNotEmpty($validator->errors(['username' => 5]));
  2192. }
  2193. /**
  2194. * Tests the sameAs proxy method
  2195. *
  2196. * @return void
  2197. */
  2198. public function testSameAs()
  2199. {
  2200. $validator = new Validator();
  2201. $this->assertProxyMethod($validator, 'sameAs', 'other', ['other', Validation::COMPARE_SAME], 'compareFields');
  2202. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  2203. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => '1']));
  2204. }
  2205. /**
  2206. * Tests the notSameAs proxy method
  2207. *
  2208. * @return void
  2209. */
  2210. public function testNotSameAs()
  2211. {
  2212. $validator = new Validator();
  2213. $this->assertProxyMethod($validator, 'notSameAs', 'other', ['other', Validation::COMPARE_NOT_SAME], 'compareFields');
  2214. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'foo']));
  2215. }
  2216. /**
  2217. * Tests the equalToField proxy method
  2218. *
  2219. * @return void
  2220. */
  2221. public function testEqualToField()
  2222. {
  2223. $validator = new Validator();
  2224. $this->assertProxyMethod($validator, 'equalToField', 'other', ['other', Validation::COMPARE_EQUAL], 'compareFields');
  2225. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  2226. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'bar']));
  2227. }
  2228. /**
  2229. * Tests the notEqualToField proxy method
  2230. *
  2231. * @return void
  2232. */
  2233. public function testNotEqualToField()
  2234. {
  2235. $validator = new Validator();
  2236. $this->assertProxyMethod($validator, 'notEqualToField', 'other', ['other', Validation::COMPARE_NOT_EQUAL], 'compareFields');
  2237. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'foo']));
  2238. }
  2239. /**
  2240. * Tests the greaterThanField proxy method
  2241. *
  2242. * @return void
  2243. */
  2244. public function testGreaterThanField()
  2245. {
  2246. $validator = new Validator();
  2247. $this->assertProxyMethod($validator, 'greaterThanField', 'other', ['other', Validation::COMPARE_GREATER], 'compareFields');
  2248. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 1]));
  2249. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 2]));
  2250. }
  2251. /**
  2252. * Tests the greaterThanOrEqualToField proxy method
  2253. *
  2254. * @return void
  2255. */
  2256. public function testGreaterThanOrEqualToField()
  2257. {
  2258. $validator = new Validator();
  2259. $this->assertProxyMethod($validator, 'greaterThanOrEqualToField', 'other', ['other', Validation::COMPARE_GREATER_OR_EQUAL], 'compareFields');
  2260. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 2]));
  2261. }
  2262. /**
  2263. * Tests the lessThanField proxy method
  2264. *
  2265. * @return void
  2266. */
  2267. public function testLessThanField()
  2268. {
  2269. $validator = new Validator();
  2270. $this->assertProxyMethod($validator, 'lessThanField', 'other', ['other', Validation::COMPARE_LESS], 'compareFields');
  2271. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 1]));
  2272. $this->assertNotEmpty($validator->errors(['username' => 2, 'other' => 1]));
  2273. }
  2274. /**
  2275. * Tests the lessThanOrEqualToField proxy method
  2276. *
  2277. * @return void
  2278. */
  2279. public function testLessThanOrEqualToField()
  2280. {
  2281. $validator = new Validator();
  2282. $this->assertProxyMethod($validator, 'lessThanOrEqualToField', 'other', ['other', Validation::COMPARE_LESS_OR_EQUAL], 'compareFields');
  2283. $this->assertNotEmpty($validator->errors(['username' => 2, 'other' => 1]));
  2284. }
  2285. /**
  2286. * Tests the containsNonAlphaNumeric proxy method
  2287. *
  2288. * @return void
  2289. */
  2290. public function testContainsNonAlphaNumeric()
  2291. {
  2292. $validator = new Validator();
  2293. $this->assertProxyMethod($validator, 'containsNonAlphaNumeric', 2, [2]);
  2294. $this->assertNotEmpty($validator->errors(['username' => '$']));
  2295. }
  2296. /**
  2297. * Tests the date proxy method
  2298. *
  2299. * @return void
  2300. */
  2301. public function testDate()
  2302. {
  2303. $validator = new Validator();
  2304. $this->assertProxyMethod($validator, 'date', ['ymd'], [['ymd']]);
  2305. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  2306. }
  2307. /**
  2308. * Tests the dateTime proxy method
  2309. *
  2310. * @return void
  2311. */
  2312. public function testDateTime()
  2313. {
  2314. $validator = new Validator();
  2315. $this->assertProxyMethod($validator, 'dateTime', ['ymd'], [['ymd']], 'datetime');
  2316. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  2317. }
  2318. /**
  2319. * Tests the time proxy method
  2320. *
  2321. * @return void
  2322. */
  2323. public function testTime()
  2324. {
  2325. $validator = new Validator();
  2326. $this->assertProxyMethod($validator, 'time');
  2327. $this->assertNotEmpty($validator->errors(['username' => 'not a time']));
  2328. }
  2329. /**
  2330. * Tests the localizedTime proxy method
  2331. *
  2332. * @return void
  2333. */
  2334. public function testLocalizedTime()
  2335. {
  2336. $validator = new Validator();
  2337. $this->assertProxyMethod($validator, 'localizedTime', 'date', ['date']);
  2338. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  2339. }
  2340. /**
  2341. * Tests the boolean proxy method
  2342. *
  2343. * @return void
  2344. */
  2345. public function testBoolean()
  2346. {
  2347. $validator = new Validator();
  2348. $this->assertProxyMethod($validator, 'boolean');
  2349. $this->assertNotEmpty($validator->errors(['username' => 'not a boolean']));
  2350. }
  2351. /**
  2352. * Tests the decimal proxy method
  2353. *
  2354. * @return void
  2355. */
  2356. public function testDecimal()
  2357. {
  2358. $validator = new Validator();
  2359. $this->assertProxyMethod($validator, 'decimal', 2, [2]);
  2360. $this->assertNotEmpty($validator->errors(['username' => 10.1]));
  2361. }
  2362. /**
  2363. * Tests the ip proxy methods
  2364. *
  2365. * @return void
  2366. */
  2367. public function testIps()
  2368. {
  2369. $validator = new Validator();
  2370. $this->assertProxyMethod($validator, 'ip');
  2371. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  2372. $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip');
  2373. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  2374. $this->assertProxyMethod($validator, 'ipv6', null, ['ipv6'], 'ip');
  2375. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  2376. }
  2377. /**
  2378. * Tests the minLength proxy method
  2379. *
  2380. * @return void
  2381. */
  2382. public function testMinLength()
  2383. {
  2384. $validator = new Validator();
  2385. $this->assertProxyMethod($validator, 'minLength', 2, [2]);
  2386. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  2387. }
  2388. /**
  2389. * Tests the minLengthBytes proxy method
  2390. *
  2391. * @return void
  2392. */
  2393. public function testMinLengthBytes()
  2394. {
  2395. $validator = new Validator();
  2396. $this->assertProxyMethod($validator, 'minLengthBytes', 11, [11]);
  2397. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  2398. }
  2399. /**
  2400. * Tests the maxLength proxy method
  2401. *
  2402. * @return void
  2403. */
  2404. public function testMaxLength()
  2405. {
  2406. $validator = new Validator();
  2407. $this->assertProxyMethod($validator, 'maxLength', 2, [2]);
  2408. $this->assertNotEmpty($validator->errors(['username' => 'aaa']));
  2409. }
  2410. /**
  2411. * Tests the maxLengthBytes proxy method
  2412. *
  2413. * @return void
  2414. */
  2415. public function testMaxLengthBytes()
  2416. {
  2417. $validator = new Validator();
  2418. $this->assertProxyMethod($validator, 'maxLengthBytes', 9, [9]);
  2419. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  2420. }
  2421. /**
  2422. * Tests the numeric proxy method
  2423. *
  2424. * @return void
  2425. */
  2426. public function testNumeric()
  2427. {
  2428. $validator = new Validator();
  2429. $this->assertProxyMethod($validator, 'numeric');
  2430. $this->assertEmpty($validator->errors(['username' => '22']));
  2431. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  2432. }
  2433. /**
  2434. * Tests the naturalNumber proxy method
  2435. *
  2436. * @return void
  2437. */
  2438. public function testNaturalNumber()
  2439. {
  2440. $validator = new Validator();
  2441. $this->assertProxyMethod($validator, 'naturalNumber', null, [false]);
  2442. $this->assertNotEmpty($validator->errors(['username' => 0]));
  2443. }
  2444. /**
  2445. * Tests the nonNegativeInteger proxy method
  2446. *
  2447. * @return void
  2448. */
  2449. public function testNonNegativeInteger()
  2450. {
  2451. $validator = new Validator();
  2452. $this->assertProxyMethod($validator, 'nonNegativeInteger', null, [true], 'naturalNumber');
  2453. $this->assertNotEmpty($validator->errors(['username' => -1]));
  2454. }
  2455. /**
  2456. * Tests the range proxy method
  2457. *
  2458. * @return void
  2459. */
  2460. public function testRange()
  2461. {
  2462. $validator = new Validator();
  2463. $this->assertProxyMethod($validator, 'range', [1, 4], [1, 4]);
  2464. $this->assertNotEmpty($validator->errors(['username' => 5]));
  2465. }
  2466. /**
  2467. * Tests the range failure case
  2468. *
  2469. * @return void
  2470. */
  2471. public function testRangeFailure()
  2472. {
  2473. $this->expectException(\InvalidArgumentException::class);
  2474. $validator = new Validator();
  2475. $validator->range('username', [1]);
  2476. }
  2477. /**
  2478. * Tests the url proxy method
  2479. *
  2480. * @return void
  2481. */
  2482. public function testUrl()
  2483. {
  2484. $validator = new Validator();
  2485. $this->assertProxyMethod($validator, 'url', null, [false]);
  2486. $this->assertNotEmpty($validator->errors(['username' => 'not url']));
  2487. }
  2488. /**
  2489. * Tests the urlWithProtocol proxy method
  2490. *
  2491. * @return void
  2492. */
  2493. public function testUrlWithProtocol()
  2494. {
  2495. $validator = new Validator();
  2496. $this->assertProxyMethod($validator, 'urlWithProtocol', null, [true], 'url');
  2497. $this->assertNotEmpty($validator->errors(['username' => 'google.com']));
  2498. }
  2499. /**
  2500. * Tests the inList proxy method
  2501. *
  2502. * @return void
  2503. */
  2504. public function testInList()
  2505. {
  2506. $validator = new Validator();
  2507. $this->assertProxyMethod($validator, 'inList', ['a', 'b'], [['a', 'b']]);
  2508. $this->assertNotEmpty($validator->errors(['username' => 'c']));
  2509. }
  2510. /**
  2511. * Tests the uuid proxy method
  2512. *
  2513. * @return void
  2514. */
  2515. public function testUuid()
  2516. {
  2517. $validator = new Validator();
  2518. $this->assertProxyMethod($validator, 'uuid');
  2519. $this->assertNotEmpty($validator->errors(['username' => 'not uuid']));
  2520. }
  2521. /**
  2522. * Tests the uploadedFile proxy method
  2523. *
  2524. * @return void
  2525. */
  2526. public function testUploadedFile()
  2527. {
  2528. $validator = new Validator();
  2529. $this->assertProxyMethod($validator, 'uploadedFile', ['foo' => 'bar'], [['foo' => 'bar']]);
  2530. $this->assertNotEmpty($validator->errors(['username' => []]));
  2531. }
  2532. /**
  2533. * Tests the latlog proxy methods
  2534. *
  2535. * @return void
  2536. */
  2537. public function testLatLong()
  2538. {
  2539. $validator = new Validator();
  2540. $this->assertProxyMethod($validator, 'latLong', null, [], 'geoCoordinate');
  2541. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2542. $this->assertProxyMethod($validator, 'latitude');
  2543. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2544. $this->assertProxyMethod($validator, 'longitude');
  2545. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2546. }
  2547. /**
  2548. * Tests the ascii proxy method
  2549. *
  2550. * @return void
  2551. */
  2552. public function testAscii()
  2553. {
  2554. $validator = new Validator();
  2555. $this->assertProxyMethod($validator, 'ascii');
  2556. $this->assertNotEmpty($validator->errors(['username' => 'ü']));
  2557. }
  2558. /**
  2559. * Tests the utf8 proxy methods
  2560. *
  2561. * @return void
  2562. */
  2563. public function testUtf8()
  2564. {
  2565. // Grinning face
  2566. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2567. $validator = new Validator();
  2568. $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]);
  2569. $this->assertEmpty($validator->errors(['username' => 'ü']));
  2570. $this->assertNotEmpty($validator->errors(['username' => $extended]));
  2571. }
  2572. /**
  2573. * Test utf8extended proxy method.
  2574. *
  2575. * @return void
  2576. */
  2577. public function testUtf8Extended()
  2578. {
  2579. // Grinning face
  2580. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2581. $validator = new Validator();
  2582. $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8');
  2583. $this->assertEmpty($validator->errors(['username' => 'ü']));
  2584. $this->assertEmpty($validator->errors(['username' => $extended]));
  2585. }
  2586. /**
  2587. * Tests the email proxy method
  2588. *
  2589. * @return void
  2590. */
  2591. public function testEmail()
  2592. {
  2593. $validator = new Validator();
  2594. $validator->email('username');
  2595. $this->assertEmpty($validator->errors(['username' => 'test@example.com']));
  2596. $this->assertNotEmpty($validator->errors(['username' => 'not an email']));
  2597. }
  2598. /**
  2599. * Tests the integer proxy method
  2600. *
  2601. * @return void
  2602. */
  2603. public function testInteger()
  2604. {
  2605. $validator = new Validator();
  2606. $this->assertProxyMethod($validator, 'integer', null, [], 'isInteger');
  2607. $this->assertNotEmpty($validator->errors(['username' => 'not integer']));
  2608. }
  2609. /**
  2610. * Tests the isArray proxy method
  2611. *
  2612. * @return void
  2613. */
  2614. public function testIsArray()
  2615. {
  2616. $validator = new Validator();
  2617. $validator->isArray('username');
  2618. $this->assertEmpty($validator->errors(['username' => [1, 2, 3]]));
  2619. $this->assertNotEmpty($validator->errors(['username' => 'is not an array']));
  2620. }
  2621. /**
  2622. * Tests the scalar proxy method
  2623. *
  2624. * @return void
  2625. */
  2626. public function testScalar()
  2627. {
  2628. $validator = new Validator();
  2629. $validator->scalar('username');
  2630. $this->assertEmpty($validator->errors(['username' => 'scalar']));
  2631. $this->assertNotEmpty($validator->errors(['username' => ['array']]));
  2632. }
  2633. /**
  2634. * Tests the hexColor proxy method
  2635. *
  2636. * @return void
  2637. */
  2638. public function testHexColor()
  2639. {
  2640. $validator = new Validator();
  2641. $this->assertProxyMethod($validator, 'hexColor');
  2642. $this->assertEmpty($validator->errors(['username' => '#FFFFFF']));
  2643. $this->assertNotEmpty($validator->errors(['username' => 'FFFFFF']));
  2644. }
  2645. /**
  2646. * Tests the multiple proxy method
  2647. *
  2648. * @return void
  2649. */
  2650. public function testMultiple()
  2651. {
  2652. $validator = new Validator();
  2653. $this->assertProxyMethod(
  2654. $validator,
  2655. 'multipleOptions',
  2656. ['min' => 1, 'caseInsensitive' => true],
  2657. [['min' => 1], true],
  2658. 'multiple'
  2659. );
  2660. $this->assertProxyMethod(
  2661. $validator,
  2662. 'multipleOptions',
  2663. ['min' => 1, 'caseInsensitive' => false],
  2664. [['min' => 1], false],
  2665. 'multiple'
  2666. );
  2667. $this->assertNotEmpty($validator->errors(['username' => '']));
  2668. }
  2669. /**
  2670. * Tests the hasAtLeast method
  2671. *
  2672. * @return void
  2673. */
  2674. public function testHasAtLeast()
  2675. {
  2676. $validator = new Validator();
  2677. $validator->hasAtLeast('things', 3);
  2678. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  2679. $this->assertEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  2680. $this->assertNotEmpty($validator->errors(['things' => [1, 2]]));
  2681. $this->assertNotEmpty($validator->errors(['things' => []]));
  2682. $this->assertNotEmpty($validator->errors(['things' => 'string']));
  2683. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  2684. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2685. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  2686. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => []]]));
  2687. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => 'string']]));
  2688. }
  2689. /**
  2690. * Tests the hasAtMost method
  2691. *
  2692. * @return void
  2693. */
  2694. public function testHasAtMost()
  2695. {
  2696. $validator = new Validator();
  2697. $validator->hasAtMost('things', 3);
  2698. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  2699. $this->assertEmpty($validator->errors(['things' => [1]]));
  2700. $this->assertNotEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  2701. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  2702. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  2703. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2704. }
  2705. /**
  2706. * Tests the regex proxy method
  2707. *
  2708. * @return void
  2709. */
  2710. public function testRegex()
  2711. {
  2712. $validator = new Validator();
  2713. $this->assertProxyMethod($validator, 'regex', '/(?<!\\S)\\d++(?!\\S)/', ['/(?<!\\S)\\d++(?!\\S)/'], 'custom');
  2714. $this->assertEmpty($validator->errors(['username' => '123']));
  2715. $this->assertNotEmpty($validator->errors(['username' => 'Foo']));
  2716. }
  2717. /**
  2718. * Tests that a rule in the Validator class exists and was configured as expected.
  2719. *
  2720. * @param Validator $validator
  2721. * @param string $method
  2722. * @param mixed $extra
  2723. * @param array $pass
  2724. * @param string|null $name
  2725. */
  2726. protected function assertProxyMethod($validator, $method, $extra = null, $pass = [], $name = null)
  2727. {
  2728. $name = $name ?: $method;
  2729. if ($extra !== null) {
  2730. $this->assertSame($validator, $validator->{$method}('username', $extra));
  2731. } else {
  2732. $this->assertSame($validator, $validator->{$method}('username'));
  2733. }
  2734. $rule = $validator->field('username')->rule($method);
  2735. $this->assertNotEmpty($rule, "Rule was not found for $method");
  2736. $this->assertNull($rule->get('message'), 'Message is present when it should not be');
  2737. $this->assertNull($rule->get('on'), 'On clause is present when it should not be');
  2738. $this->assertEquals($name, $rule->get('rule'), 'Rule name does not match');
  2739. $this->assertEquals($pass, $rule->get('pass'), 'Passed options are different');
  2740. $this->assertEquals('default', $rule->get('provider'), 'Provider does not match');
  2741. if ($extra !== null) {
  2742. $validator->{$method}('username', $extra, 'the message', 'create');
  2743. } else {
  2744. $validator->{$method}('username', 'the message', 'create');
  2745. }
  2746. $rule = $validator->field('username')->rule($method);
  2747. $this->assertEquals('the message', $rule->get('message'), 'Error messages are not the same');
  2748. $this->assertEquals('create', $rule->get('on'), 'On clause is wrong');
  2749. }
  2750. /**
  2751. * Testing adding DefaultProvider
  2752. *
  2753. * @return void
  2754. */
  2755. public function testAddingDefaultProvider()
  2756. {
  2757. $validator = new Validator();
  2758. $this->assertEmpty($validator->providers(), 'Providers should be empty');
  2759. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2760. $validator = new Validator();
  2761. $this->assertEquals($validator->providers(), ['test-provider'], 'Default provider `test-provider` is missing');
  2762. }
  2763. /**
  2764. * Testing getting DefaultProvider(s)
  2765. *
  2766. * @return void
  2767. */
  2768. public function testGetDefaultProvider()
  2769. {
  2770. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2771. $this->assertEquals(Validator::getDefaultProvider('test-provider'), 'MyNameSpace\Validation\MyProvider', 'Default provider `test-provider` is missing');
  2772. $this->assertNull(Validator::getDefaultProvider('invalid-provider'), 'Default provider (`invalid-provider`) should be missing');
  2773. $this->assertNull(Validator::getDefaultProvider(null), 'Default provider (null) should be missing');
  2774. Validator::addDefaultProvider('test-provider2', 'MyNameSpace\Validation\MySecondProvider');
  2775. $this->assertEquals(Validator::getDefaultProviders(), ['test-provider', 'test-provider2'], 'Default providers incorrect');
  2776. }
  2777. }