-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimezoneValidator.php
More file actions
53 lines (43 loc) · 1.41 KB
/
TimezoneValidator.php
File metadata and controls
53 lines (43 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);
namespace AssoConnect\ValidatorBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Validates whether a value is a valid locale code.
*
* @author Sylvain Fabre <sylvain.fabre@assoconnect.com>
*/
class TimezoneValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
*/
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Timezone) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Timezone');
}
if (null === $value || '' === $value) {
return;
}
$value = $this->getValue($value);
if (!in_array($value, \DateTimeZone::listIdentifiers(), true)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Timezone::NO_SUCH_TIMEZONE_ERROR)
->addViolation();
}
}
private function getValue(mixed $value): string
{
if ($value instanceof \DateTimeZone) {
return $value->getName();
}
if (!is_string($value)) {
throw new UnexpectedTypeException($value, 'string');
}
return $value;
}
}