Passed
Push — master ( ee8fa9...afffd0 )
by Tim
03:17
created

IpLocation::getCountryCode()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
c 0
b 0
f 0
nc 10
nop 1
dl 0
loc 22
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LD\LanguageDetection\Service;
6
7
use Psr\Http\Message\RequestFactoryInterface;
8
use TYPO3\CMS\Core\Http\Client\GuzzleClientFactory;
9
10
class IpLocation
11
{
12
    private RequestFactoryInterface $requestFactory;
13
14
    public function __construct(RequestFactoryInterface $requestFactory)
15
    {
16
        $this->requestFactory = $requestFactory;
17
    }
18
19
    public function getCountryCode(string $ip): ?string
20
    {
21
        if ('' === $ip) {
22
            return null;
23
        }
24
        $urlService = 'http://www.geoplugin.net/php.gp?ip=' . $ip;
25
        try {
26
            $request = $this->requestFactory->createRequest('GET', $urlService);
27
            $response = GuzzleClientFactory::getClient()->send($request);
28
29
            if (200 !== $response->getStatusCode()) {
30
                throw new IpLocationException('Missing information in response', 123781);
31
            }
32
            $result = (array)unserialize((string)$response->getBody());
33
34
            if (empty($result) || 404 === (int)$result['geoplugin_status']) {
35
                throw new IpLocationException('No valid data', 162378);
36
            }
37
38
            return $result['geoplugin_countryCode'] ?? null;
39
        } catch (IpLocationException $exc) {
40
            return null;
41
        }
42
    }
43
}
44