ValidationRuleParsingTest.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. }
  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.".",
  215. 'type' => 'string',
  216. 'enumValues' => [3,5,6]
  217. ],
  218. ];
  219. yield 'not_in' => [
  220. ['not_param' => 'not_in:3,5,6'],
  221. [],
  222. [
  223. 'description' => "Must not be one of <code>3</code>, <code>5</code>, or <code>6</code>.",
  224. ],
  225. ];
  226. yield 'digits' => [
  227. ['digits_param' => 'digits:8'],
  228. [],
  229. [
  230. 'description' => "Must be 8 digits.",
  231. 'type' => 'string',
  232. ],
  233. ];
  234. yield 'digits_between' => [
  235. ['digits_between_param' => 'digits_between:2,8'],
  236. [],
  237. [
  238. 'description' => "Must be between 2 and 8 digits.",
  239. 'type' => 'string',
  240. ],
  241. ];
  242. yield 'alpha' => [
  243. ['alpha_param' => 'alpha'],
  244. [],
  245. [
  246. 'description' => "Must contain only letters.",
  247. 'type' => 'string',
  248. ],
  249. ];
  250. yield 'alpha_dash' => [
  251. ['alpha_dash_param' => 'alpha_dash'],
  252. [],
  253. [
  254. 'description' => "Must contain only letters, numbers, dashes and underscores.",
  255. 'type' => 'string',
  256. ],
  257. ];
  258. yield 'alpha_num' => [
  259. ['alpha_num_param' => 'alpha_num'],
  260. [],
  261. [
  262. 'description' => "Must contain only letters and numbers.",
  263. 'type' => 'string',
  264. ],
  265. ];
  266. yield 'ends_with' => [
  267. ['ends_with_param' => 'ends_with:go,ha'],
  268. [],
  269. [
  270. 'description' => "Must end with one of <code>go</code> or <code>ha</code>.",
  271. 'type' => 'string',
  272. ],
  273. ];
  274. yield 'starts_with' => [
  275. ['starts_with_param' => 'starts_with:go,ha'],
  276. [],
  277. [
  278. 'description' => "Must start with one of <code>go</code> or <code>ha</code>.",
  279. 'type' => 'string',
  280. ],
  281. ];
  282. yield 'uuid' => [
  283. ['uuid_param' => 'uuid'],
  284. [],
  285. [
  286. 'description' => "Must be a valid UUID.",
  287. 'type' => 'string',
  288. ],
  289. ];
  290. yield 'required_if' => [
  291. ['required_if_param' => 'required_if:another_field,a_value'],
  292. [],
  293. ['description' => "This field is required when <code>another_field</code> is <code>a_value</code>."],
  294. ];
  295. yield 'required_unless' => [
  296. ['required_unless_param' => 'string|required_unless:another_field,a_value'],
  297. [],
  298. ['description' => "This field is required unless <code>another_field</code> is in <code>a_value</code>."],
  299. ];
  300. yield 'required_with' => [
  301. ['required_with_param' => 'required_with:another_field,some_other_field'],
  302. [],
  303. ['description' => 'This field is required when <code>another_field</code> or <code>some_other_field</code> is present.'],
  304. ];
  305. yield 'required_with_all' => [
  306. ['required_with_all_param' => 'required_with_all:another_field,some_other_field'],
  307. [],
  308. ['description' => 'This field is required when <code>another_field</code> and <code>some_other_field</code> are present.'],
  309. ];
  310. yield 'required_without' => [
  311. ['required_without_param' => 'string|required_without:another_field,some_other_field'],
  312. [],
  313. ['description' => 'This field is required when <code>another_field</code> or <code>some_other_field</code> is not present.'],
  314. ];
  315. yield 'required_without_all' => [
  316. ['required_without_all_param' => 'string|required_without_all:another_field,some_other_field'],
  317. [],
  318. ['description' => 'This field is required when none of <code>another_field</code> and <code>some_other_field</code> are present.'],
  319. ];
  320. yield 'same' => [
  321. ['same_param' => 'same:other_field'],
  322. [],
  323. ['description' => "The value and <code>other_field</code> must match."],
  324. ];
  325. yield 'different' => [
  326. ['different_param' => 'string|different:other_field'],
  327. [],
  328. ['description' => "The value and <code>other_field</code> must be different."],
  329. ];
  330. yield 'after' => [
  331. ['after_param' => 'after:2020-02-12'],
  332. [],
  333. ['description' => "Must be a date after <code>2020-02-12</code>."],
  334. ];
  335. yield 'before_or_equal' => [
  336. ['before_or_equal_param' => 'before_or_equal:2020-02-12'],
  337. [],
  338. ['description' => "Must be a date before or equal to <code>2020-02-12</code>."],
  339. ];
  340. yield 'size (number)' => [
  341. ['size_param' => 'numeric|size:6'],
  342. [],
  343. ['description' => "Must be 6."],
  344. ];
  345. yield 'size (string)' => [
  346. ['size_param' => 'string|size:6'],
  347. [],
  348. ['description' => "Must be 6 characters."],
  349. ];
  350. yield 'size (file)' => [
  351. ['size_param' => 'file|size:6'],
  352. [],
  353. ['description' => "Must be a file. Must be 6 kilobytes."],
  354. ];
  355. yield 'max (number)' => [
  356. ['max_param' => 'numeric|max:6'],
  357. [],
  358. ['description' => "Must not be greater than 6."],
  359. ];
  360. yield 'max (string)' => [
  361. ['max_param' => 'string|max:6'],
  362. [],
  363. ['description' => "Must not be greater than 6 characters."],
  364. ];
  365. yield 'max (file)' => [
  366. ['max_param' => 'file|max:6'],
  367. [],
  368. ['description' => "Must be a file. Must not be greater than 6 kilobytes."],
  369. ];
  370. yield 'min (number)' => [
  371. ['min_param' => 'numeric|min:6'],
  372. [],
  373. ['description' => "Must be at least 6."],
  374. ];
  375. yield 'min (string)' => [
  376. ['min_param' => 'string|min:6'],
  377. [],
  378. ['description' => "Must be at least 6 characters."],
  379. ];
  380. yield 'min (file)' => [
  381. ['min_param' => 'file|min:6'],
  382. [],
  383. ['description' => "Must be a file. Must be at least 6 kilobytes."],
  384. ];
  385. yield 'between (number)' => [
  386. ['between_param' => 'numeric|between:1,2'],
  387. [],
  388. ['description' => "Must be between 1 and 2."],
  389. ];
  390. yield 'between (string)' => [
  391. ['between_param' => 'string|between:1,2'],
  392. [],
  393. ['description' => "Must be between 1 and 2 characters."],
  394. ];
  395. yield 'between (file)' => [
  396. ['between_param' => 'file|between:1,2'],
  397. [],
  398. ['description' => "Must be a file. Must be between 1 and 2 kilobytes."],
  399. ];
  400. yield 'regex' => [
  401. ['regex_param' => 'regex:/\d/'],
  402. [],
  403. ['description' => 'Must match the regex /\d/.'],
  404. ];
  405. yield 'accepted' => [
  406. ['accepted_param' => 'accepted'],
  407. [],
  408. [
  409. 'type' => 'boolean',
  410. 'description' => 'Must be accepted.',
  411. ],
  412. ];
  413. yield 'unsupported' => [
  414. ['unsupported_param' => [new DummyValidationRule, 'bail']],
  415. ['unsupported_param' => ['description' => $description]],
  416. ['description' => "$description."],
  417. ];
  418. if (version_compare(Application::VERSION, '8.53', '>=')) {
  419. yield 'accepted_if' => [
  420. ['accepted_if_param' => 'accepted_if:another_field,a_value'],
  421. [],
  422. [
  423. 'type' => 'boolean',
  424. 'description' => "Must be accepted when <code>another_field</code> is <code>a_value</code>.",
  425. ],
  426. ];
  427. }
  428. }
  429. /** @test */
  430. public function child_does_not_overwrite_parent_status()
  431. {
  432. $ruleset = [
  433. 'array_param' => 'array|required',
  434. 'array_param.*' => 'array|required',
  435. 'array_param.*.an_item' => 'string|required',
  436. ];
  437. $results = $this->strategy->parse($ruleset);
  438. $this->assertCount(2, $results);
  439. $this->assertEquals(true, $results['array_param']['required']);
  440. }
  441. /** @test */
  442. public function can_parse_custom_closure_rules()
  443. {
  444. // Single line DocComment
  445. $ruleset = [
  446. 'closure' => [
  447. 'bail', 'required',
  448. /** This is a single line parsed closure rule. */
  449. function ($attribute, $value, $fail) {
  450. $fail('Always fail.');
  451. },
  452. ],
  453. ];
  454. $results = $this->strategy->parse($ruleset);
  455. $this->assertEquals(
  456. 'This is a single line parsed closure rule.',
  457. $results['closure']['description']
  458. );
  459. // Block DocComment
  460. $ruleset = [
  461. 'closure' => [
  462. 'bail', 'required',
  463. /**
  464. * This is a block DocComment
  465. * parsed on a closure rule.
  466. * Extra info.
  467. */
  468. function ($attribute, $value, $fail) {
  469. $fail('Always fail.');
  470. },
  471. ],
  472. ];
  473. $results = $this->strategy->parse($ruleset);
  474. $this->assertEquals(
  475. 'This is a block DocComment parsed on a closure rule. Extra info.',
  476. $results['closure']['description']
  477. );
  478. }
  479. /** @test */
  480. public function can_parse_custom_rule_classes()
  481. {
  482. $ruleset = [
  483. 'param1' => ['bail', 'required', new DummyWithDocsValidationRule],
  484. ];
  485. global $invokableRulesSupported;
  486. if ($invokableRulesSupported) {
  487. $ruleset['param2'] = [new DummyInvokableValidationRule];
  488. }
  489. global $laravel10Rules;
  490. if ($laravel10Rules) {
  491. $ruleset['param3'] = [new DummyL10ValidationRule];
  492. }
  493. $results = $this->strategy->parse($ruleset);
  494. $this->assertEquals(true, $results['param1']['required']);
  495. $this->assertEquals('This is a dummy test rule.', $results['param1']['description']);
  496. if (isset($results['param2'])) $this->assertEquals('This rule is invokable.', $results['param2']['description']);
  497. if (isset($results['param3'])) $this->assertEquals('This is a custom rule.', $results['param3']['description']);
  498. }
  499. /** @test */
  500. public function can_parse_enum_rules()
  501. {
  502. if (phpversion() < 8.1) {
  503. $this->markTestSkipped('Enums are only supported in PHP 8.1 or later');
  504. }
  505. $results = $this->strategy->parse([
  506. 'enum' => ['required', Rule::enum(Fixtures\TestStringBackedEnum::class)],
  507. ]);
  508. $this->assertEquals('string', $results['enum']['type']);
  509. $this->assertEquals(
  510. ['red', 'green', 'blue'],
  511. $results['enum']['enumValues']
  512. );
  513. $this->assertTrue(in_array(
  514. $results['enum']['example'],
  515. array_map(fn ($case) => $case->value, Fixtures\TestStringBackedEnum::cases())
  516. ));
  517. $results = $this->strategy->parse([
  518. 'enum' => ['required', Rule::enum(Fixtures\TestIntegerBackedEnum::class)],
  519. ]);
  520. $this->assertEquals('integer', $results['enum']['type']);
  521. $this->assertEquals(
  522. [1, 2, 3],
  523. $results['enum']['enumValues']
  524. );
  525. $this->assertTrue(in_array(
  526. $results['enum']['example'],
  527. array_map(fn ($case) => $case->value, Fixtures\TestIntegerBackedEnum::cases())
  528. ));
  529. $results = $this->strategy->parse([
  530. 'enum' => ['required', Rule::enum(Fixtures\TestStringBackedEnum::class)],
  531. ], [
  532. 'enum' => ['description' => 'A description'],
  533. ]);
  534. $this->assertEquals('string', $results['enum']['type']);
  535. $this->assertEquals(
  536. 'A description.',
  537. $results['enum']['description']
  538. );
  539. $this->assertTrue(in_array(
  540. $results['enum']['example'],
  541. array_map(fn ($case) => $case->value, Fixtures\TestStringBackedEnum::cases())
  542. ));
  543. }
  544. }
  545. class DummyValidationRule implements \Illuminate\Contracts\Validation\Rule
  546. {
  547. public function passes($attribute, $value)
  548. {
  549. return true;
  550. }
  551. public function message()
  552. {
  553. return '.';
  554. }
  555. }
  556. class DummyWithDocsValidationRule implements \Illuminate\Contracts\Validation\Rule
  557. {
  558. public function passes($attribute, $value)
  559. {
  560. return true;
  561. }
  562. public function message()
  563. {
  564. return '.';
  565. }
  566. public static function docs()
  567. {
  568. return [
  569. 'description' => 'This is a dummy test rule.',
  570. 'example' => 'Default example, only added if none other give.',
  571. ];
  572. }
  573. }
  574. if ($invokableRulesSupported) {
  575. class DummyInvokableValidationRule implements \Illuminate\Contracts\Validation\InvokableRule
  576. {
  577. public function __invoke($attribute, $value, $fail)
  578. {
  579. if (strtoupper($value) !== $value) {
  580. $fail(':attribute must be uppercase.');
  581. }
  582. }
  583. public function docs()
  584. {
  585. return [
  586. 'description' => 'This rule is invokable.',
  587. ];
  588. }
  589. }
  590. }
  591. if ($laravel10Rules) {
  592. // Laravel 10 deprecated the previous Rule and InvokableRule classes for a single interface
  593. // (https://github.com/laravel/framework/pull/45954)
  594. class DummyL10ValidationRule implements \Illuminate\Contracts\Validation\ValidationRule
  595. {
  596. public function validate(string $attribute, mixed $value, \Closure $fail): void
  597. {
  598. if (strtoupper($value) !== $value) {
  599. $fail('The :attribute must be an attribute.');
  600. }
  601. }
  602. public static function docs()
  603. {
  604. return [
  605. 'description' => 'This is a custom rule.',
  606. ];
  607. }
  608. }
  609. }