Files
wordpress-theme-aksrt/inc/helpers/aksrt-phone.php
T

69 lines
1.9 KiB
PHP

<?php
/**
* Phone number masking helpers shared by the account UI and the
* phone-match verification endpoint.
*
* The hidden middle segment adapts to the number: domestic 11-digit
* numbers hide 4 digits (138****1234), longer international numbers
* hide length-7 digits (min 4), so the digit-entry UI renders one box
* per hidden digit.
*
* @package AKSRT
*/
if (!defined('ABSPATH')) {
exit;
}
/**
* Split a bound phone number into visible prefix / hidden middle / visible suffix.
*
* Works on the digit core of the number (a leading "+" is ignored for the split
* but reported back). Returns null when the number holds fewer than 8 digits —
* such numbers cannot be verified by middle-digit entry.
*
* @return array{prefix:string,hidden:string,suffix:string,hidden_length:int,leading_plus:bool}|null
*/
function aksrt_phone_mask_parts(string $phone): ?array {
$phone = trim($phone);
if ($phone === '') {
return null;
}
$leading_plus = $phone[0] === '+';
$core = preg_replace('/\D+/', '', $phone);
$length = strlen($core);
if ($length < 8) {
return null;
}
$hidden_length = min(11, max(4, $length - 7));
$suffix_length = $length - 3 - $hidden_length;
if ($suffix_length < 1) {
return null;
}
return [
'prefix' => substr($core, 0, 3),
'hidden' => substr($core, 3, $hidden_length),
'suffix' => substr($core, $length - $suffix_length),
'hidden_length' => $hidden_length,
'leading_plus' => $leading_plus,
];
}
/**
* Masked display form of a phone number, e.g. 138****1234 or +861******1234.
* Falls back to the raw number when it cannot be masked.
*/
function aksrt_phone_mask_display(string $phone): string {
$parts = aksrt_phone_mask_parts($phone);
if ($parts === null) {
return $phone;
}
$mask = str_repeat('*', (int) $parts['hidden_length']);
$display = $parts['prefix'] . $mask . $parts['suffix'];
return $parts['leading_plus'] ? '+' . $display : $display;
}