Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Validator should return validated data #23397

Merged
merged 1 commit into from
Mar 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/Illuminate/Validation/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ public function fails()
/**
* Run the validator's rules against its data.
*
* @return void
* @return array
*
* @throws \Illuminate\Validation\ValidationException
*/
Expand All @@ -305,6 +305,8 @@ public function validate()
if ($this->fails()) {
throw new ValidationException($this);
}

return $this->getDataForRules();
}

/**
Expand Down Expand Up @@ -725,6 +727,20 @@ public function getData()
return $this->data;
}

/**
* Get the data under validation only for the loaded rules.
*
* @return array
*/
public function getDataForRules()
{
$ruleKeys = collect($this->getRules())->keys()->map(function ($rule) {
return explode('.', $rule, 2)[0];
})->unique()->toArray();

return collect($this->getData())->only($ruleKeys)->toArray();
}

/**
* Set the data under validation.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3874,6 +3874,30 @@ public function message()
$this->assertTrue($rule->called);
}

public function testGetDataForRules()
{
$post = ['first'=>'john', 'last'=>'doe', 'type' => 'admin'];

$v = new Validator($this->getIlluminateArrayTranslator(), $post, ['first' => 'required']);
$data = $v->getDataForRules();

$this->assertSame($data, ['first'=>'john']);

$v->sometimes('last', 'required', function () {
return true;
});
$data = $v->getDataForRules();

$this->assertSame($data, ['first'=>'john', 'last'=>'doe']);

$v->sometimes('type', 'required', function () {
return false;
});
$data = $v->getDataForRules();

$this->assertSame($data, ['first'=>'john', 'last'=>'doe']);
}

protected function getTranslator()
{
return m::mock('Illuminate\Contracts\Translation\Translator');
Expand Down