Files
laravel-manager-packagist/src/Support/Leads/Phone.php
T
2026-12-05 17:00:22 +00:00

48 lines
1.7 KiB
PHP

<?php
namespace IriksIT\Manager\Support\Leads;
/**
* A phone number as people write it ("06 12 34 56 78", "+31 6 12345678") turned into digits with the country code. A number that
* starts with a single 0 is taken to be of the home country (`manager.leads.country_code`, 31 unless the site says otherwise).
*/
final class Phone
{
/** "31612345678", or null for anything that is no phone number. */
public static function international(string $number): ?string
{
$number = trim($number);
if ($number === '' || preg_match('/^[\d\s().+\-\/]+$/', $number) !== 1) {
return null;
}
// "+31 (0)6 12345678": the zero between brackets is not dialled after a country code.
$number = str_starts_with($number, '+') || str_starts_with($number, '00') ? str_replace('(0)', '', $number) : $number;
$digits = preg_replace('/\D+/', '', $number) ?? '';
if (str_starts_with($number, '+')) {
// already has its country code
} elseif (str_starts_with($digits, '00')) {
$digits = substr($digits, 2);
} elseif (str_starts_with($digits, '0')) {
$digits = self::country().substr($digits, 1);
}
return strlen($digits) >= 9 && strlen($digits) <= 15 ? $digits : null;
}
/** Whether the number is of the home country. */
public static function isHome(string $number): bool
{
$digits = self::international($number);
return $digits !== null && str_starts_with($digits, self::country());
}
private static function country(): string
{
return preg_replace('/\D+/', '', (string) config('manager.leads.country_code', '31')) ?: '31';
}
}