@@ -39,45 +39,14 @@ public function validate(object $object): void
3939 }
4040 }
4141
42- /**
43- * @param Rule[] $rules
44- */
4542 public function validateValue (mixed $ value , Closure |Rule |array $ rules ): void
4643 {
4744 $ failingRules = [];
4845
4946 foreach (arr ($ rules ) as $ rule ) {
50- if ($ rule instanceof Closure) {
51- $ result = $ rule ($ value );
52-
53- [$ isValid , $ message ] = match (true ) {
54- is_string ($ result ) => [false , $ result ],
55- $ result === false => [false , 'Value did not pass validation. ' ],
56- default => [true , '' ],
57- };
58-
59- $ rule = new class ($ isValid , $ message ) implements Rule {
60- public function __construct (
61- private readonly bool $ isValid ,
62- private readonly string $ message ,
63- ) {
64- }
65-
66- public function isValid (mixed $ value ): bool
67- {
68- return $ this ->isValid ;
69- }
70-
71- public function message (): string
72- {
73- return $ this ->message ;
74- }
75- };
76- }
77-
78- $ isValid = $ rule ->isValid ($ value );
47+ $ rule = $ this ->convertToRule ($ rule , $ value );
7948
80- if (! $ isValid ) {
49+ if (! $ rule -> isValid ( $ value ) ) {
8150 $ failingRules [] = $ rule ;
8251 }
8352 }
@@ -86,4 +55,37 @@ public function message(): string
8655 throw new InvalidValueException ($ value , $ failingRules );
8756 }
8857 }
58+
59+ private function convertToRule (Rule |Closure $ rule , mixed $ value ): Rule
60+ {
61+ if ($ rule instanceof Rule) {
62+ return $ rule ;
63+ }
64+
65+ $ result = $ rule ($ value );
66+
67+ [$ isValid , $ message ] = match (true ) {
68+ is_string ($ result ) => [false , $ result ],
69+ $ result === false => [false , 'Value did not pass validation. ' ],
70+ default => [true , '' ],
71+ };
72+
73+ return new class ($ isValid , $ message ) implements Rule {
74+ public function __construct (
75+ private readonly bool $ isValid ,
76+ private readonly string $ message ,
77+ ) {
78+ }
79+
80+ public function isValid (mixed $ value ): bool
81+ {
82+ return $ this ->isValid ;
83+ }
84+
85+ public function message (): string
86+ {
87+ return $ this ->message ;
88+ }
89+ };
90+ }
8991}
0 commit comments