Skip to content

Commit 2c5792f

Browse files
committed
Add a TImezone validation rule
1 parent e04a42a commit 2c5792f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/Shared/Rules/TimezoneRule.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace CraftCms\Cms\Shared\Rules;
6+
7+
use Closure;
8+
use CraftCms\Cms\Support\Env;
9+
use Illuminate\Contracts\Validation\ValidationRule;
10+
use IntlDateFormatter;
11+
use IntlException;
12+
13+
final readonly class TimezoneRule implements ValidationRule
14+
{
15+
public function validate(string $attribute, mixed $value, Closure $fail): void
16+
{
17+
$timezone = Env::parse($value);
18+
19+
try {
20+
$formatter = new IntlDateFormatter(app()->getLocale(), IntlDateFormatter::NONE, IntlDateFormatter::NONE);
21+
22+
if (! $formatter->setTimeZone($timezone)) {
23+
$timezone = 'UTC';
24+
$fail("Time zone “{$timezone}” does not appear to be supported by ICU.");
25+
}
26+
} catch (IntlException) {
27+
$fail("Time zone “{$timezone}” does not appear to be supported by ICU: ".intl_get_error_message());
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)