You are here

class Ip2CountryLookup in IP-based Determination of a Visitor's Country 8

The ip2country.lookup service.

Hierarchy

Expanded class hierarchy of Ip2CountryLookup

1 file declares its use of Ip2CountryLookup
Ip2CountryCommands.php in src/Commands/Ip2CountryCommands.php
1 string reference to 'Ip2CountryLookup'
ip2country.services.yml in ./ip2country.services.yml
ip2country.services.yml
1 service uses Ip2CountryLookup
ip2country.lookup in ./ip2country.services.yml
Drupal\ip2country\Ip2CountryLookup

File

src/Ip2CountryLookup.php, line 11

Namespace

Drupal\ip2country
View source
class Ip2CountryLookup implements Ip2CountryLookupInterface {

  /**
   * The current request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $currentRequest;

  /**
   * The database connection to use.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Constructs an Ip2CountryLookup object.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(RequestStack $requestStack, Connection $connection) {
    $this->currentRequest = $requestStack
      ->getCurrentRequest();
    $this->connection = $connection;
  }

  /**
   * {@inheritdoc}
   */
  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;
    }

    // Locate IP within range.
    $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;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Ip2CountryLookup::$connection protected property The database connection to use.
Ip2CountryLookup::$currentRequest protected property The current request.
Ip2CountryLookup::getCountry public function Gets the ISO 3166 2-character country code from the IP address. Overrides Ip2CountryLookupInterface::getCountry
Ip2CountryLookup::__construct public function Constructs an Ip2CountryLookup object.