ValidatorTest.php 69 KB

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