From 263ae118fb9b0d3bc6692eb2154cd851deff7932 Mon Sep 17 00:00:00 2001 From: Henrique Moody Date: Sun, 24 Mar 2024 19:38:51 +0100 Subject: [PATCH] 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 --- library/Rules/Phone.php | 15 +++++++++++---- tests/unit/Rules/PhoneTest.php | 1 + 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/library/Rules/Phone.php b/library/Rules/Phone.php index 9a18d1d7..3d7ff533 100644 --- a/library/Rules/Phone.php +++ b/library/Rules/Phone.php @@ -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 diff --git a/tests/unit/Rules/PhoneTest.php b/tests/unit/Rules/PhoneTest.php index ea49bf7c..f151978b 100644 --- a/tests/unit/Rules/PhoneTest.php +++ b/tests/unit/Rules/PhoneTest.php @@ -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 ]; } }