Ip2CountryResource.php in IP-based Determination of a Visitor's Country 8
File
src/Plugin/rest/resource/Ip2CountryResource.php
View source
<?php
namespace Drupal\ip2country\Plugin\rest\resource;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\ip2country\Ip2CountryLookupInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Ip2CountryResource extends ResourceBase implements ContainerFactoryPluginInterface {
protected $ip2countryLookup;
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Ip2CountryLookupInterface $ip2countryLookup) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->ip2countryLookup = $ip2countryLookup;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->getParameter('serializer.formats'), $container
->get('logger.factory')
->get('rest'), $container
->get('ip2country.lookup'));
}
public function get($ip_address = NULL) {
if (filter_var($ip_address, FILTER_VALIDATE_IP)) {
$country_code = $this->ip2countryLookup
->getCountry($ip_address);
if ($country_code) {
return new ResourceResponse($country_code);
}
throw new NotFoundHttpException($this
->t('IP Address @ip is not assigned to a country.', [
'@ip' => $ip_address,
]));
}
throw new BadRequestHttpException($this
->t('The IP address you entered is invalid. Please enter an address in the form xxx.xxx.xxx.xxx where xxx is between 0 and 255 inclusive.'));
}
}