netgescon-day0/app/Support/PhoneNumber.php

67 lines
1.6 KiB
PHP
Executable File

<?php
namespace App\Support;
class PhoneNumber
{
public static function normalizeDigits(string $value): string
{
return preg_replace('/\D+/', '', $value) ?? '';
}
public static function normalizeForMatch(string $value): string
{
$clean = preg_replace('/[^0-9+]/', '', trim($value)) ?? '';
if ($clean === '') {
return '';
}
if (str_starts_with($clean, '00')) {
return '+' . substr($clean, 2);
}
return $clean;
}
public static function toE164Italy(?string $value, string $defaultPrefix = '+39'): ?string
{
$raw = trim((string) $value);
if ($raw === '') {
return null;
}
$normalized = self::normalizeForMatch($raw);
if ($normalized === '') {
return null;
}
if (str_starts_with($normalized, '+')) {
return $normalized;
}
if (str_starts_with($normalized, '39') && strlen($normalized) >= 10) {
return '+' . $normalized;
}
$prefixDigits = self::normalizeDigits($defaultPrefix);
if ($prefixDigits === '') {
$prefixDigits = '39';
}
return '+' . $prefixDigits . ltrim($normalized, '0');
}
public static function splitItaly(?string $value): array
{
$e164 = self::toE164Italy($value);
if ($e164 === null) {
return [null, null, null];
}
if (str_starts_with($e164, '+39')) {
return [$e164, '+39', substr($e164, 3) ?: null];
}
return [$e164, null, ltrim($e164, '+') ?: null];
}
}