Skip to content

Commit

Permalink
[10.x] Adds FormRequest@getRules() method (#49860)
Browse files Browse the repository at this point in the history
* adds getRules method

* revert style changes

* revert style changes

* revert style changes

* revert style changes

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
cosmastech and taylorotwell authored Jan 29, 2024
1 parent 706a7d2 commit 4fa777d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/Illuminate/Foundation/Http/FormRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,11 @@ protected function getValidatorInstance()
*/
protected function createDefaultValidator(ValidationFactory $factory)
{
$rules = method_exists($this, 'rules') ? $this->container->call([$this, 'rules']) : [];

$validator = $factory->make(
$this->validationData(), $rules,
$this->messages(), $this->attributes()
$this->validationData(),
$this->validationRules(),
$this->messages(),
$this->attributes(),
)->stopOnFirstFailure($this->stopOnFirstFailure);

if ($this->isPrecognitive()) {
Expand All @@ -141,6 +141,16 @@ public function validationData()
return $this->all();
}

/**
* Get the validation rules for this form request.
*
* @return array
*/
protected function validationRules()
{
return method_exists($this, 'rules') ? $this->container->call([$this, 'rules']) : [];
}

/**
* Handle a failed validation attempt.
*
Expand Down
34 changes: 34 additions & 0 deletions tests/Foundation/FoundationFormRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,22 @@ public function testRequestCanPassWithoutRulesMethod()
$this->assertEquals([], $request->all());
}

public function testRequestWithGetRules()
{
FoundationTestFormRequestWithGetRules::$useRuleSet = 'a';
$request = $this->createRequest(['a' => 1], FoundationTestFormRequestWithGetRules::class);

$request->validateResolved();
$this->assertEquals(['a' => 1], $request->all());

$this->expectException(ValidationException::class);
FoundationTestFormRequestWithGetRules::$useRuleSet = 'b';

$request = $this->createRequest(['a' => 1], FoundationTestFormRequestWithGetRules::class);

$request->validateResolved();
}

/**
* Catch the given exception thrown from the executor, and return it.
*
Expand Down Expand Up @@ -482,3 +498,21 @@ public function authorize()
return true;
}
}

class FoundationTestFormRequestWithGetRules extends FormRequest
{
public static $useRuleSet = 'a';

protected function validationRules(): array
{
if (self::$useRuleSet === 'a') {
return [
'a' => ['required', 'int', 'min:1']
];
} else {
return [
'a' => ['required', 'int', 'min:2'],
];
}
}
}

0 comments on commit 4fa777d

Please sign in to comment.