ValidationRuleParsingTest.php 22 KB

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