Do not validate phone numbers from other regions

I'm unsure whether this is a bug in "libphonenumber-for-php" or if we're
misusing the library. This commit will ensure that only phone numbers
from a specific region will be considered valid. I've reported the issue
to "libphonenumber-for-php" anyways [1].

[1]: https://github.com/giggsey/libphonenumber-for-php/issues/621

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Henrique Moody 2024-03-24 19:38:51 +01:00
parent ccec34cf21
commit 263ae118fb
No known key found for this signature in database
GPG key ID: 221E9281655813A6
2 changed files with 12 additions and 4 deletions

View file

@ -61,13 +61,20 @@ final class Phone extends AbstractRule
return preg_match($this->getPregFormat(), (string) $input) > 0;
}
return $this->isValidRegionalPhoneNumber((string) $input, $this->countryCode);
}
private function isValidRegionalPhoneNumber(string $input, string $countryCode): bool
{
try {
return PhoneNumberUtil::getInstance()->isValidNumber(
PhoneNumberUtil::getInstance()->parse((string) $input, $this->countryCode)
);
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$phoneNumberObject = $phoneNumberUtil->parse($input, $countryCode);
return $phoneNumberUtil->getRegionCodeForNumber($phoneNumberObject) === $countryCode;
} catch (NumberParseException) {
return false;
}
return false;
}
private function getPregFormat(): string

View file

@ -145,6 +145,7 @@ final class PhoneTest extends RuleTestCase
[new Phone(), []],
[new Phone(), '+1-650-253-00-0'],
[new Phone('BR'), '+1 11 91111 1111'], // invalid + code for BR
[new Phone('BR'), '+1 650 253 00 00'], // invalid + code for BR
];
}
}