|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Shlinkio\Shlink\IpGeolocation\Resolver; |
|
5
|
|
|
|
|
6
|
|
|
use GuzzleHttp\Client; |
|
7
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
|
8
|
|
|
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException; |
|
9
|
|
|
use Shlinkio\Shlink\Common\Exception\WrongIpException; |
|
10
|
|
|
use Shlinkio\Shlink\IpGeolocation\Model; |
|
11
|
|
|
use Shlinkio\Shlink\IpGeolocation\Resolver\IpLocationResolverInterface; |
|
12
|
|
|
|
|
13
|
|
|
use function Shlinkio\Shlink\Common\json_decode; |
|
14
|
|
|
use function sprintf; |
|
15
|
|
|
|
|
16
|
|
|
class IpApiLocationResolver implements IpLocationResolverInterface |
|
17
|
|
|
{ |
|
18
|
|
|
private const SERVICE_PATTERN = 'http://ip-api.com/json/%s'; |
|
19
|
|
|
|
|
20
|
|
|
/** @var Client */ |
|
21
|
|
|
private $httpClient; |
|
22
|
|
|
|
|
23
|
2 |
|
public function __construct(Client $httpClient) |
|
24
|
|
|
{ |
|
25
|
2 |
|
$this->httpClient = $httpClient; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @throws WrongIpException |
|
30
|
|
|
*/ |
|
31
|
2 |
|
public function resolveIpLocation(string $ipAddress): Model\Location |
|
32
|
|
|
{ |
|
33
|
|
|
try { |
|
34
|
2 |
|
$response = $this->httpClient->get(sprintf(self::SERVICE_PATTERN, $ipAddress)); |
|
35
|
1 |
|
return $this->mapFields(json_decode((string) $response->getBody())); |
|
36
|
1 |
|
} catch (GuzzleException $e) { |
|
37
|
1 |
|
throw WrongIpException::fromIpAddress($ipAddress, $e); |
|
38
|
|
|
} catch (InvalidArgumentException $e) { |
|
39
|
|
|
throw new WrongIpException('IP-API returned invalid body while locating IP address', 0, $e); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
private function mapFields(array $entry): Model\Location |
|
44
|
|
|
{ |
|
45
|
1 |
|
return new Model\Location( |
|
46
|
1 |
|
(string) ($entry['countryCode'] ?? ''), |
|
47
|
1 |
|
(string) ($entry['country'] ?? ''), |
|
48
|
1 |
|
(string) ($entry['regionName'] ?? ''), |
|
49
|
1 |
|
(string) ($entry['city'] ?? ''), |
|
50
|
1 |
|
(float) ($entry['lat'] ?? 0.0), |
|
51
|
1 |
|
(float) ($entry['lon'] ?? 0.0), |
|
52
|
1 |
|
(string) ($entry['timezone'] ?? '') |
|
53
|
|
|
); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|