1+ <?php
2+
3+ namespace ProgrammatorDev \YetAnotherPhpValidator \Rule ;
4+
5+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \TimezoneException ;
6+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \UnexpectedValueException ;
7+ use ProgrammatorDev \YetAnotherPhpValidator \Exception \ValidationException ;
8+ use ProgrammatorDev \YetAnotherPhpValidator \Validator ;
9+
10+ class Timezone extends AbstractRule implements RuleInterface
11+ {
12+ public function __construct (
13+ private readonly int $ timezoneGroup = \DateTimeZone::ALL ,
14+ private ?string $ countryCode = null ,
15+ private readonly string $ message = 'The "{{ name }}" value is not a valid timezone, "{{ value }}" given. '
16+ ) {}
17+
18+ public function assert (mixed $ value , string $ name ): void
19+ {
20+ if ($ this ->countryCode !== null ) {
21+ // Normalize country code
22+ $ this ->countryCode = strtoupper ($ this ->countryCode );
23+
24+ try {
25+ Validator::country ()->assert ($ this ->countryCode , 'countryCode ' );
26+ }
27+ catch (ValidationException $ exception ) {
28+ throw new UnexpectedValueException ($ exception ->getMessage ());
29+ }
30+ }
31+
32+ if ($ this ->timezoneGroup === \DateTimeZone::PER_COUNTRY && $ this ->countryCode === null ) {
33+ throw new UnexpectedValueException (
34+ 'A country code must be given when timezone group is \DateTimeZone::PER_COUNTRY. '
35+ );
36+ }
37+
38+ if (!\in_array ($ value , \DateTimeZone::listIdentifiers ($ this ->timezoneGroup , $ this ->countryCode ), true )) {
39+ throw new TimezoneException (
40+ message: $ this ->message ,
41+ parameters: [
42+ 'value ' => $ value ,
43+ 'name ' => $ name ,
44+ 'countryCode ' => $ this ->countryCode
45+ ]
46+ );
47+ }
48+ }
49+ }
0 commit comments