Skip to content

Commit

Permalink
Add PhoneNumber::getGeographicalAreaCode()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Feb 6, 2020
1 parent 730eace commit 8bce37b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/PhoneNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
22 changes: 22 additions & 0 deletions tests/PhoneNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
];
}
}

0 comments on commit 8bce37b

Please sign in to comment.