Completed
Push — master ( 4a3e49...406f94 )
by Alejandro
16s queued 12s
created

IpApiLocationResolver::mapFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 10
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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