Skip to content

Commit

Permalink
fixed confirmed failing when nested
Browse files Browse the repository at this point in the history
  • Loading branch information
romalytvynenko committed Jul 5, 2024
1 parent 85502c4 commit 9722a51
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ public function __construct(array $rules, array $validationNodesResults, TypeTra
public function handle()
{
return collect($this->rules)
->pipe($this->handleConfirmed(...))
->map(fn ($rules, $name) => (new RulesToParameter($name, $rules, $this->nodeDocs[$name] ?? null, $this->openApiTransformer))->generate())
->filter()
->pipe($this->handleNested(...))
->pipe($this->handleConfirmed(...))
->values()
->all();
}
Expand Down Expand Up @@ -92,27 +92,24 @@ private function handleNested(Collection $parameters)
->merge($nested);
}

private function handleConfirmed(Collection $parameters)
private function handleConfirmed(Collection $rules)
{
$confirmedParamNameRules = collect($this->rules)
$confirmedParamNameRules = $rules
->map(fn ($rules, $name) => [$name, Arr::wrap(is_string($rules) ? explode('|', $rules) : $rules)])
->filter(fn ($nameRules) => in_array('confirmed', $nameRules[1]));

if (! $confirmedParamNameRules) {
return $parameters;
return $rules;
}

foreach ($confirmedParamNameRules as $confirmedParamNameRule) {
/** @var Parameter $confirmedParam */
$confirmedParam = $parameters->first(fn ($p) => $p->name === $confirmedParamNameRule[0]);

$parameters->offsetSet(
$name = "$confirmedParamNameRule[0]_confirmation",
(clone $confirmedParam)->setName($name),
$rules->offsetSet(
"$confirmedParamNameRule[0]_confirmation",
array_filter($confirmedParamNameRule[1], fn ($rule) => $rule !== 'confirmed'),
);
}

return $parameters;
return $rules;
}

private function setDeepType(Type &$base, string $key, Type $typeToSet)
Expand Down
22 changes: 22 additions & 0 deletions tests/Generator/Request/ValidationRulesDocumentationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,28 @@
->toMatchArray(['name' => 'password_confirmation']);
});

it('supports confirmed rule in array', function () {
$rules = [
'user.password' => ['required', 'min:8', 'confirmed'],
];

$params = app()->make(RulesToParameters::class, ['rules' => $rules])->handle();

expect($params = collect($params)->map->toArray()->all())
->toHaveCount(1)
->and($params[0])
->toMatchArray([
'schema' => [
'type' => 'object',
'properties' => [
'password' => ['type' => 'string', 'minLength' => 8],
'password_confirmation' => ['type' => 'string', 'minLength' => 8],
],
'required' => ['password', 'password_confirmation'],
]
]);
});

it('supports multiple confirmed rule', function () {
$rules = [
'password' => ['required', 'min:8', 'confirmed'],
Expand Down

0 comments on commit 9722a51

Please sign in to comment.