ValidationRuleParsingTest.php 23 KB

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