ValidationRuleParsingTest.php 26 KB

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