ValidatorTest.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Validation;
  16. use Cake\TestSuite\TestCase;
  17. use Cake\Validation\ValidationSet;
  18. use Cake\Validation\Validator;
  19. /**
  20. * Tests Validator class
  21. */
  22. class ValidatorTest extends TestCase
  23. {
  24. /**
  25. * Testing you can dynamically add rules to a field
  26. *
  27. * @return void
  28. */
  29. public function testAddingRulesToField()
  30. {
  31. $validator = new Validator;
  32. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  33. $set = $validator->field('title');
  34. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  35. $this->assertCount(1, $set);
  36. $validator->add('title', 'another', ['rule' => 'alphanumeric']);
  37. $this->assertCount(2, $set);
  38. $validator->add('body', 'another', ['rule' => 'crazy']);
  39. $this->assertCount(1, $validator->field('body'));
  40. $this->assertCount(2, $validator);
  41. }
  42. /**
  43. * Testing addNested field rules
  44. *
  45. * @return void
  46. */
  47. public function testAddNestedSingle()
  48. {
  49. $validator = new Validator();
  50. $inner = new Validator();
  51. $inner->add('username', 'not-blank', ['rule' => 'notBlank']);
  52. $this->assertSame($validator, $validator->addNested('user', $inner));
  53. $this->assertCount(1, $validator->field('user'));
  54. }
  55. /**
  56. * Testing addNested connects providers
  57. *
  58. * @return void
  59. */
  60. public function testAddNestedSingleProviders()
  61. {
  62. $validator = new Validator();
  63. $validator->provider('test', $this);
  64. $inner = new Validator();
  65. $inner->add('username', 'not-blank', ['rule' => function () use ($inner, $validator) {
  66. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  67. return false;
  68. }]);
  69. $validator->addNested('user', $inner);
  70. $result = $validator->errors(['user' => ['username' => 'example']]);
  71. $this->assertNotEmpty($result, 'Validation should fail');
  72. }
  73. /**
  74. * Testing addNestedMany field rules
  75. *
  76. * @return void
  77. */
  78. public function testAddNestedMany()
  79. {
  80. $validator = new Validator();
  81. $inner = new Validator();
  82. $inner->add('comment', 'not-blank', ['rule' => 'notBlank']);
  83. $this->assertSame($validator, $validator->addNestedMany('comments', $inner));
  84. $this->assertCount(1, $validator->field('comments'));
  85. }
  86. /**
  87. * Testing addNestedMany connects providers
  88. *
  89. * @return void
  90. */
  91. public function testAddNestedManyProviders()
  92. {
  93. $validator = new Validator();
  94. $validator->provider('test', $this);
  95. $inner = new Validator();
  96. $inner->add('comment', 'not-blank', ['rule' => function () use ($inner, $validator) {
  97. $this->assertSame($validator->providers(), $inner->providers(), 'Providers should match');
  98. return false;
  99. }]);
  100. $validator->addNestedMany('comments', $inner);
  101. $result = $validator->errors(['comments' => [['comment' => 'example']]]);
  102. $this->assertNotEmpty($result, 'Validation should fail');
  103. }
  104. /**
  105. * Tests that calling field will create a default validation set for it
  106. *
  107. * @return void
  108. */
  109. public function testFieldDefault()
  110. {
  111. $validator = new Validator;
  112. $this->assertFalse($validator->hasField('foo'));
  113. $field = $validator->field('foo');
  114. $this->assertInstanceOf('Cake\Validation\ValidationSet', $field);
  115. $this->assertCount(0, $field);
  116. $this->assertTrue($validator->hasField('foo'));
  117. }
  118. /**
  119. * Tests that field method can be used as a setter
  120. *
  121. * @return void
  122. */
  123. public function testFieldSetter()
  124. {
  125. $validator = new Validator;
  126. $validationSet = new ValidationSet;
  127. $validator->field('thing', $validationSet);
  128. $this->assertSame($validationSet, $validator->field('thing'));
  129. }
  130. /**
  131. * Tests the remove method
  132. *
  133. * @return void
  134. */
  135. public function testRemove()
  136. {
  137. $validator = new Validator;
  138. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  139. $validator->add('title', 'foo', ['rule' => 'bar']);
  140. $this->assertCount(2, $validator->field('title'));
  141. $validator->remove('title');
  142. $this->assertCount(0, $validator->field('title'));
  143. $validator->remove('title');
  144. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  145. $validator->add('title', 'foo', ['rule' => 'bar']);
  146. $this->assertCount(2, $validator->field('title'));
  147. $validator->remove('title', 'foo');
  148. $this->assertCount(1, $validator->field('title'));
  149. $this->assertNull($validator->field('title')->rule('foo'));
  150. }
  151. /**
  152. * Tests the requirePresence method
  153. *
  154. * @return void
  155. */
  156. public function testRequirePresence()
  157. {
  158. $validator = new Validator;
  159. $this->assertSame($validator, $validator->requirePresence('title'));
  160. $this->assertTrue($validator->field('title')->isPresenceRequired());
  161. $validator->requirePresence('title', false);
  162. $this->assertFalse($validator->field('title')->isPresenceRequired());
  163. $validator->requirePresence('title', 'create');
  164. $this->assertEquals('create', $validator->field('title')->isPresenceRequired());
  165. $validator->requirePresence('title', 'update');
  166. $this->assertEquals('update', $validator->field('title')->isPresenceRequired());
  167. }
  168. /**
  169. * Tests the requirePresence method
  170. *
  171. * @return void
  172. */
  173. public function testRequirePresenceAsArray()
  174. {
  175. $validator = new Validator;
  176. $validator->requirePresence(['title', 'created']);
  177. $this->assertTrue($validator->field('title')->isPresenceRequired());
  178. $this->assertTrue($validator->field('created')->isPresenceRequired());
  179. $validator->requirePresence([
  180. 'title' => [
  181. 'mode' => false
  182. ],
  183. 'content' => [
  184. 'mode' => 'update'
  185. ],
  186. 'subject'
  187. ], true);
  188. $this->assertFalse($validator->field('title')->isPresenceRequired());
  189. $this->assertEquals('update', $validator->field('content')->isPresenceRequired());
  190. $this->assertTrue($validator->field('subject')->isPresenceRequired());
  191. }
  192. /**
  193. * Tests the requirePresence failure case
  194. *
  195. * @expectedException InvalidArgumentException
  196. * @return void
  197. */
  198. public function testRequirePresenceAsArrayFailure()
  199. {
  200. $validator = new Validator();
  201. $validator->requirePresence(['title' => 'derp', 'created' => false]);
  202. }
  203. /**
  204. * Tests the requirePresence method when passing a callback
  205. *
  206. * @return void
  207. */
  208. public function testRequirePresenceCallback()
  209. {
  210. $validator = new Validator;
  211. $require = true;
  212. $validator->requirePresence('title', function ($context) use (&$require) {
  213. $this->assertEquals([], $context['data']);
  214. $this->assertEquals([], $context['providers']);
  215. $this->assertEquals('title', $context['field']);
  216. $this->assertTrue($context['newRecord']);
  217. return $require;
  218. });
  219. $this->assertTrue($validator->isPresenceRequired('title', true));
  220. $require = false;
  221. $this->assertFalse($validator->isPresenceRequired('title', true));
  222. }
  223. /**
  224. * Tests the isPresenceRequired method
  225. *
  226. * @return void
  227. */
  228. public function testIsPresenceRequired()
  229. {
  230. $validator = new Validator;
  231. $this->assertSame($validator, $validator->requirePresence('title'));
  232. $this->assertTrue($validator->isPresenceRequired('title', true));
  233. $this->assertTrue($validator->isPresenceRequired('title', false));
  234. $validator->requirePresence('title', false);
  235. $this->assertFalse($validator->isPresenceRequired('title', true));
  236. $this->assertFalse($validator->isPresenceRequired('title', false));
  237. $validator->requirePresence('title', 'create');
  238. $this->assertTrue($validator->isPresenceRequired('title', true));
  239. $this->assertFalse($validator->isPresenceRequired('title', false));
  240. $validator->requirePresence('title', 'update');
  241. $this->assertTrue($validator->isPresenceRequired('title', false));
  242. $this->assertFalse($validator->isPresenceRequired('title', true));
  243. }
  244. /**
  245. * Tests errors generated when a field presence is required
  246. *
  247. * @return void
  248. */
  249. public function testErrorsWithPresenceRequired()
  250. {
  251. $validator = new Validator;
  252. $validator->requirePresence('title');
  253. $errors = $validator->errors(['foo' => 'something']);
  254. $expected = ['title' => ['_required' => 'This field is required']];
  255. $this->assertEquals($expected, $errors);
  256. $this->assertEmpty($validator->errors(['title' => 'bar']));
  257. $validator->requirePresence('title', false);
  258. $this->assertEmpty($validator->errors(['foo' => 'bar']));
  259. }
  260. /**
  261. * Test that errors() can work with nested data.
  262. *
  263. * @return void
  264. */
  265. public function testErrorsWithNestedFields()
  266. {
  267. $validator = new Validator();
  268. $user = new Validator();
  269. $user->add('username', 'letter', ['rule' => 'alphanumeric']);
  270. $comments = new Validator();
  271. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  272. $validator->addNested('user', $user);
  273. $validator->addNestedMany('comments', $comments);
  274. $data = [
  275. 'user' => [
  276. 'username' => 'is wrong'
  277. ],
  278. 'comments' => [
  279. ['comment' => 'is wrong']
  280. ]
  281. ];
  282. $errors = $validator->errors($data);
  283. $expected = [
  284. 'user' => [
  285. 'username' => ['letter' => 'The provided value is invalid']
  286. ],
  287. 'comments' => [
  288. 0 => ['comment' => ['letter' => 'The provided value is invalid']]
  289. ]
  290. ];
  291. $this->assertEquals($expected, $errors);
  292. }
  293. /**
  294. * Test nested fields with many, but invalid data.
  295. *
  296. * @return void
  297. */
  298. public function testErrorsWithNestedSingleInvalidType()
  299. {
  300. $validator = new Validator();
  301. $user = new Validator();
  302. $user->add('user', 'letter', ['rule' => 'alphanumeric']);
  303. $validator->addNested('user', $user);
  304. $data = [
  305. 'user' => 'a string',
  306. ];
  307. $errors = $validator->errors($data);
  308. $expected = [
  309. 'user' => ['_nested' => 'The provided value is invalid'],
  310. ];
  311. $this->assertEquals($expected, $errors);
  312. }
  313. /**
  314. * Test nested fields with many, but invalid data.
  315. *
  316. * @return void
  317. */
  318. public function testErrorsWithNestedManyInvalidType()
  319. {
  320. $validator = new Validator();
  321. $comments = new Validator();
  322. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  323. $validator->addNestedMany('comments', $comments);
  324. $data = [
  325. 'comments' => 'a string',
  326. ];
  327. $errors = $validator->errors($data);
  328. $expected = [
  329. 'comments' => ['_nested' => 'The provided value is invalid'],
  330. ];
  331. $this->assertEquals($expected, $errors);
  332. }
  333. /**
  334. * Test nested fields with many, but invalid data.
  335. *
  336. * @return void
  337. */
  338. public function testErrorsWithNestedManySomeInvalid()
  339. {
  340. $validator = new Validator();
  341. $comments = new Validator();
  342. $comments->add('comment', 'letter', ['rule' => 'alphanumeric']);
  343. $validator->addNestedMany('comments', $comments);
  344. $data = [
  345. 'comments' => [
  346. 'a string',
  347. ['comment' => 'letters'],
  348. ['comment' => 'more invalid']
  349. ]
  350. ];
  351. $errors = $validator->errors($data);
  352. $expected = [
  353. 'comments' => [
  354. '_nested' => 'The provided value is invalid',
  355. ],
  356. ];
  357. $this->assertEquals($expected, $errors);
  358. }
  359. /**
  360. * Tests custom error messages generated when a field presence is required
  361. *
  362. * @return void
  363. */
  364. public function testCustomErrorsWithPresenceRequired()
  365. {
  366. $validator = new Validator;
  367. $validator->requirePresence('title', true, 'Custom message');
  368. $errors = $validator->errors(['foo' => 'something']);
  369. $expected = ['title' => ['_required' => 'Custom message']];
  370. $this->assertEquals($expected, $errors);
  371. }
  372. /**
  373. * Tests custom error messages generated when a field presence is required
  374. *
  375. * @return void
  376. */
  377. public function testCustomErrorsWithPresenceRequiredAsArray()
  378. {
  379. $validator = new Validator;
  380. $validator->requirePresence(['title', 'content'], true, 'Custom message');
  381. $errors = $validator->errors(['foo' => 'something']);
  382. $expected = [
  383. 'title' => ['_required' => 'Custom message'],
  384. 'content' => ['_required' => 'Custom message']
  385. ];
  386. $this->assertEquals($expected, $errors);
  387. $validator->requirePresence([
  388. 'title' => [
  389. 'message' => 'Test message'
  390. ],
  391. 'content'
  392. ], true, 'Custom message');
  393. $errors = $validator->errors(['foo' => 'something']);
  394. $expected = [
  395. 'title' => ['_required' => 'Test message'],
  396. 'content' => ['_required' => 'Custom message']
  397. ];
  398. $this->assertEquals($expected, $errors);
  399. }
  400. /**
  401. * Tests the allowEmpty method
  402. *
  403. * @return void
  404. */
  405. public function testAllowEmpty()
  406. {
  407. $validator = new Validator;
  408. $this->assertSame($validator, $validator->allowEmpty('title'));
  409. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  410. $validator->allowEmpty('title', 'create');
  411. $this->assertEquals('create', $validator->field('title')->isEmptyAllowed());
  412. $validator->allowEmpty('title', 'update');
  413. $this->assertEquals('update', $validator->field('title')->isEmptyAllowed());
  414. }
  415. /**
  416. * Tests the allowEmpty method with date/time fields.
  417. *
  418. * @return void
  419. */
  420. public function testAllowEmptyDateTime()
  421. {
  422. $validator = new Validator;
  423. $validator->allowEmpty('created')
  424. ->add('created', 'date', ['rule' => 'date']);
  425. $data = [
  426. 'created' => [
  427. 'year' => '',
  428. 'month' => '',
  429. 'day' => ''
  430. ]
  431. ];
  432. $result = $validator->errors($data);
  433. $this->assertEmpty($result, 'No errors on empty date');
  434. $data = [
  435. 'created' => [
  436. 'year' => '',
  437. 'month' => '',
  438. 'day' => '',
  439. 'hour' => '',
  440. 'minute' => '',
  441. 'second' => '',
  442. 'meridian' => '',
  443. ]
  444. ];
  445. $result = $validator->errors($data);
  446. $this->assertEmpty($result, 'No errors on empty datetime');
  447. $data = [
  448. 'created' => [
  449. 'hour' => '',
  450. 'minute' => '',
  451. 'meridian' => '',
  452. ]
  453. ];
  454. $result = $validator->errors($data);
  455. $this->assertEmpty($result, 'No errors on empty time');
  456. }
  457. /**
  458. * Tests the allowEmpty method with file fields.
  459. *
  460. * @return void
  461. */
  462. public function testAllowEmptyFileFields()
  463. {
  464. $validator = new Validator;
  465. $validator->allowEmpty('picture')
  466. ->add('picture', 'file', ['rule' => 'uploadedFile']);
  467. $data = [
  468. 'picture' => [
  469. 'name' => '',
  470. 'type' => '',
  471. 'tmp_name' => '',
  472. 'error' => UPLOAD_ERR_NO_FILE,
  473. ]
  474. ];
  475. $result = $validator->errors($data);
  476. $this->assertEmpty($result, 'No errors on empty date');
  477. $data = [
  478. 'picture' => [
  479. 'name' => 'fake.png',
  480. 'type' => '',
  481. 'tmp_name' => '',
  482. 'error' => UPLOAD_ERR_OK,
  483. ]
  484. ];
  485. $result = $validator->errors($data);
  486. $this->assertNotEmpty($result, 'Invalid file should be caught still.');
  487. }
  488. /**
  489. * Tests the allowEmpty as array method
  490. *
  491. * @return void
  492. */
  493. public function testAllowEmptyAsArray()
  494. {
  495. $validator = new Validator;
  496. $validator->allowEmpty([
  497. 'title',
  498. 'subject',
  499. 'posted_at' => [
  500. 'when' => false,
  501. 'message' => 'Post time cannot be empty'
  502. ],
  503. 'updated_at' => [
  504. 'when' => true
  505. ],
  506. 'show_at' => [
  507. 'when' => 'update'
  508. ]
  509. ], 'create', 'Cannot be empty');
  510. $this->assertEquals('create', $validator->field('title')->isEmptyAllowed());
  511. $this->assertEquals('create', $validator->field('subject')->isEmptyAllowed());
  512. $this->assertFalse($validator->field('posted_at')->isEmptyAllowed());
  513. $this->assertTrue($validator->field('updated_at')->isEmptyAllowed());
  514. $this->assertEquals('update', $validator->field('show_at')->isEmptyAllowed());
  515. $errors = $validator->errors([
  516. 'title' => '',
  517. 'subject' => null,
  518. 'posted_at' => null,
  519. 'updated_at' => null,
  520. 'show_at' => ''
  521. ], false);
  522. $expected = [
  523. 'title' => ['_empty' => 'Cannot be empty'],
  524. 'subject' => ['_empty' => 'Cannot be empty'],
  525. 'posted_at' => ['_empty' => 'Post time cannot be empty']
  526. ];
  527. $this->assertEquals($expected, $errors);
  528. }
  529. /**
  530. * Tests the allowEmpty failure case
  531. *
  532. * @expectedException InvalidArgumentException
  533. * @return void
  534. */
  535. public function testAllowEmptyAsArrayFailure()
  536. {
  537. $validator = new Validator();
  538. $validator->allowEmpty(['title' => 'derp', 'created' => false]);
  539. }
  540. /**
  541. * Test the notEmpty() method.
  542. *
  543. * @return void
  544. */
  545. public function testNotEmpty()
  546. {
  547. $validator = new Validator;
  548. $validator->notEmpty('title');
  549. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  550. $validator->allowEmpty('title');
  551. $this->assertTrue($validator->field('title')->isEmptyAllowed());
  552. }
  553. /**
  554. * Tests the notEmpty as array method
  555. *
  556. * @return void
  557. */
  558. public function testNotEmptyAsArray()
  559. {
  560. $validator = new Validator;
  561. $validator->notEmpty(['title', 'created']);
  562. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  563. $this->assertFalse($validator->field('created')->isEmptyAllowed());
  564. $validator->notEmpty([
  565. 'title' => [
  566. 'when' => false
  567. ],
  568. 'content' => [
  569. 'when' => 'update'
  570. ],
  571. 'posted_at' => [
  572. 'when' => 'create'
  573. ],
  574. 'show_at' => [
  575. 'message' => 'Show date cannot be empty',
  576. 'when' => false
  577. ],
  578. 'subject'
  579. ], 'Not empty', true);
  580. $this->assertFalse($validator->field('title')->isEmptyAllowed());
  581. $this->assertTrue($validator->isEmptyAllowed('content', true));
  582. $this->assertFalse($validator->isEmptyAllowed('content', false));
  583. $this->assertFalse($validator->isEmptyAllowed('posted_at', true));
  584. $this->assertTrue($validator->isEmptyAllowed('posted_at', false));
  585. $this->assertTrue($validator->field('subject')->isEmptyAllowed());
  586. $errors = $validator->errors([
  587. 'title' => '',
  588. 'content' => '',
  589. 'posted_at' => null,
  590. 'show_at' => null,
  591. 'subject' => ''
  592. ], false);
  593. $expected = [
  594. 'title' => ['_empty' => 'Not empty'],
  595. 'content' => ['_empty' => 'Not empty'],
  596. 'show_at' => ['_empty' => 'Show date cannot be empty']
  597. ];
  598. $this->assertEquals($expected, $errors);
  599. }
  600. /**
  601. * Tests the notEmpty failure case
  602. *
  603. * @expectedException InvalidArgumentException
  604. * @return void
  605. */
  606. public function testNotEmptyAsArrayFailure()
  607. {
  608. $validator = new Validator();
  609. $validator->notEmpty(['title' => 'derp', 'created' => false]);
  610. }
  611. /**
  612. * Test the notEmpty() method.
  613. *
  614. * @return void
  615. */
  616. public function testNotEmptyModes()
  617. {
  618. $validator = new Validator;
  619. $validator->notEmpty('title', 'Need a title', 'create');
  620. $this->assertFalse($validator->isEmptyAllowed('title', true));
  621. $this->assertTrue($validator->isEmptyAllowed('title', false));
  622. $validator->notEmpty('title', 'Need a title', 'update');
  623. $this->assertTrue($validator->isEmptyAllowed('title', true));
  624. $this->assertFalse($validator->isEmptyAllowed('title', false));
  625. $validator->notEmpty('title', 'Need a title');
  626. $this->assertFalse($validator->isEmptyAllowed('title', true));
  627. $this->assertFalse($validator->isEmptyAllowed('title', false));
  628. $validator->notEmpty('title');
  629. $this->assertFalse($validator->isEmptyAllowed('title', true));
  630. $this->assertFalse($validator->isEmptyAllowed('title', false));
  631. }
  632. /**
  633. * Test interactions between notEmpty() and isAllowed().
  634. *
  635. * @return void
  636. */
  637. public function testNotEmptyAndIsAllowed()
  638. {
  639. $validator = new Validator;
  640. $validator->allowEmpty('title')
  641. ->notEmpty('title', 'Need it', 'update');
  642. $this->assertTrue($validator->isEmptyAllowed('title', true));
  643. $this->assertFalse($validator->isEmptyAllowed('title', false));
  644. $validator->allowEmpty('title')
  645. ->notEmpty('title');
  646. $this->assertFalse($validator->isEmptyAllowed('title', true));
  647. $this->assertFalse($validator->isEmptyAllowed('title', false));
  648. $validator->notEmpty('title')
  649. ->allowEmpty('title', 'create');
  650. $this->assertTrue($validator->isEmptyAllowed('title', true));
  651. $this->assertFalse($validator->isEmptyAllowed('title', false));
  652. }
  653. /**
  654. * Tests the allowEmpty method when passing a callback
  655. *
  656. * @return void
  657. */
  658. public function testAllowEmptyCallback()
  659. {
  660. $validator = new Validator;
  661. $allow = true;
  662. $validator->allowEmpty('title', function ($context) use (&$allow) {
  663. $this->assertEquals([], $context['data']);
  664. $this->assertEquals([], $context['providers']);
  665. $this->assertTrue($context['newRecord']);
  666. return $allow;
  667. });
  668. $this->assertTrue($validator->isEmptyAllowed('title', true));
  669. $allow = false;
  670. $this->assertFalse($validator->isEmptyAllowed('title', true));
  671. }
  672. /**
  673. * Tests the notEmpty method when passing a callback
  674. *
  675. * @return void
  676. */
  677. public function testNotEmptyCallback()
  678. {
  679. $validator = new Validator;
  680. $prevent = true;
  681. $validator->notEmpty('title', 'error message', function ($context) use (&$prevent) {
  682. $this->assertEquals([], $context['data']);
  683. $this->assertEquals([], $context['providers']);
  684. $this->assertFalse($context['newRecord']);
  685. return $prevent;
  686. });
  687. $this->assertFalse($validator->isEmptyAllowed('title', false));
  688. $prevent = false;
  689. $this->assertTrue($validator->isEmptyAllowed('title', false));
  690. }
  691. /**
  692. * Tests the isEmptyAllowed method
  693. *
  694. * @return void
  695. */
  696. public function testIsEmptyAllowed()
  697. {
  698. $validator = new Validator;
  699. $this->assertSame($validator, $validator->allowEmpty('title'));
  700. $this->assertTrue($validator->isEmptyAllowed('title', true));
  701. $this->assertTrue($validator->isEmptyAllowed('title', false));
  702. $validator->notEmpty('title');
  703. $this->assertFalse($validator->isEmptyAllowed('title', true));
  704. $this->assertFalse($validator->isEmptyAllowed('title', false));
  705. $validator->allowEmpty('title', 'create');
  706. $this->assertTrue($validator->isEmptyAllowed('title', true));
  707. $this->assertFalse($validator->isEmptyAllowed('title', false));
  708. $validator->allowEmpty('title', 'update');
  709. $this->assertTrue($validator->isEmptyAllowed('title', false));
  710. $this->assertFalse($validator->isEmptyAllowed('title', true));
  711. }
  712. /**
  713. * Tests errors generated when a field is not allowed to be empty
  714. *
  715. * @return void
  716. */
  717. public function testErrorsWithEmptyNotAllowed()
  718. {
  719. $validator = new Validator;
  720. $validator->notEmpty('title');
  721. $errors = $validator->errors(['title' => '']);
  722. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  723. $this->assertEquals($expected, $errors);
  724. $errors = $validator->errors(['title' => []]);
  725. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  726. $this->assertEquals($expected, $errors);
  727. $errors = $validator->errors(['title' => null]);
  728. $expected = ['title' => ['_empty' => 'This field cannot be left empty']];
  729. $this->assertEquals($expected, $errors);
  730. $errors = $validator->errors(['title' => 0]);
  731. $this->assertEmpty($errors);
  732. $errors = $validator->errors(['title' => '0']);
  733. $this->assertEmpty($errors);
  734. $errors = $validator->errors(['title' => false]);
  735. $this->assertEmpty($errors);
  736. }
  737. /**
  738. * Tests custom error messages generated when a field is allowed to be empty
  739. *
  740. * @return void
  741. */
  742. public function testCustomErrorsWithAllowedEmpty()
  743. {
  744. $validator = new Validator;
  745. $validator->allowEmpty('title', false, 'Custom message');
  746. $errors = $validator->errors(['title' => null]);
  747. $expected = ['title' => ['_empty' => 'Custom message']];
  748. $this->assertEquals($expected, $errors);
  749. }
  750. /**
  751. * Tests custom error messages generated when a field is not allowed to be empty
  752. *
  753. * @return void
  754. */
  755. public function testCustomErrorsWithEmptyNotAllowed()
  756. {
  757. $validator = new Validator;
  758. $validator->notEmpty('title', 'Custom message');
  759. $errors = $validator->errors(['title' => '']);
  760. $expected = ['title' => ['_empty' => 'Custom message']];
  761. $this->assertEquals($expected, $errors);
  762. }
  763. /**
  764. * Tests errors generated when a field is allowed to be empty
  765. *
  766. * @return void
  767. */
  768. public function testErrorsWithEmptyAllowed()
  769. {
  770. $validator = new Validator;
  771. $validator->allowEmpty('title');
  772. $errors = $validator->errors(['title' => '']);
  773. $this->assertEmpty($errors);
  774. $errors = $validator->errors(['title' => []]);
  775. $this->assertEmpty($errors);
  776. $errors = $validator->errors(['title' => null]);
  777. $this->assertEmpty($errors);
  778. $errors = $validator->errors(['title' => 0]);
  779. $this->assertEmpty($errors);
  780. $errors = $validator->errors(['title' => 0.0]);
  781. $this->assertEmpty($errors);
  782. $errors = $validator->errors(['title' => '0']);
  783. $this->assertEmpty($errors);
  784. $errors = $validator->errors(['title' => false]);
  785. $this->assertEmpty($errors);
  786. }
  787. /**
  788. * Test the provider() method
  789. *
  790. * @return void
  791. */
  792. public function testProvider()
  793. {
  794. $validator = new Validator;
  795. $object = new \stdClass;
  796. $this->assertSame($validator, $validator->provider('foo', $object));
  797. $this->assertSame($object, $validator->provider('foo'));
  798. $this->assertNull($validator->provider('bar'));
  799. $another = new \stdClass;
  800. $this->assertSame($validator, $validator->provider('bar', $another));
  801. $this->assertSame($another, $validator->provider('bar'));
  802. $this->assertEquals(new \Cake\Validation\RulesProvider, $validator->provider('default'));
  803. }
  804. /**
  805. * Tests errors() method when using validators from the default provider, this proves
  806. * that it returns a default validation message and the custom one set in the rule
  807. *
  808. * @return void
  809. */
  810. public function testErrorsFromDefaultProvider()
  811. {
  812. $validator = new Validator;
  813. $validator
  814. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  815. ->add('email', 'notBlank', ['rule' => 'notBlank'])
  816. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  817. $errors = $validator->errors(['email' => 'not an email!']);
  818. $expected = [
  819. 'email' => [
  820. 'alpha' => 'The provided value is invalid',
  821. 'email' => 'Y u no write email?'
  822. ]
  823. ];
  824. $this->assertEquals($expected, $errors);
  825. }
  826. /**
  827. * Tests using validation methods from different providers and returning the error
  828. * as a string
  829. *
  830. * @return void
  831. */
  832. public function testErrorsFromCustomProvider()
  833. {
  834. $validator = new Validator;
  835. $validator
  836. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  837. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  838. $thing = $this->getMockBuilder('\stdClass')
  839. ->setMethods(['isCool'])
  840. ->getMock();
  841. $thing->expects($this->once())->method('isCool')
  842. ->will($this->returnCallback(function ($data, $context) use ($thing) {
  843. $this->assertEquals('bar', $data);
  844. $expected = [
  845. 'default' => new \Cake\Validation\RulesProvider,
  846. 'thing' => $thing
  847. ];
  848. $expected = [
  849. 'newRecord' => true,
  850. 'providers' => $expected,
  851. 'data' => [
  852. 'email' => '!',
  853. 'title' => 'bar'
  854. ],
  855. 'field' => 'title'
  856. ];
  857. $this->assertEquals($expected, $context);
  858. return "That ain't cool, yo";
  859. }));
  860. $validator->provider('thing', $thing);
  861. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  862. $expected = [
  863. 'email' => ['alpha' => 'The provided value is invalid'],
  864. 'title' => ['cool' => "That ain't cool, yo"]
  865. ];
  866. $this->assertEquals($expected, $errors);
  867. }
  868. /**
  869. * Tests that it is possible to pass extra arguments to the validation function
  870. * and it still gets the providers as last argument
  871. *
  872. * @return void
  873. */
  874. public function testMethodsWithExtraArguments()
  875. {
  876. $validator = new Validator;
  877. $validator->add('title', 'cool', [
  878. 'rule' => ['isCool', 'and', 'awesome'],
  879. 'provider' => 'thing'
  880. ]);
  881. $thing = $this->getMockBuilder('\stdClass')
  882. ->setMethods(['isCool'])
  883. ->getMock();
  884. $thing->expects($this->once())->method('isCool')
  885. ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
  886. $this->assertEquals('bar', $data);
  887. $this->assertEquals('and', $a);
  888. $this->assertEquals('awesome', $b);
  889. $expected = [
  890. 'default' => new \Cake\Validation\RulesProvider,
  891. 'thing' => $thing
  892. ];
  893. $expected = [
  894. 'newRecord' => true,
  895. 'providers' => $expected,
  896. 'data' => [
  897. 'email' => '!',
  898. 'title' => 'bar'
  899. ],
  900. 'field' => 'title'
  901. ];
  902. $this->assertEquals($expected, $context);
  903. return "That ain't cool, yo";
  904. }));
  905. $validator->provider('thing', $thing);
  906. $errors = $validator->errors(['email' => '!', 'title' => 'bar']);
  907. $expected = [
  908. 'title' => ['cool' => "That ain't cool, yo"]
  909. ];
  910. $this->assertEquals($expected, $errors);
  911. }
  912. /**
  913. * Tests that it is possible to use a closure as a rule
  914. *
  915. * @return void
  916. */
  917. public function testUsingClosureAsRule()
  918. {
  919. $validator = new Validator;
  920. $validator->add('name', 'myRule', [
  921. 'rule' => function ($data, $provider) {
  922. $this->assertEquals('foo', $data);
  923. return 'You fail';
  924. }
  925. ]);
  926. $expected = ['name' => ['myRule' => 'You fail']];
  927. $this->assertEquals($expected, $validator->errors(['name' => 'foo']));
  928. }
  929. /**
  930. * Tests that setting last to a rule will stop validating the rest of the rules
  931. *
  932. * @return void
  933. */
  934. public function testErrorsWithLastRule()
  935. {
  936. $validator = new Validator;
  937. $validator
  938. ->add('email', 'alpha', ['rule' => 'alphanumeric', 'last' => true])
  939. ->add('email', 'email', ['rule' => 'email', 'message' => 'Y u no write email?']);
  940. $errors = $validator->errors(['email' => 'not an email!']);
  941. $expected = [
  942. 'email' => [
  943. 'alpha' => 'The provided value is invalid'
  944. ]
  945. ];
  946. $this->assertEquals($expected, $errors);
  947. }
  948. /**
  949. * Tests it is possible to get validation sets for a field using an array interface
  950. *
  951. * @return void
  952. */
  953. public function testArrayAccessGet()
  954. {
  955. $validator = new Validator;
  956. $validator
  957. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  958. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  959. $this->assertSame($validator['email'], $validator->field('email'));
  960. $this->assertSame($validator['title'], $validator->field('title'));
  961. }
  962. /**
  963. * Tests it is possible to check for validation sets for a field using an array inteface
  964. *
  965. * @return void
  966. */
  967. public function testArrayAccessExists()
  968. {
  969. $validator = new Validator;
  970. $validator
  971. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  972. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  973. $this->assertTrue(isset($validator['email']));
  974. $this->assertTrue(isset($validator['title']));
  975. $this->assertFalse(isset($validator['foo']));
  976. }
  977. /**
  978. * Tests it is possible to set validation rules for a field using an array inteface
  979. *
  980. * @return void
  981. */
  982. public function testArrayAccessSet()
  983. {
  984. $validator = new Validator;
  985. $validator
  986. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  987. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  988. $validator['name'] = $validator->field('title');
  989. $this->assertSame($validator->field('title'), $validator->field('name'));
  990. $validator['name'] = ['alpha' => ['rule' => 'alphanumeric']];
  991. $this->assertEquals($validator->field('email'), $validator->field('email'));
  992. }
  993. /**
  994. * Tests it is possible to unset validation rules
  995. *
  996. * @return void
  997. */
  998. public function testArrayAccessUset()
  999. {
  1000. $validator = new Validator;
  1001. $validator
  1002. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1003. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1004. $this->assertTrue(isset($validator['title']));
  1005. unset($validator['title']);
  1006. $this->assertFalse(isset($validator['title']));
  1007. }
  1008. /**
  1009. * Tests the countable interface
  1010. *
  1011. * @return void
  1012. */
  1013. public function testCount()
  1014. {
  1015. $validator = new Validator;
  1016. $validator
  1017. ->add('email', 'alpha', ['rule' => 'alphanumeric'])
  1018. ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
  1019. $this->assertCount(2, $validator);
  1020. }
  1021. /**
  1022. * Tests adding rules via alternative syntax
  1023. *
  1024. * @return void
  1025. */
  1026. public function testAddMulitple()
  1027. {
  1028. $validator = new Validator;
  1029. $validator->add('title', [
  1030. 'notBlank' => [
  1031. 'rule' => 'notBlank'
  1032. ],
  1033. 'length' => [
  1034. 'rule' => ['minLength', 10],
  1035. 'message' => 'Titles need to be at least 10 characters long'
  1036. ]
  1037. ]);
  1038. $set = $validator->field('title');
  1039. $this->assertInstanceOf('Cake\Validation\ValidationSet', $set);
  1040. $this->assertCount(2, $set);
  1041. }
  1042. /**
  1043. * Integration test for compareWith validator.
  1044. *
  1045. * @return void
  1046. */
  1047. public function testCompareWithIntegration()
  1048. {
  1049. $validator = new Validator;
  1050. $validator->add('password', [
  1051. 'compare' => [
  1052. 'rule' => ['compareWith', 'password_compare']
  1053. ],
  1054. ]);
  1055. $data = [
  1056. 'password' => 'test',
  1057. 'password_compare' => 'not the same'
  1058. ];
  1059. $this->assertNotEmpty($validator->errors($data), 'Validation should fail.');
  1060. }
  1061. /**
  1062. * Test debugInfo helper method.
  1063. *
  1064. * @return void
  1065. */
  1066. public function testDebugInfo()
  1067. {
  1068. $validator = new Validator();
  1069. $validator->provider('test', $this);
  1070. $validator->add('title', 'not-empty', ['rule' => 'notEmpty']);
  1071. $validator->requirePresence('body');
  1072. $validator->allowEmpty('published');
  1073. $result = $validator->__debugInfo();
  1074. $expected = [
  1075. '_providers' => ['test'],
  1076. '_fields' => [
  1077. 'title' => [
  1078. 'isPresenceRequired' => false,
  1079. 'isEmptyAllowed' => false,
  1080. 'rules' => ['not-empty'],
  1081. ],
  1082. 'body' => [
  1083. 'isPresenceRequired' => true,
  1084. 'isEmptyAllowed' => false,
  1085. 'rules' => [],
  1086. ],
  1087. 'published' => [
  1088. 'isPresenceRequired' => false,
  1089. 'isEmptyAllowed' => true,
  1090. 'rules' => [],
  1091. ],
  1092. ],
  1093. '_presenceMessages' => [],
  1094. '_allowEmptyMessages' => [],
  1095. '_useI18n' => true,
  1096. ];
  1097. $this->assertEquals($expected, $result);
  1098. }
  1099. /**
  1100. * Tests that the 'create' and 'update' modes are preserved when using
  1101. * nested validators
  1102. *
  1103. * @return void
  1104. */
  1105. public function testNestedValidatorCreate()
  1106. {
  1107. $validator = new Validator();
  1108. $inner = new Validator();
  1109. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1110. $validator->addNested('user', $inner);
  1111. $this->assertNotEmpty($validator->errors(['user' => ['username' => 'example']], true));
  1112. $this->assertEmpty($validator->errors(['user' => ['username' => 'a']], false));
  1113. }
  1114. /**
  1115. * Tests that the 'create' and 'update' modes are preserved when using
  1116. * nested validators
  1117. *
  1118. * @return void
  1119. */
  1120. public function testNestedManyValidatorCreate()
  1121. {
  1122. $validator = new Validator();
  1123. $inner = new Validator();
  1124. $inner->add('username', 'email', ['rule' => 'email', 'on' => 'create']);
  1125. $validator->addNestedMany('user', $inner);
  1126. $this->assertNotEmpty($validator->errors(['user' => [['username' => 'example']]], true));
  1127. $this->assertEmpty($validator->errors(['user' => [['username' => 'a']]], false));
  1128. }
  1129. /**
  1130. * Tests the notBlank proxy method
  1131. *
  1132. * @return void
  1133. */
  1134. public function testNotBlank()
  1135. {
  1136. $validator = new Validator();
  1137. $this->assertProxyMethod($validator, 'notBlank');
  1138. $this->assertNotEmpty($validator->errors(['username' => ' ']));
  1139. }
  1140. /**
  1141. * Tests the alphanumeric proxy method
  1142. *
  1143. * @return void
  1144. */
  1145. public function testAlphanumeric()
  1146. {
  1147. $validator = new Validator();
  1148. $this->assertProxyMethod($validator, 'alphaNumeric');
  1149. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1150. }
  1151. /**
  1152. * Tests the lengthBetween proxy method
  1153. *
  1154. * @return void
  1155. */
  1156. public function testLengthBetween()
  1157. {
  1158. $validator = new Validator();
  1159. $this->assertProxyMethod($validator, 'lengthBetween', [5, 7], [5, 7]);
  1160. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1161. }
  1162. /**
  1163. * Tests the lengthBetween proxy method
  1164. *
  1165. * @expectedException InvalidArgumentException
  1166. * @return void
  1167. */
  1168. public function testLengthBetweenFailure()
  1169. {
  1170. $validator = new Validator();
  1171. $validator->lengthBetween('username', [7]);
  1172. }
  1173. /**
  1174. * Tests the creditCard proxy method
  1175. *
  1176. * @return void
  1177. */
  1178. public function testCreditCard()
  1179. {
  1180. $validator = new Validator();
  1181. $this->assertProxyMethod($validator, 'creditCard', 'all', ['all', true], 'cc');
  1182. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1183. }
  1184. /**
  1185. * Tests the greaterThan proxy method
  1186. *
  1187. * @return void
  1188. */
  1189. public function testGreaterThan()
  1190. {
  1191. $validator = new Validator();
  1192. $this->assertProxyMethod($validator, 'greaterThan', 5, ['>', 5], 'comparison');
  1193. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1194. }
  1195. /**
  1196. * Tests the greaterThanOrEqual proxy method
  1197. *
  1198. * @return void
  1199. */
  1200. public function testGreaterThanOrEqual()
  1201. {
  1202. $validator = new Validator();
  1203. $this->assertProxyMethod($validator, 'greaterThanOrEqual', 5, ['>=', 5], 'comparison');
  1204. $this->assertNotEmpty($validator->errors(['username' => 2]));
  1205. }
  1206. /**
  1207. * Tests the lessThan proxy method
  1208. *
  1209. * @return void
  1210. */
  1211. public function testLessThan()
  1212. {
  1213. $validator = new Validator();
  1214. $this->assertProxyMethod($validator, 'lessThan', 5, ['<', 5], 'comparison');
  1215. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1216. }
  1217. /**
  1218. * Tests the lessThanOrEqual proxy method
  1219. *
  1220. * @return void
  1221. */
  1222. public function testLessThanOrEqual()
  1223. {
  1224. $validator = new Validator();
  1225. $this->assertProxyMethod($validator, 'lessThanOrEqual', 5, ['<=', 5], 'comparison');
  1226. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1227. }
  1228. /**
  1229. * Tests the equals proxy method
  1230. *
  1231. * @return void
  1232. */
  1233. public function testEquals()
  1234. {
  1235. $validator = new Validator();
  1236. $this->assertProxyMethod($validator, 'equals', 5, ['==', 5], 'comparison');
  1237. $this->assertEmpty($validator->errors(['username' => 5]));
  1238. $this->assertNotEmpty($validator->errors(['username' => 6]));
  1239. }
  1240. /**
  1241. * Tests the notEquals proxy method
  1242. *
  1243. * @return void
  1244. */
  1245. public function testNotEquals()
  1246. {
  1247. $validator = new Validator();
  1248. $this->assertProxyMethod($validator, 'notEquals', 5, ['!=', 5], 'comparison');
  1249. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1250. }
  1251. /**
  1252. * Tests the sameAs proxy method
  1253. *
  1254. * @return void
  1255. */
  1256. public function testSameAs()
  1257. {
  1258. $validator = new Validator();
  1259. $this->assertProxyMethod($validator, 'sameAs', 'other', ['other'], 'compareWith');
  1260. $this->assertNotEmpty($validator->errors(['username' => 'foo']));
  1261. }
  1262. /**
  1263. * Tests the containsNonAlphaNumeric proxy method
  1264. *
  1265. * @return void
  1266. */
  1267. public function testContainsNonAlphaNumeric()
  1268. {
  1269. $validator = new Validator();
  1270. $this->assertProxyMethod($validator, 'containsNonAlphaNumeric', 2, [2]);
  1271. $this->assertNotEmpty($validator->errors(['username' => '$']));
  1272. }
  1273. /**
  1274. * Tests the date proxy method
  1275. *
  1276. * @return void
  1277. */
  1278. public function testDate()
  1279. {
  1280. $validator = new Validator();
  1281. $this->assertProxyMethod($validator, 'date', ['ymd'], [['ymd']]);
  1282. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1283. }
  1284. /**
  1285. * Tests the dateTime proxy method
  1286. *
  1287. * @return void
  1288. */
  1289. public function testDateTime()
  1290. {
  1291. $validator = new Validator();
  1292. $this->assertProxyMethod($validator, 'dateTime', ['ymd'], [['ymd']], 'datetime');
  1293. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1294. }
  1295. /**
  1296. * Tests the time proxy method
  1297. *
  1298. * @return void
  1299. */
  1300. public function testTime()
  1301. {
  1302. $validator = new Validator();
  1303. $this->assertProxyMethod($validator, 'time');
  1304. $this->assertNotEmpty($validator->errors(['username' => 'not a time']));
  1305. }
  1306. /**
  1307. * Tests the localizedTime proxy method
  1308. *
  1309. * @return void
  1310. */
  1311. public function testLocalizedTime()
  1312. {
  1313. $validator = new Validator();
  1314. $this->assertProxyMethod($validator, 'localizedTime', 'date', ['date']);
  1315. $this->assertNotEmpty($validator->errors(['username' => 'not a date']));
  1316. }
  1317. /**
  1318. * Tests the boolean proxy method
  1319. *
  1320. * @return void
  1321. */
  1322. public function testBoolean()
  1323. {
  1324. $validator = new Validator();
  1325. $this->assertProxyMethod($validator, 'boolean');
  1326. $this->assertNotEmpty($validator->errors(['username' => 'not a boolean']));
  1327. }
  1328. /**
  1329. * Tests the decimal proxy method
  1330. *
  1331. * @return void
  1332. */
  1333. public function testDecimal()
  1334. {
  1335. $validator = new Validator();
  1336. $this->assertProxyMethod($validator, 'decimal', 2, [2]);
  1337. $this->assertNotEmpty($validator->errors(['username' => 10.1]));
  1338. }
  1339. /**
  1340. * Tests the ip proxy methods
  1341. *
  1342. * @return void
  1343. */
  1344. public function testIps()
  1345. {
  1346. $validator = new Validator();
  1347. $this->assertProxyMethod($validator, 'ip');
  1348. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1349. $this->assertProxyMethod($validator, 'ipv4', null, ['ipv4'], 'ip');
  1350. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1351. $this->assertProxyMethod($validator, 'ipv6', null, ['ipv6'], 'ip');
  1352. $this->assertNotEmpty($validator->errors(['username' => 'not ip']));
  1353. }
  1354. /**
  1355. * Tests the minLength proxy method
  1356. *
  1357. * @return void
  1358. */
  1359. public function testMinLength()
  1360. {
  1361. $validator = new Validator();
  1362. $this->assertProxyMethod($validator, 'minLength', 2, [2]);
  1363. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1364. }
  1365. /**
  1366. * Tests the maxLength proxy method
  1367. *
  1368. * @return void
  1369. */
  1370. public function testMaxLength()
  1371. {
  1372. $validator = new Validator();
  1373. $this->assertProxyMethod($validator, 'maxLength', 2, [2]);
  1374. $this->assertNotEmpty($validator->errors(['username' => 'aaa']));
  1375. }
  1376. /**
  1377. * Tests the numeric proxy method
  1378. *
  1379. * @return void
  1380. */
  1381. public function testNumeric()
  1382. {
  1383. $validator = new Validator();
  1384. $this->assertProxyMethod($validator, 'numeric');
  1385. $this->assertEmpty($validator->errors(['username' => '22']));
  1386. $this->assertNotEmpty($validator->errors(['username' => 'a']));
  1387. }
  1388. /**
  1389. * Tests the naturalNumber proxy method
  1390. *
  1391. * @return void
  1392. */
  1393. public function testNaturalNumber()
  1394. {
  1395. $validator = new Validator();
  1396. $this->assertProxyMethod($validator, 'naturalNumber', null, [false]);
  1397. $this->assertNotEmpty($validator->errors(['username' => 0]));
  1398. }
  1399. /**
  1400. * Tests the nonNegativeInteger proxy method
  1401. *
  1402. * @return void
  1403. */
  1404. public function testNonNegativeInteger()
  1405. {
  1406. $validator = new Validator();
  1407. $this->assertProxyMethod($validator, 'nonNegativeInteger', null, [true], 'naturalNumber');
  1408. $this->assertNotEmpty($validator->errors(['username' => -1]));
  1409. }
  1410. /**
  1411. * Tests the range proxy method
  1412. *
  1413. * @return void
  1414. */
  1415. public function testRange()
  1416. {
  1417. $validator = new Validator();
  1418. $this->assertProxyMethod($validator, 'range', [1, 4], [1, 4]);
  1419. $this->assertNotEmpty($validator->errors(['username' => 5]));
  1420. }
  1421. /**
  1422. * Tests the range failure case
  1423. *
  1424. * @expectedException InvalidArgumentException
  1425. * @return void
  1426. */
  1427. public function testRangeFailure()
  1428. {
  1429. $validator = new Validator();
  1430. $validator->range('username', [1]);
  1431. }
  1432. /**
  1433. * Tests the url proxy method
  1434. *
  1435. * @return void
  1436. */
  1437. public function testUrl()
  1438. {
  1439. $validator = new Validator();
  1440. $this->assertProxyMethod($validator, 'url', null, [false]);
  1441. $this->assertNotEmpty($validator->errors(['username' => 'not url']));
  1442. }
  1443. /**
  1444. * Tests the urlWithProtocol proxy method
  1445. *
  1446. * @return void
  1447. */
  1448. public function testUrlWithProtocol()
  1449. {
  1450. $validator = new Validator();
  1451. $this->assertProxyMethod($validator, 'urlWithProtocol', null, [true], 'url');
  1452. $this->assertNotEmpty($validator->errors(['username' => 'google.com']));
  1453. }
  1454. /**
  1455. * Tests the inList proxy method
  1456. *
  1457. * @return void
  1458. */
  1459. public function testInList()
  1460. {
  1461. $validator = new Validator();
  1462. $this->assertProxyMethod($validator, 'inList', ['a', 'b'], [['a', 'b']]);
  1463. $this->assertNotEmpty($validator->errors(['username' => 'c']));
  1464. }
  1465. /**
  1466. * Tests the uuid proxy method
  1467. *
  1468. * @return void
  1469. */
  1470. public function testUuid()
  1471. {
  1472. $validator = new Validator();
  1473. $this->assertProxyMethod($validator, 'uuid');
  1474. $this->assertNotEmpty($validator->errors(['username' => 'not uuid']));
  1475. }
  1476. /**
  1477. * Tests the uploadedFile proxy method
  1478. *
  1479. * @return void
  1480. */
  1481. public function testUploadedFile()
  1482. {
  1483. $validator = new Validator();
  1484. $this->assertProxyMethod($validator, 'uploadedFile', ['foo' => 'bar'], [['foo' => 'bar']]);
  1485. $this->assertNotEmpty($validator->errors(['username' => []]));
  1486. }
  1487. /**
  1488. * Tests the latlog proxy methods
  1489. *
  1490. * @return void
  1491. */
  1492. public function testLatLong()
  1493. {
  1494. $validator = new Validator();
  1495. $this->assertProxyMethod($validator, 'latLong', null, [], 'geoCoordinate');
  1496. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1497. $this->assertProxyMethod($validator, 'latitude');
  1498. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1499. $this->assertProxyMethod($validator, 'longitude');
  1500. $this->assertNotEmpty($validator->errors(['username' => 2000]));
  1501. }
  1502. /**
  1503. * Tests the ascii proxy method
  1504. *
  1505. * @return void
  1506. */
  1507. public function testAscii()
  1508. {
  1509. $validator = new Validator();
  1510. $this->assertProxyMethod($validator, 'ascii');
  1511. $this->assertNotEmpty($validator->errors(['username' => 'ü']));
  1512. }
  1513. /**
  1514. * Tests the utf8 proxy methods
  1515. *
  1516. * @return void
  1517. */
  1518. public function testUtf8()
  1519. {
  1520. // Grinning face
  1521. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  1522. $validator = new Validator();
  1523. $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]);
  1524. $this->assertEmpty($validator->errors(['username' => 'ü']));
  1525. $this->assertNotEmpty($validator->errors(['username' => $extended]));
  1526. }
  1527. /**
  1528. * Test utf8extended proxy method.
  1529. *
  1530. * @return void
  1531. */
  1532. public function testUtf8Extended()
  1533. {
  1534. // Grinning face
  1535. $extended = 'some' . "\xf0\x9f\x98\x80" . 'value';
  1536. $validator = new Validator();
  1537. $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8');
  1538. $this->assertEmpty($validator->errors(['username' => 'ü']));
  1539. $this->assertEmpty($validator->errors(['username' => $extended]));
  1540. }
  1541. /**
  1542. * Tests the email proxy method
  1543. *
  1544. * @return void
  1545. */
  1546. public function testEmail()
  1547. {
  1548. $validator = new Validator();
  1549. $validator->email('username');
  1550. $this->assertEmpty($validator->errors(['username' => 'test@example.com']));
  1551. $this->assertNotEmpty($validator->errors(['username' => 'not an email']));
  1552. }
  1553. /**
  1554. * Tests the integer proxy method
  1555. *
  1556. * @return void
  1557. */
  1558. public function testInteger()
  1559. {
  1560. $validator = new Validator();
  1561. $this->assertProxyMethod($validator, 'integer', null, [], 'isInteger');
  1562. $this->assertNotEmpty($validator->errors(['username' => 'not integer']));
  1563. }
  1564. /**
  1565. * Tests the isArray proxy method
  1566. */
  1567. public function testIsArray()
  1568. {
  1569. $validator = new Validator();
  1570. $validator->isArray('username');
  1571. $this->assertEmpty($validator->errors(['username' => [1, 2, 3]]));
  1572. $this->assertNotEmpty($validator->errors(['username' => 'is not an array']));
  1573. }
  1574. /**
  1575. * Tests the multiple proxy method
  1576. *
  1577. * @return void
  1578. */
  1579. public function testMultiple()
  1580. {
  1581. $validator = new Validator();
  1582. $this->assertProxyMethod(
  1583. $validator,
  1584. 'multipleOptions',
  1585. ['min' => 1, 'caseInsensitive' => true],
  1586. [['min' => 1], false],
  1587. 'multiple'
  1588. );
  1589. $this->assertNotEmpty($validator->errors(['username' => '']));
  1590. }
  1591. /**
  1592. * Tests the hasAtLeast method
  1593. *
  1594. * @return void
  1595. */
  1596. public function testHasAtLeast()
  1597. {
  1598. $validator = new Validator();
  1599. $validator->hasAtLeast('things', 3);
  1600. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  1601. $this->assertEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  1602. $this->assertNotEmpty($validator->errors(['things' => [1, 2]]));
  1603. $this->assertNotEmpty($validator->errors(['things' => []]));
  1604. $this->assertNotEmpty($validator->errors(['things' => 'string']));
  1605. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  1606. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  1607. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  1608. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => []]]));
  1609. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => 'string']]));
  1610. }
  1611. /**
  1612. * Tests the hasAtMost method
  1613. *
  1614. * @return void
  1615. */
  1616. public function testHasAtMost()
  1617. {
  1618. $validator = new Validator();
  1619. $validator->hasAtMost('things', 3);
  1620. $this->assertEmpty($validator->errors(['things' => [1, 2, 3]]));
  1621. $this->assertEmpty($validator->errors(['things' => [1]]));
  1622. $this->assertNotEmpty($validator->errors(['things' => [1, 2, 3, 4]]));
  1623. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3]]]));
  1624. $this->assertEmpty($validator->errors(['things' => ['_ids' => [1, 2]]]));
  1625. $this->assertNotEmpty($validator->errors(['things' => ['_ids' => [1, 2, 3, 4]]]));
  1626. }
  1627. /**
  1628. * Tests that a rule in the Validator class exists and was configured as expected.
  1629. *
  1630. * @param Validator $validator
  1631. * @param string $method
  1632. * @param mixed $extra
  1633. * @param array $pass
  1634. * @param string|null $name
  1635. */
  1636. protected function assertProxyMethod($validator, $method, $extra = null, $pass = [], $name = null)
  1637. {
  1638. $name = $name ?: $method;
  1639. if ($extra !== null) {
  1640. $this->assertSame($validator, $validator->{$method}('username', $extra));
  1641. } else {
  1642. $this->assertSame($validator, $validator->{$method}('username'));
  1643. }
  1644. $rule = $validator->field('username')->rule($method);
  1645. $this->assertNotEmpty($rule, "Rule was not found for $method");
  1646. $this->assertNull($rule->get('message'), 'Message is present when it should not be');
  1647. $this->assertNull($rule->get('on'), 'On clause is present when it should not be');
  1648. $this->assertEquals($name, $rule->get('rule'), 'Rule name does not match');
  1649. $this->assertEquals($pass, $rule->get('pass'), 'Passed options are different');
  1650. $this->assertEquals('default', $rule->get('provider'), 'Provider does not match');
  1651. if ($extra !== null) {
  1652. $validator->{$method}('username', $extra, 'the message', 'create');
  1653. } else {
  1654. $validator->{$method}('username', 'the message', 'create');
  1655. }
  1656. $rule = $validator->field('username')->rule($method);
  1657. $this->assertEquals('the message', $rule->get('message'), 'Error messages are not the same');
  1658. $this->assertEquals('create', $rule->get('on'), 'On clause is wrong');
  1659. }
  1660. }