ParsesValidationRules.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. <?php
  2. namespace Knuckles\Scribe\Extracting;
  3. use Illuminate\Contracts\Validation\Rule;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Str;
  7. use Knuckles\Scribe\Exceptions\CouldntProcessValidationRule;
  8. use Knuckles\Scribe\Exceptions\ProblemParsingValidationRules;
  9. use Knuckles\Scribe\Exceptions\ScribeException;
  10. use Knuckles\Scribe\Tools\ConsoleOutputUtils as c;
  11. use Knuckles\Scribe\Tools\WritingUtils as w;
  12. use Throwable;
  13. trait ParsesValidationRules
  14. {
  15. use ParamHelpers;
  16. public static \stdClass $MISSING_VALUE;
  17. public function getParametersFromValidationRules(array $validationRules, array $customParameterData = []): array
  18. {
  19. self::$MISSING_VALUE = new \stdClass();
  20. $validationRules = $this->normaliseRules($validationRules);
  21. $parameters = [];
  22. $dependentRules = [];
  23. foreach ($validationRules as $parameter => $ruleset) {
  24. try {
  25. if (count($customParameterData) && !isset($customParameterData[$parameter])) {
  26. c::debug($this->getMissingCustomDataMessage($parameter));
  27. }
  28. $userSpecifiedParameterInfo = $customParameterData[$parameter] ?? [];
  29. // Make sure the user-specified description comes first (and add full stops where needed).
  30. $description = $userSpecifiedParameterInfo['description'] ?? '';
  31. if (!empty($description) && !Str::endsWith($description, '.')) {
  32. $description .= '.';
  33. }
  34. $parameterData = [
  35. 'name' => $parameter,
  36. 'required' => false,
  37. 'type' => null,
  38. 'example' => self::$MISSING_VALUE,
  39. 'description' => $description,
  40. ];
  41. $dependentRules[$parameter] = [];
  42. // First, parse only "independent" rules
  43. foreach ($ruleset as $rule) {
  44. $parsed = $this->parseRule($rule, $parameterData, true);
  45. if (!$parsed) {
  46. $dependentRules[$parameter][] = $rule;
  47. }
  48. }
  49. $parameterData['description'] = trim($parameterData['description']);
  50. // Set a default type
  51. if (is_null($parameterData['type'])) {
  52. $parameterData['type'] = 'string';
  53. }
  54. $parameterData['name'] = $parameter;
  55. $parameters[$parameter] = $parameterData;
  56. } catch (Throwable $e) {
  57. if ($e instanceof ScribeException) {
  58. throw $e;
  59. }
  60. throw ProblemParsingValidationRules::forParam($parameter, $e);
  61. }
  62. }
  63. // Now parse any "dependent" rules and set examples. At this point, we should know all field's types.
  64. foreach ($dependentRules as $parameter => $ruleset) {
  65. try {
  66. $parameterData = $parameters[$parameter];
  67. $userSpecifiedParameterInfo = $customParameterData[$parameter] ?? [];
  68. foreach ($ruleset as $rule) {
  69. $this->parseRule($rule, $parameterData, false, $parameters);
  70. }
  71. // Make sure the user-specified example overwrites others.
  72. if (isset($userSpecifiedParameterInfo['example'])) {
  73. if ($this->shouldCastUserExample()) {
  74. // Examples in comments are strings, we need to cast them properly
  75. $parameterData['example'] = $this->castToType($userSpecifiedParameterInfo['example'], $parameterData['type'] ?? 'string');
  76. } else {
  77. $parameterData['example'] = $userSpecifiedParameterInfo['example'];
  78. }
  79. }
  80. // End descriptions with a full stop
  81. $parameterData['description'] = trim($parameterData['description']);
  82. if (!empty($parameterData['description']) && !Str::endsWith($parameterData['description'], '.')) {
  83. $parameterData['description'] .= '.';
  84. }
  85. $parameterData = $this->updateParameterExample($parameterData);
  86. $parameters[$parameter] = $parameterData;
  87. } catch (Throwable $e) {
  88. if ($e instanceof ScribeException) {
  89. throw $e;
  90. }
  91. throw ProblemParsingValidationRules::forParam($parameter, $e);
  92. }
  93. }
  94. return $parameters;
  95. }
  96. /**
  97. * Transform validation rules from:
  98. * 'param1' => 'int|required' TO 'param1' => ['int', 'required']
  99. *
  100. * @param array<string,string|string[]> $rules
  101. *
  102. * @return array
  103. */
  104. protected function normaliseRules(array $rules): array
  105. {
  106. // We can simply call Validator::make($data, $rules)->getRules() to get the normalised rules,
  107. // but Laravel will ignore any nested array rules (`ids.*')
  108. // unless the key referenced (`ids`) exists in the dataset and is a non-empty array
  109. // So we'll create a single-item array for each array parameter
  110. $testData = [];
  111. foreach ($rules as $key => $ruleset) {
  112. if (!Str::contains($key, '.*')) continue;
  113. // All we need is for Laravel to see this key exists
  114. Arr::set($testData, str_replace('.*', '.0', $key), Str::random());
  115. }
  116. // Now this will return the complete ruleset.
  117. // Nested array parameters will be present, with '*' replaced by '0'
  118. $newRules = Validator::make($testData, $rules)->getRules();
  119. // Transform the key names back from 'ids.0' to 'ids.*'
  120. return collect($newRules)->mapWithKeys(function ($val, $paramName) use ($rules) {
  121. if (Str::contains($paramName, '.0')) {
  122. $genericArrayKeyName = str_replace('.0', '.*', $paramName);
  123. // But only if that was the original value
  124. if (isset($rules[$genericArrayKeyName])) {
  125. $paramName = $genericArrayKeyName;
  126. }
  127. }
  128. return [$paramName => $val];
  129. })->toArray();
  130. }
  131. /**
  132. * Parse a validation rule and extract a parameter type, description and setter (used to generate an example).
  133. *
  134. * If $independentOnly is true, only independent rules will be parsed.
  135. * If a rule depends on another parameter (eg gt:field) or needs to know the type of the parameter first (eg:
  136. * size:34), it will return false.
  137. */
  138. protected function parseRule($rule, array &$parameterData, bool $independentOnly, array $allParameters = []): bool
  139. {
  140. try {
  141. if (!(is_string($rule) || $rule instanceof Rule)) {
  142. return true;
  143. }
  144. // Convert string rules into rule + arguments (eg "in:1,2" becomes ["in", ["1", "2"]])
  145. $parsedRule = $this->parseStringRuleIntoRuleAndArguments($rule);
  146. [$rule, $arguments] = $parsedRule;
  147. $dependentRules = ['between', 'max', 'min', 'size', 'gt', 'gte', 'lt', 'lte', 'before', 'after', 'before_or_equal', 'after_or_equal'];
  148. if ($independentOnly && in_array($rule, $dependentRules)) {
  149. return false;
  150. }
  151. // Reminders:
  152. // 1. Append to the description (with a leading space); don't overwrite.
  153. // 2. Avoid testing on the value of $parameterData['type'],
  154. // as that may not have been set yet, since the rules can be in any order.
  155. // For this reason, only deterministic rules are supported
  156. // 3. All rules supported must be rules that we can generate a valid dummy value for.
  157. switch ($rule) {
  158. case 'required':
  159. $parameterData['required'] = true;
  160. break;
  161. /*
  162. * Primitive types. No description should be added
  163. */
  164. case 'bool':
  165. case 'boolean':
  166. $parameterData['setter'] = function () {
  167. return Arr::random([true, false]);
  168. };
  169. $parameterData['type'] = 'boolean';
  170. break;
  171. case 'string':
  172. $parameterData['setter'] = function () {
  173. return $this->generateDummyValue('string');
  174. };
  175. $parameterData['type'] = 'string';
  176. break;
  177. case 'int':
  178. case 'integer':
  179. $parameterData['setter'] = function () {
  180. return $this->generateDummyValue('integer');
  181. };
  182. $parameterData['type'] = 'integer';
  183. break;
  184. case 'numeric':
  185. $parameterData['setter'] = function () {
  186. return $this->generateDummyValue('number');
  187. };
  188. $parameterData['type'] = 'number';
  189. break;
  190. case 'array':
  191. $parameterData['setter'] = function () {
  192. return [$this->generateDummyValue('string')];
  193. };
  194. $parameterData['type'] = 'array'; // The cleanup code in normaliseArrayAndObjectParameters() will set this to a valid type (x[] or object)
  195. break;
  196. case 'file':
  197. $parameterData['type'] = 'file';
  198. $parameterData['description'] .= ' Must be a file.';
  199. $parameterData['setter'] = function () {
  200. return $this->generateDummyValue('file');
  201. };
  202. break;
  203. /**
  204. * Special string types
  205. */
  206. case 'alpha':
  207. $parameterData['description'] .= " Must contain only letters.";
  208. $parameterData['setter'] = function () {
  209. return $this->getFaker()->lexify('??????');
  210. };
  211. break;
  212. case 'alpha_dash':
  213. $parameterData['description'] .= " Must contain only letters, numbers, dashes and underscores.";
  214. $parameterData['setter'] = function () {
  215. return $this->getFaker()->lexify('???-???_?');
  216. };
  217. break;
  218. case 'alpha_num':
  219. $parameterData['description'] .= " Must contain only letters and numbers.";
  220. $parameterData['setter'] = function () {
  221. return $this->getFaker()->bothify('#?#???#');
  222. };
  223. break;
  224. case 'timezone':
  225. // Laravel's message merely says "The value must be a valid zone"
  226. $parameterData['description'] .= " Must be a valid time zone, such as <code>Africa/Accra</code>.";
  227. $parameterData['setter'] = function () {
  228. return $this->getFaker()->timezone;
  229. };
  230. break;
  231. case 'email':
  232. $parameterData['description'] .= ' ' . $this->getDescription($rule);
  233. $parameterData['setter'] = function () {
  234. return $this->getFaker()->safeEmail;
  235. };
  236. $parameterData['type'] = 'string';
  237. break;
  238. case 'url':
  239. $parameterData['setter'] = function () {
  240. return $this->getFaker()->url;
  241. };
  242. $parameterData['type'] = 'string';
  243. // Laravel's message is "The value format is invalid". Ugh.🤮
  244. $parameterData['description'] .= " Must be a valid URL.";
  245. break;
  246. case 'ip':
  247. $parameterData['description'] .= ' ' . $this->getDescription($rule);
  248. $parameterData['type'] = 'string';
  249. $parameterData['setter'] = function () {
  250. return $this->getFaker()->ipv4;
  251. };
  252. break;
  253. case 'json':
  254. $parameterData['type'] = 'string';
  255. $parameterData['description'] .= ' ' . $this->getDescription($rule);
  256. $parameterData['setter'] = function () {
  257. return json_encode([$this->getFaker()->word, $this->getFaker()->word,]);
  258. };
  259. break;
  260. case 'date':
  261. $parameterData['type'] = 'string';
  262. $parameterData['description'] .= ' ' . $this->getDescription($rule);
  263. $parameterData['setter'] = fn() => date('Y-m-d\TH:i:s', time());
  264. break;
  265. case 'date_format':
  266. $parameterData['type'] = 'string';
  267. // Laravel description here is "The value must match the format Y-m-d". Not descriptive enough.
  268. $parameterData['description'] .= " Must be a valid date in the format <code>{$arguments[0]}</code>.";
  269. $parameterData['setter'] = function () use ($arguments) {
  270. return date($arguments[0], time());
  271. };
  272. break;
  273. case 'after':
  274. case 'after_or_equal':
  275. $parameterData['type'] = 'string';
  276. $parameterData['description'] .= ' ' . $this->getDescription($rule, [':date' => "<code>{$arguments[0]}</code>"]);
  277. // TODO introduce the concept of "modifiers", like date_format
  278. // The startDate may refer to another field, in which case, we just ignore it for now.
  279. $startDate = isset($allParameters[$arguments[0]]) ? 'today' : $arguments[0];
  280. $parameterData['setter'] = fn() => $this->getFaker()->dateTimeBetween($startDate, '+100 years')->format('Y-m-d');
  281. break;
  282. case 'before':
  283. case 'before_or_equal':
  284. $parameterData['type'] = 'string';
  285. // The argument can be either another field or a date
  286. // The endDate may refer to another field, in which case, we just ignore it for now.
  287. $endDate = isset($allParameters[$arguments[0]]) ? 'today' : $arguments[0];
  288. $parameterData['description'] .= ' ' . $this->getDescription($rule, [':date' => "<code>{$arguments[0]}</code>"]);
  289. $parameterData['setter'] = fn() => $this->getFaker()->dateTimeBetween('-30 years', $endDate)->format('Y-m-d');
  290. break;
  291. case 'starts_with':
  292. $parameterData['description'] .= ' Must start with one of ' . w::getListOfValuesAsFriendlyHtmlString($arguments);
  293. $parameterData['setter'] = fn() => $this->getFaker()->lexify("{$arguments[0]}????");;
  294. break;
  295. case 'ends_with':
  296. $parameterData['description'] .= ' Must end with one of ' . w::getListOfValuesAsFriendlyHtmlString($arguments);
  297. $parameterData['setter'] = fn() => $this->getFaker()->lexify("????{$arguments[0]}");;
  298. break;
  299. case 'uuid':
  300. $parameterData['description'] .= ' ' . $this->getDescription($rule) . ' ';
  301. $parameterData['setter'] = fn() => $this->getFaker()->uuid();;
  302. break;
  303. case 'regex':
  304. $parameterData['description'] .= ' ' . $this->getDescription($rule, [':regex' => $arguments[0]]);
  305. $parameterData['setter'] = fn() => $this->getFaker()->regexify($arguments[0]);;
  306. break;
  307. /**
  308. * Special number types.
  309. */
  310. case 'digits':
  311. $parameterData['description'] .= ' ' . $this->getDescription($rule, [':digits' => $arguments[0]]);
  312. $parameterData['setter'] = fn() => $this->getFaker()->randomNumber($arguments[0], true);
  313. $parameterData['type'] = 'number';
  314. break;
  315. case 'digits_between':
  316. $parameterData['description'] .= ' ' . $this->getDescription($rule, [':min' => $arguments[0], ':max' => $arguments[1]]);
  317. $parameterData['setter'] = fn() => $this->getFaker()->randomNumber($this->getFaker()->numberBetween(...$arguments), true);
  318. $parameterData['type'] = 'number';
  319. break;
  320. /**
  321. * These rules can apply to numbers, strings, arrays or files
  322. */
  323. case 'size':
  324. $parameterData['description'] .= ' ' . $this->getDescription(
  325. $rule, [':size' => $arguments[0]], $this->getLaravelValidationBaseTypeMapping($parameterData['type'])
  326. );
  327. $parameterData['setter'] = $this->getDummyValueGenerator($parameterData['type'], $arguments[0]);
  328. break;
  329. case 'min':
  330. $parameterData['description'] .= ' ' . $this->getDescription(
  331. $rule, [':min' => $arguments[0]], $this->getLaravelValidationBaseTypeMapping($parameterData['type'])
  332. );
  333. $parameterData['setter'] = $this->getDummyDataGeneratorBetween($parameterData['type'], $arguments[0]);
  334. break;
  335. case 'max':
  336. $parameterData['description'] .= ' ' . $this->getDescription(
  337. $rule, [':max' => $arguments[0]], $this->getLaravelValidationBaseTypeMapping($parameterData['type'])
  338. );
  339. $parameterData['setter'] = $this->getDummyDataGeneratorBetween($parameterData['type'], 0, $arguments[0]);
  340. break;
  341. case 'between':
  342. $parameterData['description'] .= ' ' . $this->getDescription(
  343. $rule, [':min' => $arguments[0], ':max' => $arguments[1]], $this->getLaravelValidationBaseTypeMapping($parameterData['type'])
  344. );
  345. $parameterData['setter'] = $this->getDummyDataGeneratorBetween($parameterData['type'], $arguments[0], $arguments[1]);
  346. break;
  347. /**
  348. * Special file types.
  349. */
  350. case 'image':
  351. $parameterData['type'] = 'file';
  352. $parameterData['description'] .= ' ' . $this->getDescription($rule) . ' ';
  353. $parameterData['setter'] = function () {
  354. // This is fine because the file example generator generates an image
  355. return $this->generateDummyValue('file');
  356. };
  357. break;
  358. /**
  359. * Other rules.
  360. */
  361. case 'in':
  362. // Not using the rule description here because it only says "The attribute is invalid"
  363. $parameterData['description'] .= ' Must be one of ' . w::getListOfValuesAsFriendlyHtmlString($arguments) . ' ';
  364. $parameterData['setter'] = function () use ($arguments) {
  365. return Arr::random($arguments);
  366. };
  367. break;
  368. /**
  369. * These rules only add a description. Generating valid examples is too complex.
  370. */
  371. case 'not_in':
  372. $parameterData['description'] .= ' Must not be one of ' . w::getListOfValuesAsFriendlyHtmlString($arguments) . ' ';
  373. break;
  374. case 'required_if':
  375. $parameterData['description'] .= ' ' . $this->getDescription(
  376. $rule, [':other' => "<code>{$arguments[0]}</code>", ':value' => "<code>{$arguments[1]}</code>"]
  377. ) . ' ';
  378. break;
  379. case 'required_unless':
  380. $parameterData['description'] .= ' ' . $this->getDescription(
  381. $rule, [':other' => "<code>" . array_shift($arguments) . "</code>", ':values' => w::getListOfValuesAsFriendlyHtmlString($arguments)]
  382. ) . ' ';
  383. break;
  384. case 'required_with':
  385. $parameterData['description'] .= ' ' . $this->getDescription(
  386. $rule, [':values' => w::getListOfValuesAsFriendlyHtmlString($arguments)]
  387. ) . ' ';
  388. break;
  389. case 'required_without':
  390. $description = $this->getDescription(
  391. $rule, [':values' => w::getListOfValuesAsFriendlyHtmlString($arguments)]
  392. ) . ' ';
  393. $parameterData['description'] .= str_replace('must be present', 'is not present', $description);
  394. break;
  395. case 'required_with_all':
  396. case 'required_without_all':
  397. $parameterData['description'] .= ' ' . $this->getDescription(
  398. $rule, [':values' => w::getListOfValuesAsFriendlyHtmlString($arguments, "and")]
  399. ) . ' ';
  400. break;
  401. case 'same':
  402. case 'different':
  403. $parameterData['description'] .= ' ' . $this->getDescription(
  404. $rule, [':other' => "<code>{$arguments[0]}</code>"]
  405. ) . ' ';
  406. break;
  407. default:
  408. // Other rules not supported
  409. break;
  410. }
  411. return true;
  412. } catch (Throwable $e) {
  413. throw CouldntProcessValidationRule::forParam($parameterData['name'], $rule, $e);
  414. }
  415. }
  416. /**
  417. * Parse a string rule into the base rule and arguments.
  418. * Laravel validation rules are specified in the format {rule}:{arguments}
  419. * Arguments are separated by commas.
  420. * For instance the rule "max:3" states that the value may only be three letters.
  421. *
  422. * @param string|Rule $rule
  423. *
  424. * @return array
  425. */
  426. protected function parseStringRuleIntoRuleAndArguments($rule): array
  427. {
  428. $ruleArguments = [];
  429. // Convert any Rule objects to strings
  430. if ($rule instanceof Rule) {
  431. $className = substr(strrchr(get_class($rule), "\\"), 1);
  432. return [$className, []];
  433. }
  434. if (strpos($rule, ':') !== false) {
  435. [$rule, $argumentsString] = explode(':', $rule, 2);
  436. // These rules can have commas in their arguments, so we don't split on commas
  437. if (in_array(strtolower($rule), ['regex', 'date', 'date_format'])) {
  438. $ruleArguments = [$argumentsString];
  439. } else {
  440. $ruleArguments = str_getcsv($argumentsString);
  441. }
  442. }
  443. return [strtolower(trim($rule)), $ruleArguments];
  444. }
  445. protected function updateParameterExample(array $parameterData): array
  446. {
  447. // If no example was given by the user, set an autogenerated example.
  448. // Each parsed rule returns a 'setter' function. We'll evaluate the last one.
  449. if ($parameterData['example'] === self::$MISSING_VALUE && isset($parameterData['setter'])) {
  450. $parameterData['example'] = $parameterData['setter']();
  451. }
  452. // If the parameter is required and has no example, generate one.
  453. if ($parameterData['required'] === true && $parameterData['example'] === self::$MISSING_VALUE) {
  454. $parameterData['example'] = $this->generateDummyValue($parameterData['type']);
  455. }
  456. if (!is_null($parameterData['example']) && $parameterData['example'] !== self::$MISSING_VALUE) {
  457. // Casting again is important since values may have been cast to string in the validator
  458. $parameterData['example'] = $this->castToType($parameterData['example'], $parameterData['type']);
  459. }
  460. return $parameterData;
  461. }
  462. /**
  463. * Laravel uses .* notation for arrays. This PR aims to normalise that into our "new syntax".
  464. *
  465. * 'years.*' with type 'integer' becomes 'years' with type 'integer[]'
  466. * 'cars.*.age' with type 'string' becomes 'cars[].age' with type 'string' and 'cars' with type 'object[]'
  467. * 'cars.*.things.*.*' with type 'string' becomes 'cars[].things' with type 'string[][]' and 'cars' with type
  468. * 'object[]'
  469. *
  470. * @param array[] $bodyParametersFromValidationRules
  471. *
  472. * @return array
  473. */
  474. public function normaliseArrayAndObjectParameters(array $bodyParametersFromValidationRules): array
  475. {
  476. $results = [];
  477. foreach ($bodyParametersFromValidationRules as $name => $details) {
  478. if (isset($results[$name])) {
  479. continue;
  480. }
  481. if ($details['type'] === 'array') {
  482. // Generic array type. If a child item exists,
  483. // this will be overwritten with the correct type (such as object or object[]) by the code below
  484. $details['type'] = 'string[]';
  485. }
  486. if (Str::endsWith($name, '.*')) {
  487. // Wrap array example properly
  488. $needsWrapping = !is_array($details['example']);
  489. $nestingLevel = 0;
  490. // Change cars.*.dogs.things.*.* with type X to cars.*.dogs.things with type X[][]
  491. while (Str::endsWith($name, '.*')) {
  492. $details['type'] .= '[]';
  493. if ($needsWrapping) {
  494. // Make it two items in each array
  495. $secondItem = $secondValue = $details['setter']();
  496. for ($i = 0; $i < $nestingLevel; $i++) {
  497. $secondItem = [$secondValue];
  498. }
  499. $details['example'] = [$details['example'], $secondItem];
  500. }
  501. $name = substr($name, 0, -2);
  502. $nestingLevel++;
  503. }
  504. }
  505. // Now make sure the field cars.*.dogs exists
  506. $parentPath = $name;
  507. while (Str::contains($parentPath, '.')) {
  508. $parentPath = preg_replace('/\.[^.]+$/', '', $parentPath);
  509. if (empty($bodyParametersFromValidationRules[$parentPath])) {
  510. if (Str::endsWith($parentPath, '.*')) {
  511. $parentPath = substr($parentPath, 0, -2);
  512. $type = 'object[]';
  513. $example = [[]];
  514. } else {
  515. $type = 'object';
  516. $example = [];
  517. }
  518. $normalisedPath = str_replace('.*.', '[].', $parentPath);
  519. $results[$normalisedPath] = [
  520. 'name' => $normalisedPath,
  521. 'type' => $type,
  522. 'required' => false,
  523. 'description' => '',
  524. 'example' => $example,
  525. ];
  526. } else {
  527. // if the parent field already exists with a type 'array'
  528. $parentDetails = $bodyParametersFromValidationRules[$parentPath];
  529. unset($bodyParametersFromValidationRules[$parentPath]);
  530. if (Str::endsWith($parentPath, '.*')) {
  531. $parentPath = substr($parentPath, 0, -2);
  532. $parentDetails['type'] = 'object[]';
  533. // Set the example too. Very likely the example array was an array of strings or an empty array
  534. if (empty($parentDetails['example']) || is_string($parentDetails['example'][0]) || is_string($parentDetails['example'][0][0])) {
  535. $parentDetails['example'] = [[]];
  536. }
  537. } else {
  538. $parentDetails['type'] = 'object';
  539. if (empty($parentDetails['example']) || is_string($parentDetails['example'][0])) {
  540. $parentDetails['example'] = [];
  541. }
  542. }
  543. $normalisedPath = str_replace('.*.', '[].', $parentPath);
  544. $parentDetails['name'] = $normalisedPath;
  545. $results[$normalisedPath] = $parentDetails;
  546. }
  547. }
  548. $details['name'] = $name = str_replace('.*.', '[].', $name);
  549. unset($details['setter']);
  550. // Change type 'array' to 'object' if there are subfields
  551. if (
  552. $details['type'] === 'array'
  553. && Arr::first(array_keys($bodyParametersFromValidationRules), function ($key) use ($name) {
  554. return preg_match("/{$name}\\.[^*]/", $key);
  555. })
  556. ) {
  557. $details['type'] = 'object';
  558. }
  559. $results[$name] = $details;
  560. }
  561. return $results;
  562. }
  563. protected function getDescription(string $rule, array $arguments = [], $baseType = 'string'): string
  564. {
  565. $description = trans("validation.{$rule}");
  566. // For rules that can apply to multiple types (eg 'max' rule), Laravel returns an array of possible messages
  567. // 'numeric' => 'The :attribute must not be greater than :max'
  568. // 'file' => 'The :attribute must have a size less than :max kilobytes'
  569. if (is_array($description)) {
  570. $description = $description[$baseType];
  571. }
  572. // Convert messages from failure type ("The :attribute is not a valid date.") to info ("The :attribute must be a valid date.")
  573. $description = str_replace(['is not', 'does not'], ['must be', 'must'], $description);
  574. $description = str_replace('may not', 'must not', $description);
  575. foreach ($arguments as $placeholder => $argument) {
  576. $description = str_replace($placeholder, $argument, $description);
  577. }
  578. // FOr rules that validate subfields
  579. $description = str_replace("The :attribute field", "This field", $description);
  580. return str_replace("The value must", "Must", str_replace(":attribute", "value", $description));
  581. }
  582. private function getLaravelValidationBaseTypeMapping(string $parameterType): string
  583. {
  584. $mapping = [
  585. 'number' => 'numeric',
  586. 'integer' => 'numeric',
  587. 'file' => 'file',
  588. 'string' => 'string',
  589. 'array' => 'array',
  590. ];
  591. if (Str::endsWith($parameterType, '[]')) {
  592. return 'array';
  593. }
  594. return $mapping[$parameterType] ?? 'string';
  595. }
  596. protected function getMissingCustomDataMessage($parameterName)
  597. {
  598. return "";
  599. }
  600. protected function shouldCastUserExample()
  601. {
  602. return false;
  603. }
  604. }