Skip to content

Commit

Permalink
[10.x] Support ConditionalRules within NestedRules (#47344)
Browse files Browse the repository at this point in the history
* failing test

* filter conditional rules when compiling NestedRules

* styleci

* always filter conditional rules

* modify test

* split tests
  • Loading branch information
cosmastech authored Jun 7, 2023
1 parent d06f3a9 commit 0307ae4
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Illuminate/Validation/NestedRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ public function compile($attribute, $value, $data = null)
$nested[$attribute.'.'.$key] = $rule;
}

return $parser->explode($nested);
$rules = $nested;
} else {
$rules = [$attribute => $rules];
}

return $parser->explode([$attribute => $rules]);
return $parser->explode(ValidationRuleParser::filterConditionalRules($rules, $data));
}
}
64 changes: 64 additions & 0 deletions tests/Validation/ValidationForEachTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,70 @@ public function testForEachCallbacksCanContainMultipleRegexRules()
], $v->getMessageBag()->toArray());
}

public function testConditionalRulesCanBeAddedToForEachWithAssociativeArray()
{
$v = new Validator(
$this->getIlluminateArrayTranslator(),
[
'foo' => [
['bar' => true],
['bar' => false],
],
],
[
'foo.*' => Rule::forEach(fn(mixed $value, string $attribute) => [
'bar' => Rule::when(true, ['accepted'], ['declined']),
]),
]
);

$this->assertEquals([
'foo.1.bar' => ['validation.accepted'],
], $v->getMessageBag()->toArray());
}
public function testConditionalRulesCanBeAddedToForEachWithList()
{
$v = new Validator(
$this->getIlluminateArrayTranslator(),
[
'foo' => [
['bar' => true],
['bar' => false],
],
],
[
'foo.*.bar' => Rule::forEach(fn(mixed $value, string $attribute) => [
Rule::when(true, ['accepted'], ['declined']),
]),
]);

$this->assertEquals([
'foo.1.bar' => ['validation.accepted'],
], $v->getMessageBag()->toArray());

}

public function testConditionalRulesCanBeAddedToForEachWithObject()
{
$v = new Validator(
$this->getIlluminateArrayTranslator(),
[
'foo' => [
['bar' => true],
['bar' => false],
],
],
[
'foo.*.bar' => Rule::forEach(fn (mixed $value, string $attribute) =>
Rule::when(true, ['accepted'], ['declined']),
),
]);

$this->assertEquals([
'foo.1.bar' => ['validation.accepted'],
], $v->getMessageBag()->toArray());
}

protected function getTranslator()
{
return m::mock(TranslatorContract::class);
Expand Down

0 comments on commit 0307ae4

Please sign in to comment.