Ip2CountryLookup.php in IP-based Determination of a Visitor's Country 8
File
src/Ip2CountryLookup.php
View source
<?php
namespace Drupal\ip2country;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\RequestStack;
class Ip2CountryLookup implements Ip2CountryLookupInterface {
protected $currentRequest;
protected $connection;
public function __construct(RequestStack $requestStack, Connection $connection) {
$this->currentRequest = $requestStack
->getCurrentRequest();
$this->connection = $connection;
}
public function getCountry($ip_address = NULL) {
$ip_address = isset($ip_address) ? $ip_address : $this->currentRequest
->getClientIp();
$ipl = ip2long($ip_address);
if (is_int($ip_address)) {
$ipl = $ip_address;
}
$sql = "SELECT country FROM {ip2country}\n WHERE (:start >= ip_range_first AND :end <= ip_range_last) LIMIT 1";
$result = $this->connection
->query($sql, [
':start' => $ipl,
':end' => $ipl,
])
->fetchField();
return $result;
}
}