Skip to content

Commit d22d43e

Browse files
committed
optimize code
1 parent b5d1cc2 commit d22d43e

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

src/PhoneHelper.php

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,11 @@
2020
class PhoneHelper
2121
{
2222
private static $countryCodes = [
23+
'7' => [
24+
'Российская Федерация' => ['9'],
25+
'Казахстан' => ['7'],
26+
],
2327
'1' => 'США/Канада',
24-
'7' => 'Россия/Казахстан',
2528
'20' => 'Египет',
2629
'21' => 'Южная Африка',
2730
'22' => 'Марокко',
@@ -139,7 +142,7 @@ public static function formatInternationalMobilePhoneNumber(?string $phoneNumber
139142
return [
140143
'formattedNumber' => $phoneNumber,
141144
'countryCode' => $countryCode,
142-
'countryName' => self::$countryCodes[$countryCode],
145+
'countryName' => self::getCountryNameFromPhoneNumber($phoneNumber, $countryCode),
143146
];
144147
}
145148

@@ -294,9 +297,48 @@ private static function getCountryCodeFromPhoneNumber(string $phoneNumber): ?str
294297
{
295298
// Extract the country code from the phone number
296299
foreach (self::$countryCodes as $code => $country) {
297-
if (\str_starts_with($phoneNumber, '+' . $code)) {
298-
return $code;
300+
if (\is_array($country)) {
301+
foreach ($country as $subCode => $prefixes) {
302+
foreach ($prefixes as $prefix) {
303+
if (\str_starts_with($phoneNumber, '+' . $code . $prefix)) {
304+
return $code;
305+
}
306+
}
307+
}
308+
} else {
309+
if (\str_starts_with($phoneNumber, '+' . $code)) {
310+
return $code;
311+
}
312+
}
313+
}
314+
315+
return null;
316+
}
317+
318+
/**
319+
* Determines the name of the country by phone number and code of the country.
320+
*
321+
* Определяем название страны по номеру телефона и коду страны.
322+
*
323+
* @param string $phoneNumber the formatted phone number
324+
* @param string $countryCode the country code
325+
*
326+
* @return string|null the country code, or null if the country code cannot be determined
327+
*/
328+
private static function getCountryNameFromPhoneNumber(string $phoneNumber, string $countryCode): ?string
329+
{
330+
$country = self::$countryCodes[$countryCode];
331+
332+
if (\is_array($country)) {
333+
foreach ($country as $name => $prefixes) {
334+
foreach ($prefixes as $prefix) {
335+
if (\str_starts_with($phoneNumber, '+' . $countryCode . $prefix)) {
336+
return $name;
337+
}
338+
}
299339
}
340+
} else {
341+
return $country;
300342
}
301343

302344
return null;

0 commit comments

Comments
 (0)