Skip to content

Commit f615831

Browse files
committed
Use libphonenumber library to normalize customer phone number
1 parent 775a9eb commit f615831

File tree

3 files changed

+163
-11
lines changed

3 files changed

+163
-11
lines changed

src/backend/app/Helpers/PhoneNumberNormalizer.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
namespace App\Helpers;
44

5+
use Propaganistas\LaravelPhone\PhoneNumber;
6+
57
class PhoneNumberNormalizer {
68
/**
7-
* Normalize a phone number to canonical format: +<digits only>.
8-
* Strips spaces, hyphens, parentheses, dots, and other non-digit characters.
9+
* Normalize a phone number to E.164 format using libphonenumber.
10+
* Trims whitespace, prepends '+' if missing, then formats via PhoneNumber::formatE164().
911
*/
1012
public static function normalize(?string $phone): ?string {
1113
if ($phone === null || trim($phone) === '') {
@@ -14,12 +16,11 @@ public static function normalize(?string $phone): ?string {
1416

1517
$phone = trim($phone);
1618
$hasPlus = str_starts_with($phone, '+');
17-
$digits = preg_replace('/\D/', '', $phone);
1819

19-
if ($digits === '' || $digits === null) {
20-
return null;
21-
}
20+
$phone = $hasPlus ? $phone : '+'.$phone;
21+
22+
$phoneNumber = new PhoneNumber($phone);
2223

23-
return $hasPlus ? '+'.$digits : '+'.$digits;
24+
return $phoneNumber->formatE164();
2425
}
2526
}

src/backend/composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"parsecsv/php-parsecsv": "^1.3",
2929
"phpoffice/phpspreadsheet": "^1.7",
3030
"predis/predis": "^1.1.7",
31+
"propaganistas/laravel-phone": "^6.0",
3132
"pusher/pusher-php-server": "^7.0",
3233
"spatie/geocoder": "^3.14",
3334
"spatie/laravel-backup": "^9.0",

src/backend/composer.lock

Lines changed: 154 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)