-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhoneValidator.php
More file actions
77 lines (67 loc) · 2.88 KB
/
PhoneValidator.php
File metadata and controls
77 lines (67 loc) · 2.88 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
declare(strict_types=1);
namespace AssoConnect\ValidatorBundle\Validator\Constraints;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberUtil;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class PhoneValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Phone) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\Phone');
}
if ($value === '' || $value === null) {
return;
}
if (substr($value, 0, 1) !== '+') {
$this->buildViolation($value, $constraint->notIntlFormatMessage, Phone::NOT_INTL_FORMAT_ERROR);
return;
}
$phone = $value;
$phoneUtil = PhoneNumberUtil::getInstance();
try {
$phoneObject = $phoneUtil->parse($phone);
if ($phoneUtil->isPossibleNumber($phoneObject)) {
$phoneNumberType = $phoneUtil->getNumberType($phoneObject);
if (in_array($phoneNumberType, $constraint->getValidTypes(), true)) {
return;
}
$this->buildViolation($value, $constraint->wrongTypeMessage, Phone::INVALID_TYPE_ERROR);
return;
}
$this->buildViolation($value, $constraint->inexistantMessage, Phone::PHONE_NUMBER_NOT_EXIST);
} catch (NumberParseException $exception) {
switch ($exception->getErrorType()) {
case NumberParseException::NOT_A_NUMBER:
$this->buildViolation($value, $constraint->message, Phone::INVALID_FORMAT_ERROR);
break;
case NumberParseException::TOO_SHORT_AFTER_IDD:
case NumberParseException::TOO_SHORT_NSN:
$this->buildViolation($value, $constraint->tooShortMessage, Phone::LENGTH_MIN_ERROR);
break;
case NumberParseException::TOO_LONG:
$this->buildViolation($value, $constraint->tooLongMessage, Phone::LENGTH_MAX_ERROR);
break;
case NumberParseException::INVALID_COUNTRY_CODE:
$this->buildViolation(
$value,
$constraint->invalidCountryCodeMessage,
Phone::INVALID_COUNTRY_CODE
);
break;
default:
throw $exception;
}
}
}
private function buildViolation(string $value, string $message, string $code): void
{
$this->context->buildViolation($message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($code)
->addViolation();
}
}