You are here

public function Ip2CountryResource::get in IP-based Determination of a Visitor's Country 8

Responds to GET requests for this Resource.

Parameters

string $ip_address: The IP address to look up, formatted as a dotted quad (xxx.xxx.xxx.xxx).

Return value

\Drupal\rest\ResourceResponse The response containing the 2-character ISO 3166-2 country code for the given IP address.

Throws

\Symfony\Component\HttpKernel\Exception\NotFoundHttpException Thrown when the IP address is not assigned to a country.

\Symfony\Component\HttpKernel\Exception\BadRequestHttpException Thrown when the given IP address is not valid.

File

src/Plugin/rest/resource/Ip2CountryResource.php, line 84

Class

Ip2CountryResource
Provides a resource for looking up IP addresses.

Namespace

Drupal\ip2country\Plugin\rest\resource

Code

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.'));
}