ValidatorTest.php 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  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', 'update', 'message');
  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. * Tests the allowEmptyArray method
  695. *
  696. * @return void
  697. */
  698. public function testAllowEmptyArray()
  699. {
  700. $validator = new Validator();
  701. $validator->allowEmptyArray('items')
  702. ->hasAtMost('items', 3);
  703. $this->assertTrue($validator->field('items')->isEmptyAllowed());
  704. $data = [
  705. 'items' => '',
  706. ];
  707. $result = $validator->errors($data);
  708. $this->assertEmpty($result);
  709. $data = [
  710. 'items' => null,
  711. ];
  712. $result = $validator->errors($data);
  713. $this->assertEmpty($result);
  714. $data = [
  715. 'items' => [],
  716. ];
  717. $result = $validator->errors($data);
  718. $this->assertEmpty($result);
  719. $data = [
  720. 'items' => [1, 2, 3, 4, 5],
  721. ];
  722. $expected = [
  723. 'items' => [
  724. 'hasAtMost' => 'The provided value is invalid',
  725. ],
  726. ];
  727. $result = $validator->errors($data);
  728. $this->assertSame($expected, $result);
  729. $validator = new Validator();
  730. $validator->allowEmptyArray('items', 'update', 'message');
  731. $this->assertFalse($validator->isEmptyAllowed('items', true));
  732. $this->assertTrue($validator->isEmptyAllowed('items', false));
  733. $data = [
  734. 'items' => null,
  735. ];
  736. $expected = [
  737. 'items' => ['_empty' => 'message'],
  738. ];
  739. $this->assertSame($expected, $validator->errors($data, true));
  740. $this->assertEmpty($validator->errors($data, false));
  741. }
  742. /**
  743. * Tests the allowEmptyFile method
  744. *
  745. * @return void
  746. */
  747. public function testAllowEmptyFile()
  748. {
  749. $validator = new Validator();
  750. $validator->allowEmptyFile('photo')
  751. ->uploadedFile('photo', []);
  752. $this->assertTrue($validator->field('photo')->isEmptyAllowed());
  753. $data = [
  754. 'photo' => [
  755. 'name' => '',
  756. 'type' => '',
  757. 'tmp_name' => '',
  758. 'error' => UPLOAD_ERR_NO_FILE,
  759. ]
  760. ];
  761. $result = $validator->errors($data);
  762. $this->assertEmpty($result);
  763. $data = [
  764. 'photo' => null,
  765. ];
  766. $result = $validator->errors($data);
  767. $this->assertEmpty($result);
  768. $data = [
  769. 'photo' => [
  770. 'name' => '',
  771. 'type' => '',
  772. 'tmp_name' => '',
  773. 'error' => UPLOAD_ERR_FORM_SIZE,
  774. ]
  775. ];
  776. $expected = [
  777. 'photo' => [
  778. 'uploadedFile' => 'The provided value is invalid'
  779. ]
  780. ];
  781. $result = $validator->errors($data);
  782. $this->assertSame($expected, $result);
  783. $data = [
  784. 'photo' => '',
  785. ];
  786. $expected = [
  787. 'photo' => [
  788. 'uploadedFile' => 'The provided value is invalid'
  789. ]
  790. ];
  791. $result = $validator->errors($data);
  792. $this->assertSame($expected, $result);
  793. $data = ['photo' => []];
  794. $result = $validator->errors($data);
  795. $this->assertSame($expected, $result);
  796. $validator = new Validator();
  797. $validator->allowEmptyArray('photo', 'update', 'message');
  798. $this->assertFalse($validator->isEmptyAllowed('photo', true));
  799. $this->assertTrue($validator->isEmptyAllowed('photo', false));
  800. $data = [
  801. 'photo' => null,
  802. ];
  803. $expected = [
  804. 'photo' => ['_empty' => 'message'],
  805. ];
  806. $this->assertSame($expected, $validator->errors($data, true));
  807. $this->assertEmpty($validator->errors($data, false));
  808. }
  809. /**
  810. * Tests the allowEmptyDate method
  811. *
  812. * @return void
  813. */
  814. public function testAllowEmptyDate()
  815. {
  816. $validator = new Validator();
  817. $validator->allowEmptyDate('date')
  818. ->date('date');
  819. $this->assertTrue($validator->field('date')->isEmptyAllowed());
  820. $data = [
  821. 'date' => [
  822. 'year' => '',
  823. 'month' => '',
  824. 'day' => ''
  825. ],
  826. ];
  827. $result = $validator->errors($data);
  828. $this->assertEmpty($result);
  829. $data = [
  830. 'date' => '',
  831. ];
  832. $result = $validator->errors($data);
  833. $this->assertEmpty($result);
  834. $data = [
  835. 'date' => null,
  836. ];
  837. $result = $validator->errors($data);
  838. $this->assertEmpty($result);
  839. $data = ['date' => []];
  840. $result = $validator->errors($data);
  841. $this->assertEmpty($result);
  842. $validator = new Validator();
  843. $validator->allowEmptyArray('date', 'update', 'message');
  844. $this->assertFalse($validator->isEmptyAllowed('date', true));
  845. $this->assertTrue($validator->isEmptyAllowed('date', false));
  846. $data = [
  847. 'date' => null,
  848. ];
  849. $expected = [
  850. 'date' => ['_empty' => 'message'],
  851. ];
  852. $this->assertSame($expected, $validator->errors($data, true));
  853. $this->assertEmpty($validator->errors($data, false));
  854. }
  855. /**
  856. * Tests the allowEmptyTime method
  857. *
  858. * @return void
  859. */
  860. public function testAllowEmptyTime()
  861. {
  862. $validator = new Validator();
  863. $validator->allowEmptyTime('time')
  864. ->time('time');
  865. $this->assertTrue($validator->field('time')->isEmptyAllowed());
  866. $data = [
  867. 'time' => [
  868. 'hour' => '',
  869. 'minute' => '',
  870. 'second' => '',
  871. ],
  872. ];
  873. $result = $validator->errors($data);
  874. $this->assertEmpty($result);
  875. $data = [
  876. 'time' => '',
  877. ];
  878. $result = $validator->errors($data);
  879. $this->assertEmpty($result);
  880. $data = [
  881. 'time' => null,
  882. ];
  883. $result = $validator->errors($data);
  884. $this->assertEmpty($result);
  885. $data = ['time' => []];
  886. $result = $validator->errors($data);
  887. $this->assertEmpty($result);
  888. $validator = new Validator();
  889. $validator->allowEmptyArray('time', 'update', 'message');
  890. $this->assertFalse($validator->isEmptyAllowed('time', true));
  891. $this->assertTrue($validator->isEmptyAllowed('time', false));
  892. $data = [
  893. 'time' => null,
  894. ];
  895. $expected = [
  896. 'time' => ['_empty' => 'message'],
  897. ];
  898. $this->assertSame($expected, $validator->errors($data, true));
  899. $this->assertEmpty($validator->errors($data, false));
  900. }
  901. /**
  902. * Tests the allowEmptyDate method
  903. *
  904. * @return void
  905. */
  906. public function testAllowEmptyDateTime()
  907. {
  908. $validator = new Validator();
  909. $validator->allowEmptyDate('published')
  910. ->dateTime('published');
  911. $this->assertTrue($validator->field('published')->isEmptyAllowed());
  912. $data = [
  913. 'published' => [
  914. 'year' => '',
  915. 'month' => '',
  916. 'day' => '',
  917. 'hour' => '',
  918. 'minute' => '',
  919. 'second' => '',
  920. ],
  921. ];
  922. $result = $validator->errors($data);
  923. $this->assertEmpty($result);
  924. $data = [
  925. 'published' => '',
  926. ];
  927. $result = $validator->errors($data);
  928. $this->assertEmpty($result);
  929. $data = [
  930. 'published' => null,
  931. ];
  932. $result = $validator->errors($data);
  933. $this->assertEmpty($result);
  934. $data = [
  935. 'published' => [],
  936. ];
  937. $result = $validator->errors($data);
  938. $this->assertEmpty($result);
  939. $validator = new Validator();
  940. $validator->allowEmptyArray('published', 'update', 'message');
  941. $this->assertFalse($validator->isEmptyAllowed('published', true));
  942. $this->assertTrue($validator->isEmptyAllowed('published', false));
  943. $data = [
  944. 'published' => null,
  945. ];
  946. $expected = [
  947. 'published' => ['_empty' => 'message'],
  948. ];
  949. $this->assertSame($expected, $validator->errors($data, true));
  950. $this->assertEmpty($validator->errors($data, false));
  951. }
  952. /**
  953. * Test the notEmpty() method.
  954. *
  955. * @return void
  956. */
  957. public function testNotEmpty()
  958. {
  959. $validator = new Validator();
  960. $validator->notEmpty('title');
  961. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  962. $validator->allowEmpty('title');
  963. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  964. }
  965. /**
  966. * Tests the notEmpty as array method
  967. *
  968. * @return void
  969. */
  970. public function testNotEmptyAsArray()
  971. {
  972. $validator = new Validator();
  973. $validator->notEmpty(['title', 'created']);
  974. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  975. $this->assertFalse($validator->field('created')->isEmptyAllowed());
  976. $validator->notEmpty([
  977. 'title' => [
  978. 'when' => false
  979. ],
  980. 'content' => [
  981. 'when' => 'update'
  982. ],
  983. 'posted_at' => [
  984. 'when' => 'create'
  985. ],
  986. 'show_at' => [
  987. 'message' => 'Show date cannot be empty',
  988. 'when' => false
  989. ],
  990. 'subject'
  991. ], 'Not empty', true);
  992. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  993. $this->assertTrue($validator->isEmptyAllowed('content', true));
  994. $this->assertFalse($validator->isEmptyAllowed('content', false));
  995. $this->assertFalse($validator->isEmptyAllowed('posted_at', true));
  996. $this->assertTrue($validator->isEmptyAllowed('posted_at', false));
  997. $this->assertTrue($validator->field('subject')->isEmptyAllowed());
  998. $errors = $validator->errors([
  999. 'title' => '',
  1000. 'content' => '',
  1001. 'posted_at' => null,
  1002. 'show_at' => null,
  1003. 'subject' => ''
  1004. ], false);
  1005. $expected = [
  1006. 'title' => ['_empty' => 'Not empty'],
  1007. 'content' => ['_empty' => 'Not empty'],
  1008. 'show_at' => ['_empty' => 'Show date cannot be empty']
  1009. ];
  1010. $this->assertEquals($expected, $errors);
  1011. }
  1012. /**
  1013. * Tests the notEmpty failure case
  1014. *
  1015. * @return void
  1016. */
  1017. public function testNotEmptyAsArrayFailure()
  1018. {
  1019. $this->expectException(\InvalidArgumentException::class);
  1020. $validator = new Validator();
  1021. $validator->notEmpty(['title' => 'derp', 'created' => false]);
  1022. }
  1023. /**
  1024. * Test the notEmpty() method.
  1025. *
  1026. * @return void
  1027. */
  1028. public function testNotEmptyModes()
  1029. {
  1030. $validator = new Validator();
  1031. $validator->notEmpty('title', 'Need a title', 'create');
  1032. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1033. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1034. $validator->notEmpty('title', 'Need a title', 'update');
  1035. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1036. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1037. $validator->notEmpty('title', 'Need a title');
  1038. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1039. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1040. $validator->notEmpty('title');
  1041. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1042. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1043. }
  1044. /**
  1045. * Test interactions between notEmpty() and isAllowed().
  1046. *
  1047. * @return void
  1048. */
  1049. public function testNotEmptyAndIsAllowed()
  1050. {
  1051. $validator = new Validator();
  1052. $validator->allowEmpty('title')
  1053. ->notEmpty('title', 'Need it', 'update');
  1054. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1055. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1056. $validator->allowEmpty('title')
  1057. ->notEmpty('title');
  1058. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1059. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1060. $validator->notEmpty('title')
  1061. ->allowEmpty('title', 'create');
  1062. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1063. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1064. }
  1065. /**
  1066. * Tests the allowEmpty method when passing a callback
  1067. *
  1068. * @return void
  1069. */
  1070. public function testAllowEmptyCallback()
  1071. {
  1072. $validator = new Validator();
  1073. $allow = true;
  1074. $validator->allowEmpty('title', function ($context) use (&$allow) {
  1075. $this->assertEquals([], $context['data']);
  1076. $this->assertEquals([], $context['providers']);
  1077. $this->assertTrue($context['newRecord']);
  1078. return $allow;
  1079. });
  1080. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1081. $allow = false;
  1082. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1083. }
  1084. /**
  1085. * Tests the notEmpty method when passing a callback
  1086. *
  1087. * @return void
  1088. */
  1089. public function testNotEmptyCallback()
  1090. {
  1091. $validator = new Validator();
  1092. $prevent = true;
  1093. $validator->notEmpty('title', 'error message', function ($context) use (&$prevent) {
  1094. $this->assertEquals([], $context['data']);
  1095. $this->assertEquals([], $context['providers']);
  1096. $this->assertFalse($context['newRecord']);
  1097. return $prevent;
  1098. });
  1099. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1100. $prevent = false;
  1101. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1102. }
  1103. /**
  1104. * Tests the isEmptyAllowed method
  1105. *
  1106. * @return void
  1107. */
  1108. public function testIsEmptyAllowed()
  1109. {
  1110. $validator = new Validator();
  1111. $this->assertSame($validator, $validator->allowEmpty('title'));
  1112. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1113. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1114. $validator->notEmpty('title');
  1115. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1116. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1117. $validator->allowEmpty('title', 'create');
  1118. $this->assertTrue($validator->isEmptyAllowed('title', true));
  1119. $this->assertFalse($validator->isEmptyAllowed('title', false));
  1120. $validator->allowEmpty('title', 'update');
  1121. $this->assertTrue($validator->isEmptyAllowed('title', false));
  1122. $this->assertFalse($validator->isEmptyAllowed('title', true));
  1123. }
  1124. /**
  1125. * Tests errors generated when a field is not allowed to be empty
  1126. *
  1127. * @return void
  1128. */
  1129. public function testErrorsWithEmptyNotAllowed()
  1130. {
  1131. $validator = new Validator();
  1132. $validator->notEmpty('title');
  1133. $errors = $validator->errors(['title' => '']);
  1134. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1135. $this->assertEquals($expected, $errors);
  1136. $errors = $validator->errors(['title' => []]);
  1137. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1138. $this->assertEquals($expected, $errors);
  1139. $errors = $validator->errors(['title' => null]);
  1140. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  1141. $this->assertEquals($expected, $errors);
  1142. $errors = $validator->errors(['title' => 0]);
  1143. $this->assertEmpty($errors);
  1144. $errors = $validator->errors(['title' => '0']);
  1145. $this->assertEmpty($errors);
  1146. $errors = $validator->errors(['title' => false]);
  1147. $this->assertEmpty($errors);
  1148. }
  1149. /**
  1150. * Tests custom error messages generated when a field is allowed to be empty
  1151. *
  1152. * @return void
  1153. */
  1154. public function testCustomErrorsWithAllowedEmpty()
  1155. {
  1156. $validator = new Validator();
  1157. $validator->allowEmpty('title', false, 'Custom message');
  1158. $errors = $validator->errors(['title' => null]);
  1159. $expected = ['title' => ['_empty' => 'Custom message']];
  1160. $this->assertEquals($expected, $errors);
  1161. }
  1162. /**
  1163. * Tests custom error messages generated when a field is not allowed to be empty
  1164. *
  1165. * @return void
  1166. */
  1167. public function testCustomErrorsWithEmptyNotAllowed()
  1168. {
  1169. $validator = new Validator();
  1170. $validator->notEmpty('title', 'Custom message');
  1171. $errors = $validator->errors(['title' => '']);
  1172. $expected = ['title' => ['_empty' => 'Custom message']];
  1173. $this->assertEquals($expected, $errors);
  1174. }
  1175. /**
  1176. * Tests errors generated when a field is allowed to be empty
  1177. *
  1178. * @return void
  1179. */
  1180. public function testErrorsWithEmptyAllowed()
  1181. {
  1182. $validator = new Validator();
  1183. $validator->allowEmpty('title');
  1184. $errors = $validator->errors(['title' => '']);
  1185. $this->assertEmpty($errors);
  1186. $errors = $validator->errors(['title' => []]);
  1187. $this->assertEmpty($errors);
  1188. $errors = $validator->errors(['title' => null]);
  1189. $this->assertEmpty($errors);
  1190. $errors = $validator->errors(['title' => 0]);
  1191. $this->assertEmpty($errors);
  1192. $errors = $validator->errors(['title' => 0.0]);
  1193. $this->assertEmpty($errors);
  1194. $errors = $validator->errors(['title' => '0']);
  1195. $this->assertEmpty($errors);
  1196. $errors = $validator->errors(['title' => false]);
  1197. $this->assertEmpty($errors);
  1198. }
  1199. /**
  1200. * Test the provider() method
  1201. *
  1202. * @return void
  1203. */
  1204. public function testProvider()
  1205. {
  1206. $validator = new Validator();
  1207. $object = new \stdClass;
  1208. $this->assertSame($validator, $validator->setProvider('foo', $object));
  1209. $this->assertSame($object, $validator->getProvider('foo'));
  1210. $this->assertNull($validator->getProvider('bar'));
  1211. $another = new \stdClass;
  1212. $this->assertSame($validator, $validator->setProvider('bar', $another));
  1213. $this->assertSame($another, $validator->getProvider('bar'));
  1214. $this->assertEquals(new \Cake\Validation\RulesProvider, $validator->getProvider('default'));
  1215. }
  1216. /**
  1217. * Tests errors() method when using validators from the default provider, this proves
  1218. * that it returns a default validation message and the custom one set in the rule
  1219. *
  1220. * @return void
  1221. */
  1222. public function testErrorsFromDefaultProvider()
  1223. {
  1224. $validator = new Validator();
  1225. $validator
  1226. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1227. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  1228. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1229. $errors = $validator->errors(['email' => 'not an email!']);
  1230. $expected = [
  1231. 'email' => [
  1232. 'alpha' => 'The provided value is invalid',
  1233. 'email' => 'Y u no write email?'
  1234. ]
  1235. ];
  1236. $this->assertEquals($expected, $errors);
  1237. }
  1238. /**
  1239. * Tests using validation methods from different providers and returning the error
  1240. * as a string
  1241. *
  1242. * @return void
  1243. */
  1244. public function testErrorsFromCustomProvider()
  1245. {
  1246. $validator = new Validator();
  1247. $validator
  1248. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1249. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1250. $thing = $this->getMockBuilder('\stdClass')
  1251. ->setMethods(['isCool'])
  1252. ->getMock();
  1253. $thing->expects($this->once())->method('isCool')
  1254. ->will($this->returnCallback(function ($data, $context) use ($thing) {
  1255. $this->assertEquals('bar', $data);
  1256. $expected = [
  1257. 'default' => new \Cake\Validation\RulesProvider,
  1258. 'thing' => $thing
  1259. ];
  1260. $expected = [
  1261. 'newRecord' => true,
  1262. 'providers' => $expected,
  1263. 'data' => [
  1264. 'email' => '!',
  1265. 'title' => 'bar'
  1266. ],
  1267. 'field' => 'title'
  1268. ];
  1269. $this->assertEquals($expected, $context);
  1270. return "That ain't cool, yo";
  1271. }));
  1272. $validator->setProvider('thing', $thing);
  1273. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  1274. $expected = [
  1275. 'email' => ['alpha' => 'The provided value is invalid'],
  1276. 'title' => ['cool' => "That ain't cool, yo"]
  1277. ];
  1278. $this->assertEquals($expected, $errors);
  1279. }
  1280. /**
  1281. * Tests that it is possible to pass extra arguments to the validation function
  1282. * and it still gets the providers as last argument
  1283. *
  1284. * @return void
  1285. */
  1286. public function testMethodsWithExtraArguments()
  1287. {
  1288. $validator = new Validator();
  1289. $validator->add('title', 'cool', [
  1290. 'rule' => ['isCool', 'and', 'awesome'],
  1291. 'provider' => 'thing'
  1292. ]);
  1293. $thing = $this->getMockBuilder('\stdClass')
  1294. ->setMethods(['isCool'])
  1295. ->getMock();
  1296. $thing->expects($this->once())->method('isCool')
  1297. ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
  1298. $this->assertEquals('bar', $data);
  1299. $this->assertEquals('and', $a);
  1300. $this->assertEquals('awesome', $b);
  1301. $expected = [
  1302. 'default' => new \Cake\Validation\RulesProvider,
  1303. 'thing' => $thing
  1304. ];
  1305. $expected = [
  1306. 'newRecord' => true,
  1307. 'providers' => $expected,
  1308. 'data' => [
  1309. 'email' => '!',
  1310. 'title' => 'bar'
  1311. ],
  1312. 'field' => 'title'
  1313. ];
  1314. $this->assertEquals($expected, $context);
  1315. return "That ain't cool, yo";
  1316. }));
  1317. $validator->setProvider('thing', $thing);
  1318. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  1319. $expected = [
  1320. 'title' => ['cool' => "That ain't cool, yo"]
  1321. ];
  1322. $this->assertEquals($expected, $errors);
  1323. }
  1324. /**
  1325. * Tests that it is possible to use a closure as a rule
  1326. *
  1327. * @return void
  1328. */
  1329. public function testUsingClosureAsRule()
  1330. {
  1331. $validator = new Validator();
  1332. $validator->add('name', 'myRule', [
  1333. 'rule' => function ($data, $provider) {
  1334. $this->assertEquals('foo', $data);
  1335. return 'You fail';
  1336. }
  1337. ]);
  1338. $expected = ['name' => ['myRule' => 'You fail']];
  1339. $this->assertEquals($expected, $validator->errors(['name' => 'foo']));
  1340. }
  1341. /**
  1342. * Tests that setting last to a rule will stop validating the rest of the rules
  1343. *
  1344. * @return void
  1345. */
  1346. public function testErrorsWithLastRule()
  1347. {
  1348. $validator = new Validator();
  1349. $validator
  1350. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  1351. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  1352. $errors = $validator->errors(['email' => 'not an email!']);
  1353. $expected = [
  1354. 'email' => [
  1355. 'alpha' => 'The provided value is invalid'
  1356. ]
  1357. ];
  1358. $this->assertEquals($expected, $errors);
  1359. }
  1360. /**
  1361. * Tests it is possible to get validation sets for a field using an array interface
  1362. *
  1363. * @return void
  1364. */
  1365. public function testArrayAccessGet()
  1366. {
  1367. $validator = new Validator();
  1368. $validator
  1369. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1370. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1371. $this->assertSame($validator['email'], $validator->field('email'));
  1372. $this->assertSame($validator['title'], $validator->field('title'));
  1373. }
  1374. /**
  1375. * Tests it is possible to check for validation sets for a field using an array interface
  1376. *
  1377. * @return void
  1378. */
  1379. public function testArrayAccessExists()
  1380. {
  1381. $validator = new Validator();
  1382. $validator
  1383. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1384. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1385. $this->assertArrayHasKey('email', $validator);
  1386. $this->assertArrayHasKey('title', $validator);
  1387. $this->assertArrayNotHasKey('foo', $validator);
  1388. }
  1389. /**
  1390. * Tests it is possible to set validation rules for a field using an array interface
  1391. *
  1392. * @return void
  1393. */
  1394. public function testArrayAccessSet()
  1395. {
  1396. $validator = new Validator();
  1397. $validator
  1398. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1399. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1400. $validator['name'] = $validator->field('title');
  1401. $this->assertSame($validator->field('title'), $validator->field('name'));
  1402. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  1403. $this->assertEquals($validator->field('email'), $validator->field('email'));
  1404. }
  1405. /**
  1406. * Tests it is possible to unset validation rules
  1407. *
  1408. * @return void
  1409. */
  1410. public function testArrayAccessUnset()
  1411. {
  1412. $validator = new Validator();
  1413. $validator
  1414. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1415. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1416. $this->assertArrayHasKey('title', $validator);
  1417. unset($validator['title']);
  1418. $this->assertArrayNotHasKey('title', $validator);
  1419. }
  1420. /**
  1421. * Tests the countable interface
  1422. *
  1423. * @return void
  1424. */
  1425. public function testCount()
  1426. {
  1427. $validator = new Validator();
  1428. $validator
  1429. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1430. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1431. $this->assertCount(2, $validator);
  1432. }
  1433. /**
  1434. * Tests adding rules via alternative syntax
  1435. *
  1436. * @return void
  1437. */
  1438. public function testAddMultiple()
  1439. {
  1440. $validator = new Validator();
  1441. $validator->add('title', [
  1442. 'notBlank' => [
  1443. 'rule' => 'notBlank'
  1444. ],
  1445. 'length' => [
  1446. 'rule' => ['minLength', 10],
  1447. 'message' => 'Titles need to be at least 10 characters long'
  1448. ]
  1449. ]);
  1450. $set = $validator->field('title');
  1451. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  1452. $this->assertCount(2, $set);
  1453. }
  1454. /**
  1455. * Integration test for compareWith validator.
  1456. *
  1457. * @return void
  1458. */
  1459. public function testCompareWithIntegration()
  1460. {
  1461. $validator = new Validator();
  1462. $validator->add('password', [
  1463. 'compare' => [
  1464. 'rule' => ['compareWith', 'password_compare']
  1465. ],
  1466. ]);
  1467. $data = [
  1468. 'password' => 'test',
  1469. 'password_compare' => 'not the same'
  1470. ];
  1471. $this->assertNotEmpty($validator->errors($data), 'Validation should fail.');
  1472. }
  1473. /**
  1474. * Test debugInfo helper method.
  1475. *
  1476. * @return void
  1477. */
  1478. public function testDebugInfo()
  1479. {
  1480. $validator = new Validator();
  1481. $validator->setProvider('test', $this);
  1482. $validator->add('title', 'not-empty', ['rule' => 'notBlank']);
  1483. $validator->requirePresence('body');
  1484. $validator->allowEmpty('published');
  1485. $result = $validator->__debugInfo();
  1486. $expected = [
  1487. '_providers' => ['test'],
  1488. '_fields' => [
  1489. 'title' => [
  1490. 'isPresenceRequired' => false,
  1491. 'isEmptyAllowed' => false,
  1492. 'rules' => ['not-empty'],
  1493. ],
  1494. 'body' => [
  1495. 'isPresenceRequired' => true,
  1496. 'isEmptyAllowed' => false,
  1497. 'rules' => [],
  1498. ],
  1499. 'published' => [
  1500. 'isPresenceRequired' => false,
  1501. 'isEmptyAllowed' => true,
  1502. 'rules' => [],
  1503. ],
  1504. ],
  1505. '_presenceMessages' => [],
  1506. '_allowEmptyMessages' => [],
  1507. '_allowEmptyFlags' => [],
  1508. '_useI18n' => true,
  1509. ];
  1510. $this->assertEquals($expected, $result);
  1511. }
  1512. /**
  1513. * Tests that the 'create' and 'update' modes are preserved when using
  1514. * nested validators
  1515. *
  1516. * @return void
  1517. */
  1518. public function testNestedValidatorCreate()
  1519. {
  1520. $validator = new Validator();
  1521. $inner = new Validator();
  1522. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1523. $validator->addNested('user', $inner);
  1524. $this->assertNotEmpty($validator->errors(['user' => ['username' => 'example']], true));
  1525. $this->assertEmpty($validator->errors(['user' => ['username' => 'a']], false));
  1526. }
  1527. /**
  1528. * Tests that the 'create' and 'update' modes are preserved when using
  1529. * nested validators
  1530. *
  1531. * @return void
  1532. */
  1533. public function testNestedManyValidatorCreate()
  1534. {
  1535. $validator = new Validator();
  1536. $inner = new Validator();
  1537. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1538. $validator->addNestedMany('user', $inner);
  1539. $this->assertNotEmpty($validator->errors(['user' => [['username' => 'example']]], true));
  1540. $this->assertEmpty($validator->errors(['user' => [['username' => 'a']]], false));
  1541. }
  1542. /**
  1543. * Tests the notBlank proxy method
  1544. *
  1545. * @return void
  1546. */
  1547. public function testNotBlank()
  1548. {
  1549. $validator = new Validator();
  1550. $this->assertProxyMethod($validator, 'notBlank');
  1551. $this->assertNotEmpty($validator->errors(['username' => ' ']));
  1552. }
  1553. /**
  1554. * Tests the alphanumeric proxy method
  1555. *
  1556. * @return void
  1557. */
  1558. public function testAlphanumeric()
  1559. {
  1560. $validator = new Validator();
  1561. $this->assertProxyMethod($validator, 'alphaNumeric');
  1562. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1563. }
  1564. /**
  1565. * Tests the lengthBetween proxy method
  1566. *
  1567. * @return void
  1568. */
  1569. public function testLengthBetween()
  1570. {
  1571. $validator = new Validator();
  1572. $this->assertProxyMethod($validator, 'lengthBetween', [5, 7], [5, 7]);
  1573. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1574. }
  1575. /**
  1576. * Tests the lengthBetween proxy method
  1577. *
  1578. * @return void
  1579. */
  1580. public function testLengthBetweenFailure()
  1581. {
  1582. $this->expectException(\InvalidArgumentException::class);
  1583. $validator = new Validator();
  1584. $validator->lengthBetween('username', [7]);
  1585. }
  1586. /**
  1587. * Tests the creditCard proxy method
  1588. *
  1589. * @return void
  1590. */
  1591. public function testCreditCard()
  1592. {
  1593. $validator = new Validator();
  1594. $this->assertProxyMethod($validator, 'creditCard', 'all', ['all', true], 'creditCard');
  1595. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1596. }
  1597. /**
  1598. * Tests the greaterThan proxy method
  1599. *
  1600. * @return void
  1601. */
  1602. public function testGreaterThan()
  1603. {
  1604. $validator = new Validator();
  1605. $this->assertProxyMethod($validator, 'greaterThan', 5, [Validation::COMPARE_GREATER, 5], 'comparison');
  1606. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1607. }
  1608. /**
  1609. * Tests the greaterThanOrEqual proxy method
  1610. *
  1611. * @return void
  1612. */
  1613. public function testGreaterThanOrEqual()
  1614. {
  1615. $validator = new Validator();
  1616. $this->assertProxyMethod($validator, 'greaterThanOrEqual', 5, [Validation::COMPARE_GREATER_OR_EQUAL, 5], 'comparison');
  1617. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1618. }
  1619. /**
  1620. * Tests the lessThan proxy method
  1621. *
  1622. * @return void
  1623. */
  1624. public function testLessThan()
  1625. {
  1626. $validator = new Validator();
  1627. $this->assertProxyMethod($validator, 'lessThan', 5, [Validation::COMPARE_LESS, 5], 'comparison');
  1628. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1629. }
  1630. /**
  1631. * Tests the lessThanOrEqual proxy method
  1632. *
  1633. * @return void
  1634. */
  1635. public function testLessThanOrEqual()
  1636. {
  1637. $validator = new Validator();
  1638. $this->assertProxyMethod($validator, 'lessThanOrEqual', 5, [Validation::COMPARE_LESS_OR_EQUAL, 5], 'comparison');
  1639. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1640. }
  1641. /**
  1642. * Tests the equals proxy method
  1643. *
  1644. * @return void
  1645. */
  1646. public function testEquals()
  1647. {
  1648. $validator = new Validator();
  1649. $this->assertProxyMethod($validator, 'equals', 5, [Validation::COMPARE_EQUAL, 5], 'comparison');
  1650. $this->assertEmpty($validator->errors(['username' => 5]));
  1651. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1652. }
  1653. /**
  1654. * Tests the notEquals proxy method
  1655. *
  1656. * @return void
  1657. */
  1658. public function testNotEquals()
  1659. {
  1660. $validator = new Validator();
  1661. $this->assertProxyMethod($validator, 'notEquals', 5, [Validation::COMPARE_NOT_EQUAL, 5], 'comparison');
  1662. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1663. }
  1664. /**
  1665. * Tests the sameAs proxy method
  1666. *
  1667. * @return void
  1668. */
  1669. public function testSameAs()
  1670. {
  1671. $validator = new Validator();
  1672. $this->assertProxyMethod($validator, 'sameAs', 'other', ['other', Validation::COMPARE_SAME], 'compareFields');
  1673. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1674. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => '1']));
  1675. }
  1676. /**
  1677. * Tests the notSameAs proxy method
  1678. *
  1679. * @return void
  1680. */
  1681. public function testNotSameAs()
  1682. {
  1683. $validator = new Validator();
  1684. $this->assertProxyMethod($validator, 'notSameAs', 'other', ['other', Validation::COMPARE_NOT_SAME], 'compareFields');
  1685. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'foo']));
  1686. }
  1687. /**
  1688. * Tests the equalToField proxy method
  1689. *
  1690. * @return void
  1691. */
  1692. public function testEqualToField()
  1693. {
  1694. $validator = new Validator();
  1695. $this->assertProxyMethod($validator, 'equalToField', 'other', ['other', Validation::COMPARE_EQUAL], 'compareFields');
  1696. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1697. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'bar']));
  1698. }
  1699. /**
  1700. * Tests the notEqualToField proxy method
  1701. *
  1702. * @return void
  1703. */
  1704. public function testNotEqualToField()
  1705. {
  1706. $validator = new Validator();
  1707. $this->assertProxyMethod($validator, 'notEqualToField', 'other', ['other', Validation::COMPARE_NOT_EQUAL], 'compareFields');
  1708. $this->assertNotEmpty($validator->errors(['username' => 'foo', 'other' => 'foo']));
  1709. }
  1710. /**
  1711. * Tests the greaterThanField proxy method
  1712. *
  1713. * @return void
  1714. */
  1715. public function testGreaterThanField()
  1716. {
  1717. $validator = new Validator();
  1718. $this->assertProxyMethod($validator, 'greaterThanField', 'other', ['other', Validation::COMPARE_GREATER], 'compareFields');
  1719. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 1]));
  1720. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 2]));
  1721. }
  1722. /**
  1723. * Tests the greaterThanOrEqualToField proxy method
  1724. *
  1725. * @return void
  1726. */
  1727. public function testGreaterThanOrEqualToField()
  1728. {
  1729. $validator = new Validator();
  1730. $this->assertProxyMethod($validator, 'greaterThanOrEqualToField', 'other', ['other', Validation::COMPARE_GREATER_OR_EQUAL], 'compareFields');
  1731. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 2]));
  1732. }
  1733. /**
  1734. * Tests the lessThanField proxy method
  1735. *
  1736. * @return void
  1737. */
  1738. public function testLessThanField()
  1739. {
  1740. $validator = new Validator();
  1741. $this->assertProxyMethod($validator, 'lessThanField', 'other', ['other', Validation::COMPARE_LESS], 'compareFields');
  1742. $this->assertNotEmpty($validator->errors(['username' => 1, 'other' => 1]));
  1743. $this->assertNotEmpty($validator->errors(['username' => 2, 'other' => 1]));
  1744. }
  1745. /**
  1746. * Tests the lessThanOrEqualToField proxy method
  1747. *
  1748. * @return void
  1749. */
  1750. public function testLessThanOrEqualToField()
  1751. {
  1752. $validator = new Validator();
  1753. $this->assertProxyMethod($validator, 'lessThanOrEqualToField', 'other', ['other', Validation::COMPARE_LESS_OR_EQUAL], 'compareFields');
  1754. $this->assertNotEmpty($validator->errors(['username' => 2, 'other' => 1]));
  1755. }
  1756. /**
  1757. * Tests the containsNonAlphaNumeric proxy method
  1758. *
  1759. * @return void
  1760. */
  1761. public function testContainsNonAlphaNumeric()
  1762. {
  1763. $validator = new Validator();
  1764. $this->assertProxyMethod($validator, 'containsNonAlphaNumeric', 2, [2]);
  1765. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1766. }
  1767. /**
  1768. * Tests the date proxy method
  1769. *
  1770. * @return void
  1771. */
  1772. public function testDate()
  1773. {
  1774. $validator = new Validator();
  1775. $this->assertProxyMethod($validator, 'date', ['ymd'], [['ymd']]);
  1776. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1777. }
  1778. /**
  1779. * Tests the dateTime proxy method
  1780. *
  1781. * @return void
  1782. */
  1783. public function testDateTime()
  1784. {
  1785. $validator = new Validator();
  1786. $this->assertProxyMethod($validator, 'dateTime', ['ymd'], [['ymd']], 'datetime');
  1787. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1788. }
  1789. /**
  1790. * Tests the time proxy method
  1791. *
  1792. * @return void
  1793. */
  1794. public function testTime()
  1795. {
  1796. $validator = new Validator();
  1797. $this->assertProxyMethod($validator, 'time');
  1798. $this->assertNotEmpty($validator->errors(['username' => 'not a time']));
  1799. }
  1800. /**
  1801. * Tests the localizedTime proxy method
  1802. *
  1803. * @return void
  1804. */
  1805. public function testLocalizedTime()
  1806. {
  1807. $validator = new Validator();
  1808. $this->assertProxyMethod($validator, 'localizedTime', 'date', ['date']);
  1809. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1810. }
  1811. /**
  1812. * Tests the boolean proxy method
  1813. *
  1814. * @return void
  1815. */
  1816. public function testBoolean()
  1817. {
  1818. $validator = new Validator();
  1819. $this->assertProxyMethod($validator, 'boolean');
  1820. $this->assertNotEmpty($validator->errors(['username' => 'not a boolean']));
  1821. }
  1822. /**
  1823. * Tests the decimal proxy method
  1824. *
  1825. * @return void
  1826. */
  1827. public function testDecimal()
  1828. {
  1829. $validator = new Validator();
  1830. $this->assertProxyMethod($validator, 'decimal', 2, [2]);
  1831. $this->assertNotEmpty($validator->errors(['username' => 10.1]));
  1832. }
  1833. /**
  1834. * Tests the ip proxy methods
  1835. *
  1836. * @return void
  1837. */
  1838. public function testIps()
  1839. {
  1840. $validator = new Validator();
  1841. $this->assertProxyMethod($validator, 'ip');
  1842. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1843. $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip');
  1844. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1845. $this->assertProxyMethod($validator, 'ipv6', null, ['ipv6'], 'ip');
  1846. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1847. }
  1848. /**
  1849. * Tests the minLength proxy method
  1850. *
  1851. * @return void
  1852. */
  1853. public function testMinLength()
  1854. {
  1855. $validator = new Validator();
  1856. $this->assertProxyMethod($validator, 'minLength', 2, [2]);
  1857. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1858. }
  1859. /**
  1860. * Tests the minLengthBytes proxy method
  1861. *
  1862. * @return void
  1863. */
  1864. public function testMinLengthBytes()
  1865. {
  1866. $validator = new Validator();
  1867. $this->assertProxyMethod($validator, 'minLengthBytes', 11, [11]);
  1868. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  1869. }
  1870. /**
  1871. * Tests the maxLength proxy method
  1872. *
  1873. * @return void
  1874. */
  1875. public function testMaxLength()
  1876. {
  1877. $validator = new Validator();
  1878. $this->assertProxyMethod($validator, 'maxLength', 2, [2]);
  1879. $this->assertNotEmpty($validator->errors(['username' => 'aaa']));
  1880. }
  1881. /**
  1882. * Tests the maxLengthBytes proxy method
  1883. *
  1884. * @return void
  1885. */
  1886. public function testMaxLengthBytes()
  1887. {
  1888. $validator = new Validator();
  1889. $this->assertProxyMethod($validator, 'maxLengthBytes', 9, [9]);
  1890. $this->assertNotEmpty($validator->errors(['username' => 'ÆΔΩЖÇ']));
  1891. }
  1892. /**
  1893. * Tests the numeric proxy method
  1894. *
  1895. * @return void
  1896. */
  1897. public function testNumeric()
  1898. {
  1899. $validator = new Validator();
  1900. $this->assertProxyMethod($validator, 'numeric');
  1901. $this->assertEmpty($validator->errors(['username' => '22']));
  1902. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1903. }
  1904. /**
  1905. * Tests the naturalNumber proxy method
  1906. *
  1907. * @return void
  1908. */
  1909. public function testNaturalNumber()
  1910. {
  1911. $validator = new Validator();
  1912. $this->assertProxyMethod($validator, 'naturalNumber', null, [false]);
  1913. $this->assertNotEmpty($validator->errors(['username' => 0]));
  1914. }
  1915. /**
  1916. * Tests the nonNegativeInteger proxy method
  1917. *
  1918. * @return void
  1919. */
  1920. public function testNonNegativeInteger()
  1921. {
  1922. $validator = new Validator();
  1923. $this->assertProxyMethod($validator, 'nonNegativeInteger', null, [true], 'naturalNumber');
  1924. $this->assertNotEmpty($validator->errors(['username' => -1]));
  1925. }
  1926. /**
  1927. * Tests the range proxy method
  1928. *
  1929. * @return void
  1930. */
  1931. public function testRange()
  1932. {
  1933. $validator = new Validator();
  1934. $this->assertProxyMethod($validator, 'range', [1, 4], [1, 4]);
  1935. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1936. }
  1937. /**
  1938. * Tests the range failure case
  1939. *
  1940. * @return void
  1941. */
  1942. public function testRangeFailure()
  1943. {
  1944. $this->expectException(\InvalidArgumentException::class);
  1945. $validator = new Validator();
  1946. $validator->range('username', [1]);
  1947. }
  1948. /**
  1949. * Tests the url proxy method
  1950. *
  1951. * @return void
  1952. */
  1953. public function testUrl()
  1954. {
  1955. $validator = new Validator();
  1956. $this->assertProxyMethod($validator, 'url', null, [false]);
  1957. $this->assertNotEmpty($validator->errors(['username' => 'not url']));
  1958. }
  1959. /**
  1960. * Tests the urlWithProtocol proxy method
  1961. *
  1962. * @return void
  1963. */
  1964. public function testUrlWithProtocol()
  1965. {
  1966. $validator = new Validator();
  1967. $this->assertProxyMethod($validator, 'urlWithProtocol', null, [true], 'url');
  1968. $this->assertNotEmpty($validator->errors(['username' => 'google.com']));
  1969. }
  1970. /**
  1971. * Tests the inList proxy method
  1972. *
  1973. * @return void
  1974. */
  1975. public function testInList()
  1976. {
  1977. $validator = new Validator();
  1978. $this->assertProxyMethod($validator, 'inList', ['a', 'b'], [['a', 'b']]);
  1979. $this->assertNotEmpty($validator->errors(['username' => 'c']));
  1980. }
  1981. /**
  1982. * Tests the uuid proxy method
  1983. *
  1984. * @return void
  1985. */
  1986. public function testUuid()
  1987. {
  1988. $validator = new Validator();
  1989. $this->assertProxyMethod($validator, 'uuid');
  1990. $this->assertNotEmpty($validator->errors(['username' => 'not uuid']));
  1991. }
  1992. /**
  1993. * Tests the uploadedFile proxy method
  1994. *
  1995. * @return void
  1996. */
  1997. public function testUploadedFile()
  1998. {
  1999. $validator = new Validator();
  2000. $this->assertProxyMethod($validator, 'uploadedFile', ['foo' => 'bar'], [['foo' => 'bar']]);
  2001. $this->assertNotEmpty($validator->errors(['username' => []]));
  2002. }
  2003. /**
  2004. * Tests the latlog proxy methods
  2005. *
  2006. * @return void
  2007. */
  2008. public function testLatLong()
  2009. {
  2010. $validator = new Validator();
  2011. $this->assertProxyMethod($validator, 'latLong', null, [], 'geoCoordinate');
  2012. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2013. $this->assertProxyMethod($validator, 'latitude');
  2014. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2015. $this->assertProxyMethod($validator, 'longitude');
  2016. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  2017. }
  2018. /**
  2019. * Tests the ascii proxy method
  2020. *
  2021. * @return void
  2022. */
  2023. public function testAscii()
  2024. {
  2025. $validator = new Validator();
  2026. $this->assertProxyMethod($validator, 'ascii');
  2027. $this->assertNotEmpty($validator->errors(['username' => 'ü']));
  2028. }
  2029. /**
  2030. * Tests the utf8 proxy methods
  2031. *
  2032. * @return void
  2033. */
  2034. public function testUtf8()
  2035. {
  2036. // Grinning face
  2037. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2038. $validator = new Validator();
  2039. $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]);
  2040. $this->assertEmpty($validator->errors(['username' => 'ü']));
  2041. $this->assertNotEmpty($validator->errors(['username' => $extended]));
  2042. }
  2043. /**
  2044. * Test utf8extended proxy method.
  2045. *
  2046. * @return void
  2047. */
  2048. public function testUtf8Extended()
  2049. {
  2050. // Grinning face
  2051. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  2052. $validator = new Validator();
  2053. $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8');
  2054. $this->assertEmpty($validator->errors(['username' => 'ü']));
  2055. $this->assertEmpty($validator->errors(['username' => $extended]));
  2056. }
  2057. /**
  2058. * Tests the email proxy method
  2059. *
  2060. * @return void
  2061. */
  2062. public function testEmail()
  2063. {
  2064. $validator = new Validator();
  2065. $validator->email('username');
  2066. $this->assertEmpty($validator->errors(['username' => 'test@example.com']));
  2067. $this->assertNotEmpty($validator->errors(['username' => 'not an email']));
  2068. }
  2069. /**
  2070. * Tests the integer proxy method
  2071. *
  2072. * @return void
  2073. */
  2074. public function testInteger()
  2075. {
  2076. $validator = new Validator();
  2077. $this->assertProxyMethod($validator, 'integer', null, [], 'isInteger');
  2078. $this->assertNotEmpty($validator->errors(['username' => 'not integer']));
  2079. }
  2080. /**
  2081. * Tests the isArray proxy method
  2082. *
  2083. * @return void
  2084. */
  2085. public function testIsArray()
  2086. {
  2087. $validator = new Validator();
  2088. $validator->isArray('username');
  2089. $this->assertEmpty($validator->errors(['username' => [1, 2, 3]]));
  2090. $this->assertNotEmpty($validator->errors(['username' => 'is not an array']));
  2091. }
  2092. /**
  2093. * Tests the scalar proxy method
  2094. *
  2095. * @return void
  2096. */
  2097. public function testScalar()
  2098. {
  2099. $validator = new Validator();
  2100. $validator->scalar('username');
  2101. $this->assertEmpty($validator->errors(['username' => 'scalar']));
  2102. $this->assertNotEmpty($validator->errors(['username' => ['array']]));
  2103. }
  2104. /**
  2105. * Tests the hexColor proxy method
  2106. *
  2107. * @return void
  2108. */
  2109. public function testHexColor()
  2110. {
  2111. $validator = new Validator();
  2112. $this->assertProxyMethod($validator, 'hexColor');
  2113. $this->assertEmpty($validator->errors(['username' => '#FFFFFF']));
  2114. $this->assertNotEmpty($validator->errors(['username' => 'FFFFFF']));
  2115. }
  2116. /**
  2117. * Tests the multiple proxy method
  2118. *
  2119. * @return void
  2120. */
  2121. public function testMultiple()
  2122. {
  2123. $validator = new Validator();
  2124. $this->assertProxyMethod(
  2125. $validator,
  2126. 'multipleOptions',
  2127. ['min' => 1, 'caseInsensitive' => true],
  2128. [['min' => 1], true],
  2129. 'multiple'
  2130. );
  2131. $this->assertProxyMethod(
  2132. $validator,
  2133. 'multipleOptions',
  2134. ['min' => 1, 'caseInsensitive' => false],
  2135. [['min' => 1], false],
  2136. 'multiple'
  2137. );
  2138. $this->assertNotEmpty($validator->errors(['username' => '']));
  2139. }
  2140. /**
  2141. * Tests the hasAtLeast method
  2142. *
  2143. * @return void
  2144. */
  2145. public function testHasAtLeast()
  2146. {
  2147. $validator = new Validator();
  2148. $validator->hasAtLeast('things', 3);
  2149. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  2150. $this->assertEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  2151. $this->assertNotEmpty($validator->errors(['things' => [1, 2]]));
  2152. $this->assertNotEmpty($validator->errors(['things' => []]));
  2153. $this->assertNotEmpty($validator->errors(['things' => 'string']));
  2154. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  2155. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2156. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  2157. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => []]]));
  2158. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => 'string']]));
  2159. }
  2160. /**
  2161. * Tests the hasAtMost method
  2162. *
  2163. * @return void
  2164. */
  2165. public function testHasAtMost()
  2166. {
  2167. $validator = new Validator();
  2168. $validator->hasAtMost('things', 3);
  2169. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  2170. $this->assertEmpty($validator->errors(['things' => [1]]));
  2171. $this->assertNotEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  2172. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  2173. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  2174. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  2175. }
  2176. /**
  2177. * Tests the regex proxy method
  2178. *
  2179. * @return void
  2180. */
  2181. public function testRegex()
  2182. {
  2183. $validator = new Validator();
  2184. $this->assertProxyMethod($validator, 'regex', '/(?<!\\S)\\d++(?!\\S)/', ['/(?<!\\S)\\d++(?!\\S)/'], 'custom');
  2185. $this->assertEmpty($validator->errors(['username' => '123']));
  2186. $this->assertNotEmpty($validator->errors(['username' => 'Foo']));
  2187. }
  2188. /**
  2189. * Tests that a rule in the Validator class exists and was configured as expected.
  2190. *
  2191. * @param Validator $validator
  2192. * @param string $method
  2193. * @param mixed $extra
  2194. * @param array $pass
  2195. * @param string|null $name
  2196. */
  2197. protected function assertProxyMethod($validator, $method, $extra = null, $pass = [], $name = null)
  2198. {
  2199. $name = $name ?: $method;
  2200. if ($extra !== null) {
  2201. $this->assertSame($validator, $validator->{$method}('username', $extra));
  2202. } else {
  2203. $this->assertSame($validator, $validator->{$method}('username'));
  2204. }
  2205. $rule = $validator->field('username')->rule($method);
  2206. $this->assertNotEmpty($rule, "Rule was not found for $method");
  2207. $this->assertNull($rule->get('message'), 'Message is present when it should not be');
  2208. $this->assertNull($rule->get('on'), 'On clause is present when it should not be');
  2209. $this->assertEquals($name, $rule->get('rule'), 'Rule name does not match');
  2210. $this->assertEquals($pass, $rule->get('pass'), 'Passed options are different');
  2211. $this->assertEquals('default', $rule->get('provider'), 'Provider does not match');
  2212. if ($extra !== null) {
  2213. $validator->{$method}('username', $extra, 'the message', 'create');
  2214. } else {
  2215. $validator->{$method}('username', 'the message', 'create');
  2216. }
  2217. $rule = $validator->field('username')->rule($method);
  2218. $this->assertEquals('the message', $rule->get('message'), 'Error messages are not the same');
  2219. $this->assertEquals('create', $rule->get('on'), 'On clause is wrong');
  2220. }
  2221. /**
  2222. * Testing adding DefaultProvider
  2223. *
  2224. * @return void
  2225. */
  2226. public function testAddingDefaultProvider()
  2227. {
  2228. $validator = new Validator();
  2229. $this->assertEmpty($validator->providers(), 'Providers should be empty');
  2230. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2231. $validator = new Validator();
  2232. $this->assertEquals($validator->providers(), ['test-provider'], 'Default provider `test-provider` is missing');
  2233. }
  2234. /**
  2235. * Testing getting DefaultProvider(s)
  2236. *
  2237. * @return void
  2238. */
  2239. public function testGetDefaultProvider()
  2240. {
  2241. Validator::addDefaultProvider('test-provider', 'MyNameSpace\Validation\MyProvider');
  2242. $this->assertEquals(Validator::getDefaultProvider('test-provider'), 'MyNameSpace\Validation\MyProvider', 'Default provider `test-provider` is missing');
  2243. $this->assertNull(Validator::getDefaultProvider('invalid-provider'), 'Default provider (`invalid-provider`) should be missing');
  2244. $this->assertNull(Validator::getDefaultProvider(null), 'Default provider (null) should be missing');
  2245. Validator::addDefaultProvider('test-provider2', 'MyNameSpace\Validation\MySecondProvider');
  2246. $this->assertEquals(Validator::getDefaultProviders(), ['test-provider', 'test-provider2'], 'Default providers incorrect');
  2247. }
  2248. }