Skip to content

Commit

Permalink
optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
Leonid74 committed May 23, 2024
1 parent b5d1cc2 commit d22d43e
Showing 1 changed file with 46 additions and 4 deletions.
50 changes: 46 additions & 4 deletions src/PhoneHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
class PhoneHelper
{
private static $countryCodes = [
'7' => [
'Российская Федерация' => ['9'],
'Казахстан' => ['7'],
],
'1' => 'США/Канада',
'7' => 'Россия/Казахстан',
'20' => 'Египет',
'21' => 'Южная Африка',
'22' => 'Марокко',
Expand Down Expand Up @@ -139,7 +142,7 @@ public static function formatInternationalMobilePhoneNumber(?string $phoneNumber
return [
'formattedNumber' => $phoneNumber,
'countryCode' => $countryCode,
'countryName' => self::$countryCodes[$countryCode],
'countryName' => self::getCountryNameFromPhoneNumber($phoneNumber, $countryCode),
];
}

Expand Down Expand Up @@ -294,9 +297,48 @@ private static function getCountryCodeFromPhoneNumber(string $phoneNumber): ?str
{
// Extract the country code from the phone number
foreach (self::$countryCodes as $code => $country) {
if (\str_starts_with($phoneNumber, '+' . $code)) {
return $code;
if (\is_array($country)) {
foreach ($country as $subCode => $prefixes) {
foreach ($prefixes as $prefix) {
if (\str_starts_with($phoneNumber, '+' . $code . $prefix)) {
return $code;
}
}
}
} else {
if (\str_starts_with($phoneNumber, '+' . $code)) {
return $code;
}
}
}

return null;
}

/**
* Determines the name of the country by phone number and code of the country.
*
* Определяем название страны по номеру телефона и коду страны.
*
* @param string $phoneNumber the formatted phone number
* @param string $countryCode the country code
*
* @return string|null the country code, or null if the country code cannot be determined
*/
private static function getCountryNameFromPhoneNumber(string $phoneNumber, string $countryCode): ?string
{
$country = self::$countryCodes[$countryCode];

if (\is_array($country)) {
foreach ($country as $name => $prefixes) {
foreach ($prefixes as $prefix) {
if (\str_starts_with($phoneNumber, '+' . $countryCode . $prefix)) {
return $name;
}
}
}
} else {
return $country;
}

return null;
Expand Down

0 comments on commit d22d43e

Please sign in to comment.