1+ <?php
2+
3+ namespace ProgrammatorDev \YetAnotherPhpValidator \Rule ;
4+
5+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \AllException ;
6+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \UnexpectedValueException ;
7+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \ValidationException ;
8+ use ProgrammatorDev \YetAnotherPhpValidator \Rule \Util \AssertIsValidatableTrait ;
9+ use Symfony \Component \OptionsResolver \OptionsResolver ;
10+
11+ class All extends AbstractRule implements RuleInterface
12+ {
13+ use AssertIsValidatableTrait;
14+
15+ private array $ options ;
16+
17+ /**
18+ * @param RuleInterface[] $constraints
19+ */
20+ public function __construct (
21+ private readonly array $ constraints ,
22+ array $ options = []
23+ )
24+ {
25+ $ resolver = new OptionsResolver ();
26+
27+ $ resolver ->setDefaults (['message ' => 'At "{{ key }}": {{ message }} ' ]);
28+
29+ $ resolver ->setAllowedTypes ('message ' , 'string ' );
30+
31+ $ this ->options = $ resolver ->resolve ($ options );
32+ }
33+
34+ public function assert (mixed $ value , string $ name ): void
35+ {
36+ $ this ->assertIsValidatable ($ this ->constraints );
37+
38+ if (!\is_array ($ value )) {
39+ throw new UnexpectedValueException (
40+ \sprintf ('Expected value of type "array", "%s" given ' , get_debug_type ($ value ))
41+ );
42+ }
43+
44+ try {
45+ foreach ($ value as $ key => $ input ) {
46+ foreach ($ this ->constraints as $ constraint ) {
47+ $ constraint ->assert ($ input , $ name );
48+ }
49+ }
50+ }
51+ catch (ValidationException $ exception ) {
52+ throw new AllException (
53+ message: $ this ->options ['message ' ],
54+ parameters: [
55+ 'value ' => $ value ,
56+ 'name ' => $ name ,
57+ 'key ' => $ key ,
58+ 'message ' => $ exception ->getMessage ()
59+ ]
60+ );
61+ }
62+ }
63+ }
0 commit comments