Files
urukprize/backend/app/Services/PhoneFormatterService.php

65 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
class PhoneFormatterService
{
/**
* Normalizes a phone number to standard E.164 digits format (without '+').
* Automatically handles leading zeros and national dialing prefixes.
*
* Example Iraq: 07701234567 -> 9647701234567
* Example Iraq: +964 0780 1234 -> 9647801234
* Example Jordan: 0791234567 -> 962791234567
*/
public static function normalize(string $phone, string $defaultCountryCode = '964'): string
{
// 1. Remove all non-digit characters (+, -, spaces, dots, brackets)
$cleaned = preg_replace('/[^\d]/', '', $phone);
if (empty($cleaned)) {
return '';
}
// 2. Remove international double-zero prefixes (e.g. 00964 -> 964)
if (str_starts_with($cleaned, '00')) {
$cleaned = substr($cleaned, 2);
}
// 3. Supported Country Code Detection & Cleaning
$knownCountryCodes = ['964', '962', '20', '961', '966', '971'];
foreach ($knownCountryCodes as $cc) {
if (str_starts_with($cleaned, $cc)) {
$localPart = substr($cleaned, strlen($cc));
// Remove any redundant leading zero after country code (e.g. 964 0770... -> 964 770...)
$localPart = ltrim($localPart, '0');
return $cc . $localPart;
}
}
// 4. If no recognized country code is attached, treat as national number with default country code
// Remove leading national zero (e.g. 0770... -> 770...)
$nationalPart = ltrim($cleaned, '0');
return $defaultCountryCode . $nationalPart;
}
/**
* Formats normalized number for display in UI.
* e.g. 9647701234567 -> +964 770 123 4567
*/
public static function formatDisplay(string $normalized): string
{
if (str_starts_with($normalized, '964') && strlen($normalized) === 13) {
return '+964 ' . substr($normalized, 3, 3) . ' ' . substr($normalized, 6, 3) . ' ' . substr($normalized, 9);
}
if (str_starts_with($normalized, '962') && strlen($normalized) === 12) {
return '+962 ' . substr($normalized, 3, 2) . ' ' . substr($normalized, 5, 3) . ' ' . substr($normalized, 8);
}
return '+' . $normalized;
}
}