From 557177cbe6241f04e4b1e0e1d4b7633635aa4e2d Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 5 Mar 2018 15:09:27 -0700 Subject: [PATCH] Provide access to validated dataset --- src/Illuminate/Validation/Validator.php | 18 ++++++++++++++- tests/Validation/ValidationValidatorTest.php | 24 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Validation/Validator.php b/src/Illuminate/Validation/Validator.php index e2233adfae26..fdcec8850059 100755 --- a/src/Illuminate/Validation/Validator.php +++ b/src/Illuminate/Validation/Validator.php @@ -296,7 +296,7 @@ public function fails() /** * Run the validator's rules against its data. * - * @return void + * @return array * * @throws \Illuminate\Validation\ValidationException */ @@ -305,6 +305,8 @@ public function validate() if ($this->fails()) { throw new ValidationException($this); } + + return $this->getDataForRules(); } /** @@ -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. * diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php index 137918b19aea..b3121a0d6c77 100755 --- a/tests/Validation/ValidationValidatorTest.php +++ b/tests/Validation/ValidationValidatorTest.php @@ -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');