private function executeQuery($query)
{
$request = $this->getMessageFactory()->createRequest('GET', $query);
$content = (string) $this->getHttpClient()->sendRequest($request)->getBody();
if (empty($content)) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$json = json_decode($content, true);
if (isset($json['error'])) {
switch ($json['error']['code']) {
case static::CODE_BAD_IP:
throw new InvalidArgument('The API call should include a valid IP address.');
case static::CODE_BAD_KEY:
throw new InvalidCredentials('The API call should include a API key parameter.');
case static::CODE_NOT_AUTHORIZED:
throw new InvalidCredentials('The API key associated with your request was not recognized.');
case static::CODE_ACCOUNT_INACTIVE:
throw new InvalidCredentials('The API key has not been approved or has been disabled.');
case static::CODE_LIMIT_EXCEEDED:
throw new QuotaExceeded('The service you have requested is over capacity.');
default:
throw new NoResult(sprintf('GeoIPs error %s%s%s%s - query: %s', $json['error']['code'], isset($json['error']['status']) ? ', ' . $json['error']['status'] : '', isset($json['error']['message']) ? ', ' . $json['error']['message'] : '', isset($json['error']['notes']) ? ', ' . $json['error']['notes'] : '', $query));
}
}
if (!is_array($json) || empty($json) || empty($json['response']) || empty($json['response']['code'])) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$response = $json['response'];
// Check response code
switch ($response['code']) {
case static::CODE_NOT_FOUND:
throw new NoResult();
case static::CODE_SUCCESS:
// everything is ok
break;
default:
throw new NoResult(sprintf('The GeoIPs API returned unknown result code "%s" for query: "%s".', $response['code'], $query));
}
// Make sure that we do have proper result array
if (empty($response['location']) || !is_array($response['location'])) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$location = array_map(function ($value) {
return '' === $value ? null : $value;
}, $response['location']);
$adminLevels = [];
if (null !== $location['region_name'] || null !== $location['region_code']) {
$adminLevels[] = ['name' => $location['region_name'], 'code' => $location['region_code'], 'level' => 1];
}
if (null !== $location['county_name']) {
$adminLevels[] = ['name' => $location['county_name'], 'level' => 2];
}
$results = [];
$results[] = array_merge($this->getDefaults(), array('country' => $location['country_name'], 'countryCode' => $location['country_code'], 'adminLevels' => $adminLevels, 'locality' => $location['city_name'], 'latitude' => $location['latitude'], 'longitude' => $location['longitude'], 'timezone' => $location['timezone']));
return $this->returnResults($results);
}