phaxio-1.1.0/src/Services/Numbers.php
src/Services/Numbers.php
<?php
namespace Drupal\phaxio\Services;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Cache\CacheFactoryInterface;
/**
* Service class for Phaxio phone number handling.
*/
class Numbers extends PhaxioBase {
/**
* Numbers being handled in this instance.
*
* @var array
*/
private $numbers;
/**
* Cache bin.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
private $bin;
/**
* Initialize properties.
*/
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $moduleHandler, CacheFactoryInterface $cacheFactory) {
parent::__construct($config_factory, $moduleHandler, $cacheFactory);
$this->bin = $this->cacheFactory->get('phaxio');
}
/**
* Get all purchased numbers.
*/
public function getAllNumbers($country = NULL): Numbers {
$params = [];
$cache_key = 'allnumbers';
if ($country) {
$params['country_code'] = $country;
$cache_key .= $country;
}
if ($cache = $this->bin->get($cache_key)) {
$this->numbers = $cache->data;
return $this;
}
$this->numbers = $this->client()->phoneNumbers()->getList($params);
$this->bin->set($cache_key, $this->numbers);
return $this;
}
/**
* Filter numbers by country.
*
* This is necessary because the IncomingPhoneNumbers endpoint
* does not return locality information for purchased numbers.
*
* @param string $country
* ISO country code.
*/
public function filterByCountry(string $country) {
$countries = [
'US' => 'United States of America',
'CA' => 'Canada',
];
if (isset($countries[$country])) {
foreach ($this->numbers as $key => $value) {
if ($value->country != $countries[$country]) {
$value->exclude = TRUE;
}
};
}
return $this;
}
/**
* Magic method to get a string representation of the found numbers.
*/
public function __toString() {
$closure = function ($r, $n) {
if (!($n->exclude ?? FALSE)) {
$r .= $n->phone_number . "\n";
}
return $r;
};
return array_reduce((array) $this->numbers, $closure);
}
/**
* Magic method to get numbers in a palatable form.
*
* @param string $name
* The name of the parameter.
*/
public function __get(string $name) {
if ($name == 'numbers') {
$closure = function ($n) {
if (!($n->exclude ?? FALSE)) {
return [
'phone_number' => $n->phone_number,
];
}
};
return array_filter(array_map($closure, (array) $this->numbers));
}
elseif ($name == 'details') {
$closure = function ($n) {
if (!($n->exclude ?? FALSE)) {
return [
'phone_number' => $n->phone_number,
'city' => $n->city,
'state' => $n->state,
'country' => $n->country,
];
}
};
return array_filter(array_map($closure, (array) $this->numbers));
}
}
/**
* Manual cache reset function.
*/
public function resetCache() {
$this->bin->deleteAll();
return $this;
}
}
