File tree Expand file tree Collapse file tree 4 files changed +50
-5
lines changed
Expand file tree Collapse file tree 4 files changed +50
-5
lines changed Original file line number Diff line number Diff line change @@ -28,4 +28,11 @@ public function isInvalid() : bool;
2828 * @return \Illuminate\Contracts\Support\MessageProvider
2929 */
3030 public function getErrors () : MessageProvider ;
31+
32+ /**
33+ * Returns the reasons why the validator failed.
34+ *
35+ * @return array
36+ */
37+ public function getValidationFailureReasons () : array ;
3138}
Original file line number Diff line number Diff line change @@ -34,6 +34,13 @@ protected function getMessages() : array
3434 return [];
3535 }
3636
37+ /**
38+ * The validator.
39+ *
40+ * @return \Illuminate\Contracts\Validation\Validator
41+ */
42+ private $ validator ;
43+
3744 /**
3845 * Returns an instance of the validator from our container.
3946 *
@@ -52,11 +59,14 @@ private function getValidationFactory() : Factory
5259 */
5360 private function getValidator () : Validator
5461 {
55- return $ this ->getValidationFactory ()->make (
56- $ this ->getData (),
57- $ this ->getRules (),
58- $ this ->getMessages ()
59- );
62+ if (is_null ($ this ->validator )) {
63+ $ this ->validator = $ this ->getValidationFactory ()->make (
64+ $ this ->getData (),
65+ $ this ->getRules (),
66+ $ this ->getMessages ()
67+ );
68+ }
69+ return $ this ->validator ;
6070 }
6171
6272 /**
@@ -106,6 +116,19 @@ public function getErrors() : MessageProvider
106116 return $ this ->getValidator ()->getMessageBag ();
107117 }
108118
119+ /**
120+ * Returns the reasons why the validator failed.
121+ *
122+ * @return array
123+ */
124+ public function getValidationFailureReasons () : array
125+ {
126+ if ($ this ->isInvalid ()) {
127+ return $ this ->getValidator ()->failed ();
128+ }
129+ return [];
130+ }
131+
109132 /**
110133 * Save the model to the database.
111134 *
Original file line number Diff line number Diff line change @@ -52,4 +52,13 @@ public function testValidateThrowsAValidationException()
5252 $ model = new InvalidModel ();
5353 $ model ->validate ();
5454 }
55+
56+ public function testGetValidationFailureReasonsReturnsTheReasonsWhyTheValidationFailed ()
57+ {
58+ $ model = new InvalidModel ();
59+ $ reasons = $ model ->getValidationFailureReasons ();
60+
61+ $ this ->assertTrue (array_key_exists ('email ' , $ reasons ));
62+ $ this ->assertTrue (array_key_exists ('Required ' , $ reasons ['email ' ]));
63+ }
5564}
Original file line number Diff line number Diff line change @@ -33,4 +33,10 @@ public function testValidateDoesNotThrowAValidationException()
3333 $ model = new ValidModel ();
3434 $ this ->assertVoid ($ model ->validate ());
3535 }
36+
37+ public function testGetValidationFailureReasonsReturnsAnEmptyArray ()
38+ {
39+ $ model = new ValidModel ();
40+ $ this ->assertEmpty ($ model ->getValidationFailureReasons ());
41+ }
3642}
You can’t perform that action at this time.
0 commit comments