|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the Geocoder package. |
| 7 | + * For the full copyright and license information, please view the LICENSE |
| 8 | + * file that was distributed with this source code. |
| 9 | + * |
| 10 | + * @license MIT License |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Geocoder\Provider\IpApi; |
| 14 | + |
| 15 | +use Geocoder\Collection; |
| 16 | +use Geocoder\Exception\InvalidArgument; |
| 17 | +use Geocoder\Exception\InvalidCredentials; |
| 18 | +use Geocoder\Exception\InvalidServerResponse; |
| 19 | +use Geocoder\Exception\UnsupportedOperation; |
| 20 | +use Geocoder\Http\Provider\AbstractHttpProvider; |
| 21 | +use Geocoder\Model\AddressBuilder; |
| 22 | +use Geocoder\Model\AddressCollection; |
| 23 | +use Geocoder\Provider\IpApi\Model\IpApiLocation; |
| 24 | +use Geocoder\Query\GeocodeQuery; |
| 25 | +use Geocoder\Query\ReverseQuery; |
| 26 | +use Psr\Http\Client\ClientInterface; |
| 27 | + |
| 28 | +final class IpApi extends AbstractHttpProvider |
| 29 | +{ |
| 30 | + private const URL = '{host_prefix}ip-api.com/json/{ip}'; |
| 31 | + |
| 32 | + private const FIELDS = 'status,message,lat,lon,city,district,zip,country,countryCode,timezone,regionName,region,proxy,hosting'; |
| 33 | + |
| 34 | + private string|null $apiKey; |
| 35 | + |
| 36 | + public function __construct(ClientInterface $client, string $apiKey = null) |
| 37 | + { |
| 38 | + $this->apiKey = $apiKey; |
| 39 | + parent::__construct($client); |
| 40 | + } |
| 41 | + |
| 42 | + #[\Override] |
| 43 | + public function geocodeQuery(GeocodeQuery $query): Collection |
| 44 | + { |
| 45 | + $ip = $query->getText(); |
| 46 | + |
| 47 | + if (!filter_var($ip, FILTER_VALIDATE_IP)) { |
| 48 | + throw new UnsupportedOperation('The ip-api provider does not support street addresses.'); |
| 49 | + } |
| 50 | + |
| 51 | + if (in_array($ip, ['127.0.0.1', '::1'])) { |
| 52 | + return new AddressCollection([$this->getLocationForLocalhost()]); |
| 53 | + } |
| 54 | + |
| 55 | + $url = $this->buildUrl($ip, $query->getLocale()); |
| 56 | + |
| 57 | + $body = $this->getUrlContents($url); |
| 58 | + |
| 59 | + $data = json_decode($body, true, 512, JSON_THROW_ON_ERROR); |
| 60 | + if ('fail' === $data['status']) { |
| 61 | + $this->throwError($data['message']); |
| 62 | + } |
| 63 | + |
| 64 | + $location = $this->buildLocation($data); |
| 65 | + |
| 66 | + return new AddressCollection([$location]); |
| 67 | + } |
| 68 | + |
| 69 | + #[\Override] |
| 70 | + public function reverseQuery(ReverseQuery $query): Collection |
| 71 | + { |
| 72 | + throw new UnsupportedOperation('The ip-api provider is not able to do reverse geocoding.'); |
| 73 | + } |
| 74 | + |
| 75 | + #[\Override] |
| 76 | + public function getName(): string |
| 77 | + { |
| 78 | + return 'ip-api'; |
| 79 | + } |
| 80 | + |
| 81 | + public function buildUrl(string $ip, string|null $locale): string |
| 82 | + { |
| 83 | + $baseUrl = strtr(self::URL, [ |
| 84 | + '{host_prefix}' => $this->apiKey ? 'https://pro.' : 'http://', |
| 85 | + '{ip}' => $ip, |
| 86 | + ]); |
| 87 | + |
| 88 | + $query = http_build_query(array_filter([ |
| 89 | + 'key' => $this->apiKey, |
| 90 | + 'lang' => $locale, |
| 91 | + 'fields' => self::FIELDS, |
| 92 | + ])); |
| 93 | + |
| 94 | + return $baseUrl.'?'.$query; |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * @param array<string, scalar> $data |
| 99 | + */ |
| 100 | + private function buildLocation(array $data): IpApiLocation |
| 101 | + { |
| 102 | + $data = array_map( |
| 103 | + static fn ($value) => '' === $value ? null : $value, |
| 104 | + $data, |
| 105 | + ); |
| 106 | + |
| 107 | + $builder = new AddressBuilder($this->getName()); |
| 108 | + $builder->setCoordinates($data['lat'], $data['lon']); |
| 109 | + $builder->setLocality($data['city']); |
| 110 | + $builder->setSubLocality($data['district']); |
| 111 | + $builder->setPostalCode($data['zip']); |
| 112 | + $builder->setCountry($data['country']); |
| 113 | + $builder->setCountryCode($data['countryCode']); |
| 114 | + $builder->setTimezone($data['timezone']); |
| 115 | + |
| 116 | + if ($data['regionName']) { |
| 117 | + $builder->addAdminLevel(1, $data['regionName'], $data['region']); |
| 118 | + } |
| 119 | + |
| 120 | + /** @var IpApiLocation $location */ |
| 121 | + $location = $builder->build(IpApiLocation::class); |
| 122 | + |
| 123 | + return $location |
| 124 | + ->withIsProxy($data['proxy']) |
| 125 | + ->withIsHosting($data['hosting']); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * @see https://members.ip-api.com/faq#errors |
| 130 | + * |
| 131 | + * @return never |
| 132 | + */ |
| 133 | + private function throwError(string $message) |
| 134 | + { |
| 135 | + if ( |
| 136 | + in_array($message, ['private range', 'reserved range', 'invalid query'], true) |
| 137 | + || str_contains('Origin restriction', $message) |
| 138 | + || str_contains('IP range restriction', $message) |
| 139 | + || str_contains('Calling IP restriction', $message) |
| 140 | + ) { |
| 141 | + throw new InvalidArgument($message); |
| 142 | + } |
| 143 | + |
| 144 | + if ( |
| 145 | + str_contains('invalid/expired ke', $message) |
| 146 | + || str_contains('no API key supplied', $message) |
| 147 | + ) { |
| 148 | + throw new InvalidCredentials($message); |
| 149 | + } |
| 150 | + |
| 151 | + throw new InvalidServerResponse($message); |
| 152 | + } |
| 153 | +} |
0 commit comments