|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Shlinkio\Shlink\Common\IpGeolocation; |
|
5
|
|
|
|
|
6
|
|
|
use GeoIp2\Database\Reader; |
|
7
|
|
|
use GeoIp2\Exception\AddressNotFoundException; |
|
8
|
|
|
use GeoIp2\Model\City; |
|
9
|
|
|
use GeoIp2\Record\Subdivision; |
|
10
|
|
|
use MaxMind\Db\Reader\InvalidDatabaseException; |
|
11
|
|
|
use Shlinkio\Shlink\Common\Exception\WrongIpException; |
|
12
|
|
|
use function Functional\first; |
|
13
|
|
|
|
|
14
|
|
|
class GeoLite2LocationResolver implements IpLocationResolverInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var Reader |
|
18
|
|
|
*/ |
|
19
|
|
|
private $geoLiteDbReader; |
|
20
|
|
|
|
|
21
|
3 |
|
public function __construct(Reader $geoLiteDbReader) |
|
22
|
|
|
{ |
|
23
|
3 |
|
$this->geoLiteDbReader = $geoLiteDbReader; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param string $ipAddress |
|
28
|
|
|
* @return array |
|
29
|
|
|
* @throws WrongIpException |
|
30
|
|
|
*/ |
|
31
|
3 |
|
public function resolveIpLocation(string $ipAddress): array |
|
32
|
|
|
{ |
|
33
|
|
|
try { |
|
34
|
3 |
|
$city = $this->geoLiteDbReader->city($ipAddress); |
|
35
|
1 |
|
return $this->mapFields($city); |
|
36
|
2 |
|
} catch (AddressNotFoundException $e) { |
|
37
|
1 |
|
throw WrongIpException::fromIpAddress($ipAddress, $e); |
|
38
|
1 |
|
} catch (InvalidDatabaseException $e) { |
|
39
|
1 |
|
throw new WrongIpException('Provided GeoLite2 db file is invalid', 0, $e); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
private function mapFields(City $city): array |
|
44
|
|
|
{ |
|
45
|
|
|
/** @var Subdivision $region */ |
|
46
|
1 |
|
$region = first($city->subdivisions); |
|
47
|
|
|
|
|
48
|
|
|
return [ |
|
49
|
1 |
|
'country_code' => $city->country->isoCode ?? '', |
|
50
|
1 |
|
'country_name' => $city->country->name ?? '', |
|
51
|
1 |
|
'region_name' => $region->name ?? '', |
|
52
|
1 |
|
'city' => $city->city->name ?? '', |
|
53
|
1 |
|
'latitude' => $city->location->latitude ?? '', |
|
54
|
1 |
|
'longitude' => $city->location->longitude ?? '', |
|
55
|
1 |
|
'time_zone' => $city->location->timeZone ?? '', |
|
56
|
|
|
]; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|