ValidationRuleParsingTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. namespace Knuckles\Scribe\Tests\Unit;
  3. use Illuminate\Foundation\Application;
  4. use Illuminate\Support\Facades\Validator;
  5. use Illuminate\Validation\Rule;
  6. use Illuminate\Validation\ValidationException;
  7. use Knuckles\Scribe\Extracting\ParsesValidationRules;
  8. use Knuckles\Scribe\Tests\BaseLaravelTest;
  9. use Knuckles\Scribe\Tools\DocumentationConfig;
  10. class ValidationRuleParsingTest extends BaseLaravelTest
  11. {
  12. private $strategy;
  13. public function __construct(?string $name = null, array $data = [], $dataName = '')
  14. {
  15. parent::__construct($name, $data, $dataName);
  16. $this->strategy = new class {
  17. use ParsesValidationRules;
  18. public function parse($validationRules, $customParameterData = []): array
  19. {
  20. $this->config = new DocumentationConfig([]);
  21. $bodyParametersFromValidationRules = $this->getParametersFromValidationRules($validationRules, $customParameterData);
  22. return $this->normaliseArrayAndObjectParameters($bodyParametersFromValidationRules);
  23. }
  24. };
  25. }
  26. /**
  27. * @test
  28. * @dataProvider supportedRules
  29. */
  30. public function can_parse_supported_rules(array $ruleset, array $customInfo, array $expected)
  31. {
  32. $results = $this->strategy->parse($ruleset, $customInfo);
  33. $parameterName = array_keys($ruleset)[0];
  34. $this->assertEquals($expected['description'], $results[$parameterName]['description']);
  35. if (isset($expected['type'])) {
  36. $this->assertEquals($expected['type'], $results[$parameterName]['type']);
  37. }
  38. // Validate that the generated values actually pass validation
  39. $exampleData = [$parameterName => $results[$parameterName]['example']];
  40. $validator = Validator::make($exampleData, $ruleset);
  41. try {
  42. $validator->validate();
  43. } catch (ValidationException $e) {
  44. dump('Rules: ', $ruleset);
  45. dump('Generated value: ', $exampleData[$parameterName]);
  46. dump($e->errors());
  47. $this->fail("Generated example data from validation rule failed to match actual.");
  48. }
  49. }
  50. /** @test */
  51. public function can_parse_rule_objects()
  52. {
  53. $results = $this->strategy->parse([
  54. 'in_param' => ['numeric', Rule::in([3,5,6])]
  55. ]);
  56. $this->assertEquals(
  57. 'Must be one of <code>3</code>, <code>5</code>, or <code>6</code>.',
  58. $results['in_param']['description']
  59. );
  60. }
  61. /** @test */
  62. public function can_transform_arrays_and_objects()
  63. {
  64. $ruleset = [
  65. 'array_param' => 'array|required',
  66. 'array_param.*' => 'string',
  67. ];
  68. $results = $this->strategy->parse($ruleset);
  69. $this->assertCount(1, $results);
  70. $this->assertEquals('string[]', $results['array_param']['type']);
  71. $ruleset = [
  72. 'object_param' => 'array|required',
  73. 'object_param.field1.*' => 'string',
  74. 'object_param.field2' => 'integer|required',
  75. ];
  76. $results = $this->strategy->parse($ruleset);
  77. $this->assertCount(3, $results);
  78. $this->assertEquals('object', $results['object_param']['type']);
  79. $this->assertEquals('string[]', $results['object_param.field1']['type']);
  80. $this->assertEquals('integer', $results['object_param.field2']['type']);
  81. $ruleset = [
  82. 'array_of_objects_with_array.*.another.*.one.field1.*' => 'string|required',
  83. 'array_of_objects_with_array.*.another.*.one.field2' => 'integer',
  84. 'array_of_objects_with_array.*.another.*.two.field2' => 'numeric',
  85. ];
  86. $results = $this->strategy->parse($ruleset);
  87. $this->assertCount(7, $results);
  88. $this->assertEquals('object[]', $results['array_of_objects_with_array']['type']);
  89. $this->assertEquals('object[]', $results['array_of_objects_with_array[].another']['type']);
  90. $this->assertEquals('object', $results['array_of_objects_with_array[].another[].one']['type']);
  91. $this->assertEquals('object', $results['array_of_objects_with_array[].another[].two']['type']);
  92. $this->assertEquals('string[]', $results['array_of_objects_with_array[].another[].one.field1']['type']);
  93. $this->assertEquals('integer', $results['array_of_objects_with_array[].another[].one.field2']['type']);
  94. $this->assertEquals('number', $results['array_of_objects_with_array[].another[].two.field2']['type']);
  95. }
  96. public function supportedRules()
  97. {
  98. $description = 'A description';
  99. // Key is just an identifier
  100. // First array in each key is the validation ruleset,
  101. // Second is custom information (from bodyParameters() or comments)
  102. // Third is expected result
  103. yield 'string' => [
  104. ['string_param' => 'string'],
  105. ['string_param' => ['description' => $description]],
  106. [
  107. 'type' => 'string',
  108. 'description' => $description . ".",
  109. ],
  110. ];
  111. yield 'boolean' => [
  112. ['boolean_param' => 'boolean'],
  113. [],
  114. [
  115. 'type' => 'boolean',
  116. 'description' => "",
  117. ],
  118. ];
  119. yield 'integer' => [
  120. ['integer_param' => 'integer'],
  121. [],
  122. [
  123. 'type' => 'integer',
  124. 'description' => "",
  125. ],
  126. ];
  127. yield 'numeric' => [
  128. ['numeric_param' => 'numeric'],
  129. ['numeric_param' => ['description' => $description]],
  130. [
  131. 'type' => 'number',
  132. 'description' => $description . ".",
  133. ],
  134. ];
  135. yield 'file' => [
  136. ['file_param' => 'file|required'],
  137. ['file_param' => ['description' => $description]],
  138. [
  139. 'description' => "$description. Must be a file.",
  140. 'type' => 'file',
  141. ],
  142. ];
  143. yield 'image' => [
  144. ['image_param' => 'image|required'],
  145. [],
  146. [
  147. 'description' => "Must be an image.",
  148. 'type' => 'file',
  149. ],
  150. ];
  151. yield 'timezone' => [
  152. ['timezone_param' => 'timezone|required'],
  153. [],
  154. [
  155. 'description' => 'Must be a valid time zone, such as <code>Africa/Accra</code>.',
  156. 'type' => 'string',
  157. ],
  158. ];
  159. yield 'email' => [
  160. ['email_param' => 'email|required'],
  161. [],
  162. [
  163. 'description' => 'Must be a valid email address.',
  164. 'type' => 'string',
  165. ],
  166. ];
  167. yield 'url' => [
  168. ['url_param' => 'url|required'],
  169. ['url_param' => ['description' => $description]],
  170. [
  171. 'description' => "$description. Must be a valid URL.",
  172. 'type' => 'string',
  173. ],
  174. ];
  175. yield 'ip' => [
  176. ['ip_param' => 'ip|required'],
  177. ['ip_param' => ['description' => $description]],
  178. [
  179. 'description' => "$description. Must be a valid IP address.",
  180. 'type' => 'string',
  181. ],
  182. ];
  183. yield 'json' => [
  184. ['json_param' => 'json|required'],
  185. ['json_param' => []],
  186. [
  187. 'description' => 'Must be a valid JSON string.',
  188. 'type' => 'string',
  189. ],
  190. ];
  191. yield 'date' => [
  192. ['date_param' => 'date|required'],
  193. [],
  194. [
  195. 'description' => 'Must be a valid date.',
  196. 'type' => 'string',
  197. ],
  198. ];
  199. yield 'date_format' => [
  200. ['date_format_param' => 'date_format:Y-m-d|required'],
  201. ['date_format_param' => ['description' => $description]],
  202. [
  203. 'description' => "$description. Must be a valid date in the format <code>Y-m-d</code>.",
  204. 'type' => 'string',
  205. ],
  206. ];
  207. yield 'in' => [
  208. ['in_param' => 'in:3,5,6'],
  209. ['in_param' => ['description' => $description]],
  210. [
  211. 'description' => "$description. Must be one of <code>3</code>, <code>5</code>, or <code>6</code>.",
  212. 'type' => 'string',
  213. ],
  214. ];
  215. yield 'not_in' => [
  216. ['not_param' => 'not_in:3,5,6'],
  217. [],
  218. [
  219. 'description' => "Must not be one of <code>3</code>, <code>5</code>, or <code>6</code>.",
  220. ],
  221. ];
  222. yield 'digits' => [
  223. ['digits_param' => 'digits:8'],
  224. [],
  225. [
  226. 'description' => "Must be 8 digits.",
  227. 'type' => 'string',
  228. ],
  229. ];
  230. yield 'digits_between' => [
  231. ['digits_between_param' => 'digits_between:2,8'],
  232. [],
  233. [
  234. 'description' => "Must be between 2 and 8 digits.",
  235. 'type' => 'string',
  236. ],
  237. ];
  238. yield 'alpha' => [
  239. ['alpha_param' => 'alpha'],
  240. [],
  241. [
  242. 'description' => "Must contain only letters.",
  243. 'type' => 'string',
  244. ],
  245. ];
  246. yield 'alpha_dash' => [
  247. ['alpha_dash_param' => 'alpha_dash'],
  248. [],
  249. [
  250. 'description' => "Must contain only letters, numbers, dashes and underscores.",
  251. 'type' => 'string',
  252. ],
  253. ];
  254. yield 'alpha_num' => [
  255. ['alpha_num_param' => 'alpha_num'],
  256. [],
  257. [
  258. 'description' => "Must contain only letters and numbers.",
  259. 'type' => 'string',
  260. ],
  261. ];
  262. yield 'ends_with' => [
  263. ['ends_with_param' => 'ends_with:go,ha'],
  264. [],
  265. [
  266. 'description' => "Must end with one of <code>go</code> or <code>ha</code>.",
  267. 'type' => 'string',
  268. ],
  269. ];
  270. yield 'starts_with' => [
  271. ['starts_with_param' => 'starts_with:go,ha'],
  272. [],
  273. [
  274. 'description' => "Must start with one of <code>go</code> or <code>ha</code>.",
  275. 'type' => 'string',
  276. ],
  277. ];
  278. yield 'uuid' => [
  279. ['uuid_param' => 'uuid'],
  280. [],
  281. [
  282. 'description' => "Must be a valid UUID.",
  283. 'type' => 'string',
  284. ],
  285. ];
  286. yield 'required_if' => [
  287. ['required_if_param' => 'required_if:another_field,a_value'],
  288. [],
  289. ['description' => "This field is required when <code>another_field</code> is <code>a_value</code>."],
  290. ];
  291. yield 'required_unless' => [
  292. ['required_unless_param' => 'string|required_unless:another_field,a_value'],
  293. [],
  294. ['description' => "This field is required unless <code>another_field</code> is in <code>a_value</code>."],
  295. ];
  296. yield 'required_with' => [
  297. ['required_with_param' => 'required_with:another_field,some_other_field'],
  298. [],
  299. ['description' => 'This field is required when <code>another_field</code> or <code>some_other_field</code> is present.'],
  300. ];
  301. yield 'required_with_all' => [
  302. ['required_with_all_param' => 'required_with_all:another_field,some_other_field'],
  303. [],
  304. ['description' => 'This field is required when <code>another_field</code> and <code>some_other_field</code> are present.'],
  305. ];
  306. yield 'required_without' => [
  307. ['required_without_param' => 'string|required_without:another_field,some_other_field'],
  308. [],
  309. ['description' => 'This field is required when <code>another_field</code> or <code>some_other_field</code> is not present.'],
  310. ];
  311. yield 'required_without_all' => [
  312. ['required_without_all_param' => 'string|required_without_all:another_field,some_other_field'],
  313. [],
  314. ['description' => 'This field is required when none of <code>another_field</code> and <code>some_other_field</code> are present.'],
  315. ];
  316. yield 'same' => [
  317. ['same_param' => 'same:other_field'],
  318. [],
  319. ['description' => "The value and <code>other_field</code> must match."],
  320. ];
  321. yield 'different' => [
  322. ['different_param' => 'string|different:other_field'],
  323. [],
  324. ['description' => "The value and <code>other_field</code> must be different."],
  325. ];
  326. yield 'after' => [
  327. ['after_param' => 'after:2020-02-12'],
  328. [],
  329. ['description' => "Must be a date after <code>2020-02-12</code>."],
  330. ];
  331. yield 'before_or_equal' => [
  332. ['before_or_equal_param' => 'before_or_equal:2020-02-12'],
  333. [],
  334. ['description' => "Must be a date before or equal to <code>2020-02-12</code>."],
  335. ];
  336. yield 'size (number)' => [
  337. ['size_param' => 'numeric|size:6'],
  338. [],
  339. ['description' => "Must be 6."],
  340. ];
  341. yield 'size (string)' => [
  342. ['size_param' => 'string|size:6'],
  343. [],
  344. ['description' => "Must be 6 characters."],
  345. ];
  346. yield 'size (file)' => [
  347. ['size_param' => 'file|size:6'],
  348. [],
  349. ['description' => "Must be a file. Must be 6 kilobytes."],
  350. ];
  351. yield 'max (number)' => [
  352. ['max_param' => 'numeric|max:6'],
  353. [],
  354. ['description' => "Must not be greater than 6."],
  355. ];
  356. yield 'max (string)' => [
  357. ['max_param' => 'string|max:6'],
  358. [],
  359. ['description' => "Must not be greater than 6 characters."],
  360. ];
  361. yield 'max (file)' => [
  362. ['max_param' => 'file|max:6'],
  363. [],
  364. ['description' => "Must be a file. Must not be greater than 6 kilobytes."],
  365. ];
  366. yield 'min (number)' => [
  367. ['min_param' => 'numeric|min:6'],
  368. [],
  369. ['description' => "Must be at least 6."],
  370. ];
  371. yield 'min (string)' => [
  372. ['min_param' => 'string|min:6'],
  373. [],
  374. ['description' => "Must be at least 6 characters."],
  375. ];
  376. yield 'min (file)' => [
  377. ['min_param' => 'file|min:6'],
  378. [],
  379. ['description' => "Must be a file. Must be at least 6 kilobytes."],
  380. ];
  381. yield 'between (number)' => [
  382. ['between_param' => 'numeric|between:1,2'],
  383. [],
  384. ['description' => "Must be between 1 and 2."],
  385. ];
  386. yield 'between (string)' => [
  387. ['between_param' => 'string|between:1,2'],
  388. [],
  389. ['description' => "Must be between 1 and 2 characters."],
  390. ];
  391. yield 'between (file)' => [
  392. ['between_param' => 'file|between:1,2'],
  393. [],
  394. ['description' => "Must be a file. Must be between 1 and 2 kilobytes."],
  395. ];
  396. yield 'regex' => [
  397. ['regex_param' => 'regex:/\d/'],
  398. [],
  399. ['description' => 'Must match the regex /\d/.'],
  400. ];
  401. yield 'accepted' => [
  402. ['accepted_param' => 'accepted'],
  403. [],
  404. [
  405. 'type' => 'boolean',
  406. 'description' => 'Must be accepted.',
  407. ],
  408. ];
  409. yield 'unsupported' => [
  410. ['unsupported_param' => [new DummyValidationRule, 'bail']],
  411. ['unsupported_param' => ['description' => $description]],
  412. ['description' => "$description."],
  413. ];
  414. if (version_compare(Application::VERSION, '8.53', '>=')) {
  415. yield 'accepted_if' => [
  416. ['accepted_if_param' => 'accepted_if:another_field,a_value'],
  417. [],
  418. [
  419. 'type' => 'boolean',
  420. 'description' => "Must be accepted when <code>another_field</code> is <code>a_value</code>.",
  421. ],
  422. ];
  423. }
  424. }
  425. /** @test */
  426. public function child_does_not_overwrite_parent_status()
  427. {
  428. $ruleset = [
  429. 'array_param' => 'array|required',
  430. 'array_param.*' => 'array|required',
  431. 'array_param.*.an_item' => 'string|required',
  432. ];
  433. $results = $this->strategy->parse($ruleset);
  434. $this->assertCount(2, $results);
  435. $this->assertEquals(true, $results['array_param']['required']);
  436. }
  437. /** @test */
  438. public function can_parse_custom_closure_rules()
  439. {
  440. // Single line DocComment
  441. $ruleset = [
  442. 'closure' => [
  443. 'bail', 'required',
  444. /** This is a single line parsed closure rule. */
  445. function ($attribute, $value, $fail) {
  446. $fail('Always fail.');
  447. },
  448. ],
  449. ];
  450. $results = $this->strategy->parse($ruleset);
  451. $this->assertEquals(
  452. 'This is a single line parsed closure rule.',
  453. $results['closure']['description']
  454. );
  455. // Block DocComment
  456. $ruleset = [
  457. 'closure' => [
  458. 'bail', 'required',
  459. /**
  460. * This is a block DocComment
  461. * parsed on a closure rule.
  462. * Extra info.
  463. */
  464. function ($attribute, $value, $fail) {
  465. $fail('Always fail.');
  466. },
  467. ],
  468. ];
  469. $results = $this->strategy->parse($ruleset);
  470. $this->assertEquals(
  471. 'This is a block DocComment parsed on a closure rule. Extra info.',
  472. $results['closure']['description']
  473. );
  474. }
  475. /** @test */
  476. public function can_parse_custom_rule_classes()
  477. {
  478. $ruleset = [
  479. // The page number. Example: 1
  480. 'custom_rule' => ['bail', 'required', new DummyWithDocsValidationRule],
  481. ];
  482. $results = $this->strategy->parse($ruleset);
  483. $this->assertEquals(true, $results['custom_rule']['required']);
  484. $this->assertEquals('This is a dummy test rule.', $results['custom_rule']['description']);
  485. }
  486. }
  487. class DummyValidationRule implements \Illuminate\Contracts\Validation\Rule
  488. {
  489. public function passes($attribute, $value)
  490. {
  491. return true;
  492. }
  493. public function message()
  494. {
  495. return '.';
  496. }
  497. }
  498. class DummyWithDocsValidationRule implements \Illuminate\Contracts\Validation\Rule
  499. {
  500. public function passes($attribute, $value)
  501. {
  502. return true;
  503. }
  504. public function message()
  505. {
  506. return '.';
  507. }
  508. public static function docs()
  509. {
  510. return [
  511. 'description' => 'This is a dummy test rule.',
  512. 'example' => 'Default example, only added if none other give.',
  513. ];
  514. }
  515. }