Spaces:
No application file
No application file
File size: 1,727 Bytes
d2897cd |
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 |
<?php
namespace Mautic\FormBundle\Validator\Constraint;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Phone number validator.
*/
class PhoneNumberConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint): void
{
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$phoneUtil = PhoneNumberUtil::getInstance();
if (false === $value instanceof PhoneNumber) {
$value = (string) $value;
try {
$phoneNumber = $phoneUtil->parse($value, PhoneNumberUtil::UNKNOWN_REGION);
} catch (NumberParseException) {
$this->addViolation($value, $constraint);
return;
}
}
if (false === $phoneUtil->isValidNumber($phoneNumber)) {
$this->addViolation($value, $constraint);
return;
}
}
/**
* Add a violation.
*
* @param mixed $value the value that should be validated
* @param Constraint $constraint the constraint for the validation
*/
private function addViolation($value, Constraint $constraint): void
{
$this->context->addViolation(
$constraint->getMessage(),
['{{ value }}' => $value]
);
}
}
|