diff --git a/src/PhoneNumber.php b/src/PhoneNumber.php index 29af5e9..a8f991e 100644 --- a/src/PhoneNumber.php +++ b/src/PhoneNumber.php @@ -81,6 +81,31 @@ public function getCountryCode() : string return (string) $this->phoneNumber->getCountryCode(); } + /** + * Returns the geographical area code of this PhoneNumber. + * + * Notes: + * + * - geographical area codes change over time, and this method honors those changes; therefore, it doesn't + * guarantee the stability of the result it produces; + * - most non-geographical numbers have no area codes, including numbers from non-geographical entities; + * - some geographical numbers have no area codes. + * + * If this number has no area code, an empty string is returned. + * + * @return string + */ + public function getGeographicalAreaCode() : string + { + $phoneNumberUtil = PhoneNumberUtil::getInstance(); + + $nationalSignificantNumber = $phoneNumberUtil->getNationalSignificantNumber($this->phoneNumber); + + $areaCodeLength = $phoneNumberUtil->getLengthOfGeographicalAreaCode($this->phoneNumber); + + return substr($nationalSignificantNumber, 0, $areaCodeLength); + } + /** * Returns the national number of this PhoneNumber. * diff --git a/tests/PhoneNumberTest.php b/tests/PhoneNumberTest.php index afce667..eac41eb 100644 --- a/tests/PhoneNumberTest.php +++ b/tests/PhoneNumberTest.php @@ -542,4 +542,26 @@ public function providerFormatForCallingFrom() : array ['+16502530000', 'GB', '00 1 650-253-0000'], ]; } + + /** + * @dataProvider providerGetGeographicalAreaCode + */ + public function testGetGeographicalAreaCode(string $phoneNumber, string $areaCode) : void + { + $this->assertSame($areaCode, PhoneNumber::parse($phoneNumber)->getGeographicalAreaCode()); + } + + public function providerGetGeographicalAreaCode() : array + { + return [ + ['+442079460585', '20'], + ['+441132224444', '113'], + ['+447553840000', ''], + ['+33123000000', '1'], + ['+33234000000', '2'], + ['+33345000000', '3'], + ['+33456000000', '4'], + ['+33567000000', '5'], + ]; + } }