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

IpLocation   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 31
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getCountryCode() 0 22 6
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