mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-28 10:33:49 +00:00
add function to format phonenumber using twilio (if configured)
This commit is contained in:
@@ -53,6 +53,7 @@ class PhonenumberHelper
|
||||
protected $cachePool;
|
||||
|
||||
const LOOKUP_URI = 'https://lookups.twilio.com/v1/PhoneNumbers/%s';
|
||||
const FORMAT_URI = 'https://lookups.twilio.com/v1/PhoneNumbers/%s';
|
||||
|
||||
|
||||
public function __construct(
|
||||
@@ -121,6 +122,64 @@ class PhonenumberHelper
|
||||
return \in_array($validation, [ 'landline', 'voip' ]);
|
||||
}
|
||||
|
||||
public function format($phonenumber)
|
||||
{
|
||||
return $this->performTwilioFormat($phonenumber);
|
||||
}
|
||||
|
||||
protected function performTwilioFormat($phonenumber)
|
||||
{
|
||||
if (FALSE === $this->isPhonenumberValidationConfigured()) {
|
||||
return $phonenumber;
|
||||
}
|
||||
|
||||
// filter only number
|
||||
$filtered = \preg_replace("/[^0-9]/", "", $phonenumber);
|
||||
|
||||
$item = $this->cachePool->getItem('pnum_format_nat_'.$filtered);
|
||||
|
||||
if ($item->isHit()) {
|
||||
return $item->get();
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->twilioClient->get(sprintf(self::FORMAT_URI, '+'.$filtered), [
|
||||
'http_errors' => true,
|
||||
]);
|
||||
|
||||
} catch (ClientException $e) {
|
||||
$this->logger->error("[phonenumber helper] Could not format number "
|
||||
. "due to client error", [
|
||||
"message" => $e->getResponseBodySummary($e->getResponse()),
|
||||
"status_code" => $e->getResponse()->getStatusCode(),
|
||||
"phonenumber" => $phonenumber
|
||||
]);
|
||||
|
||||
return $phonenumber;
|
||||
} catch (ServerException $e) {
|
||||
$this->logger->error("[phonenumber helper] Could not format number "
|
||||
. "due to server error", [
|
||||
"message" => $e->getResponseBodySummary($e->getResponse()),
|
||||
"status_code" => $e->getResponse()->getStatusCode(),
|
||||
"phonenumber" => $phonenumber
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$format = \json_decode($response->getBody())->national_format;
|
||||
|
||||
$item
|
||||
->set($format)
|
||||
// expires after 3d
|
||||
->expiresAfter(3600 * 24 * 3)
|
||||
;
|
||||
|
||||
$this->cachePool->save($item);
|
||||
|
||||
return $format;
|
||||
}
|
||||
|
||||
protected function performTwilioLookup($phonenumber)
|
||||
{
|
||||
if (FALSE === $this->isPhonenumberValidationConfigured()) {
|
||||
|
Reference in New Issue
Block a user