1+ <?php
2+
3+ namespace ProgrammatorDev \YetAnotherPhpValidator ;
4+
5+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \InvalidRuleException ;
6+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \ValidationException ;
7+ use ProgrammatorDev \YetAnotherPhpValidator \Rule \RuleInterface ;
8+
9+ /**
10+ * @mixin StaticValidatorInterface
11+ */
12+ class Validator
13+ {
14+ private array $ rules ;
15+
16+ public function __construct (RuleInterface ...$ rules )
17+ {
18+ $ this ->rules = $ rules ;
19+ }
20+
21+ private static function create (): self
22+ {
23+ return new self ();
24+ }
25+
26+ /**
27+ * @throws InvalidRuleException
28+ */
29+ public static function __callStatic (string $ ruleName , array $ arguments = []): self
30+ {
31+ return self ::create ()->__call ($ ruleName , $ arguments );
32+ }
33+
34+ /**
35+ * @throws InvalidRuleException
36+ */
37+ public function __call (string $ ruleName , array $ arguments = []): self
38+ {
39+ $ factory = new Factory ();
40+ $ this ->addRule ($ ruleName , $ factory ->createRule ($ ruleName , $ arguments ));
41+
42+ return $ this ;
43+ }
44+
45+ /**
46+ * @throws ValidationException
47+ */
48+ public function assert (mixed $ input , string $ name ): void
49+ {
50+ foreach ($ this ->getRules () as $ rule ) {
51+ $ rule ->setName ($ name )->validate ($ input );
52+ }
53+ }
54+
55+ public function validate (mixed $ input ): bool
56+ {
57+ try {
58+ $ this ->assert ($ input , '' );
59+ }
60+ catch (ValidationException ) {
61+ return false ;
62+ }
63+
64+ return true ;
65+ }
66+
67+ /**
68+ * @return RuleInterface[]
69+ */
70+ private function getRules (): array
71+ {
72+ return $ this ->rules ;
73+ }
74+
75+ private function addRule (string $ name , RuleInterface $ rule ): self
76+ {
77+ $ this ->rules [$ name ] = $ rule ;
78+
79+ return $ this ;
80+ }
81+ }
0 commit comments