1+ <?php
2+
3+ namespace ProgrammatorDev \YetAnotherPhpValidator \Rule ;
4+
5+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \RangeException ;
6+ use ProgrammatorDev \YetAnotherPhpValidator \Rule \Util \AssertIsComparableTrait ;
7+ use ProgrammatorDev \YetAnotherPhpValidator \Validator ;
8+ use Symfony \Component \OptionsResolver \OptionsResolver ;
9+
10+ class Range extends AbstractRule implements RuleInterface
11+ {
12+ use AssertIsComparableTrait;
13+
14+ private array $ options ;
15+
16+ public function __construct (
17+ private readonly mixed $ minConstraint ,
18+ private readonly mixed $ maxConstraint ,
19+ array $ options = []
20+ )
21+ {
22+ $ resolver = new OptionsResolver ();
23+
24+ $ resolver ->setDefaults ([
25+ 'message ' => 'The {{ name }} value should be between "{{ minConstraint }}" and "{{ maxConstraint }}", "{{ value }}" given. '
26+ ]);
27+
28+ $ resolver ->setAllowedTypes ('message ' , 'string ' );
29+
30+ $ this ->options = $ resolver ->resolve ($ options );
31+ }
32+
33+ public function assert (mixed $ value , string $ name ): void
34+ {
35+ $ this ->assertIsComparable ($ this ->minConstraint , $ this ->maxConstraint );
36+
37+ if (!Validator::greaterThan ($ this ->minConstraint )->lessThan ($ this ->maxConstraint )->validate ($ value )) {
38+ throw new RangeException (
39+ message: $ this ->options ['message ' ],
40+ parameters: [
41+ 'value ' => $ value ,
42+ 'name ' => $ name ,
43+ 'minConstraint ' => $ this ->minConstraint ,
44+ 'maxConstraint ' => $ this ->maxConstraint
45+ ]
46+ );
47+ }
48+ }
49+ }
0 commit comments