Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit 35b66c4

Browse files
committed
feat: added timezone rule
1 parent 6299143 commit 35b66c4

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
3+
namespace ProgrammatorDev\YetAnotherPhpValidator\Exception;
4+
5+
class TimezoneException extends ValidationException {}

src/Rule/Timezone.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)