ValidationRuleParsingTest.php 20 KB

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