IpLocation::getClient()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lochmueller\LanguageDetection\Service;
6
7
use Psr\Http\Message\RequestFactoryInterface;
8
use TYPO3\CMS\Core\Http\Client\GuzzleClientFactory;
9
use TYPO3\CMS\Core\Information\Typo3Version;
10
use TYPO3\CMS\Core\Utility\GeneralUtility;
11
12
class IpLocation
13
{
14
    public function __construct(private RequestFactoryInterface $requestFactory) {}
15
16
    public function getCountryCode(string $ip): ?string
17
    {
18
        if ($ip === '') {
19
            return null;
20
        }
21
        $urlService = 'http://www.geoplugin.net/php.gp?ip=' . $ip;
22
        try {
23
            $request = $this->requestFactory->createRequest('GET', $urlService);
24
            $response = $this->getClient()->send($request);
25
26
            if ($response->getStatusCode() !== 200) {
27
                throw new IpLocationException('Missing information in response', 123781);
28
            }
29
            $result = (array)unserialize((string)$response->getBody(), ['allowed_classes' => false]);
30
31
            if (empty($result) || (int)$result['geoplugin_status'] === 404) {
32
                throw new IpLocationException('No valid data', 162378);
33
            }
34
35
            return $result['geoplugin_countryCode'] ?? null;
36
        } catch (IpLocationException $exc) {
37
            return null;
38
        }
39
    }
40
41
    protected function getClient(): \Psr\Http\Client\ClientInterface
42
    {
43
        if (GeneralUtility::makeInstance(Typo3Version::class)->getMajorVersion() >= 12) {
44
            return GeneralUtility::makeInstance(GuzzleClientFactory::class)->getClient();
45
        }
46
        return GuzzleClientFactory::getClient();
0 ignored issues
show
Bug Best Practice introduced by
The expression return TYPO3\CMS\Core\Ht...entFactory::getClient() returns the type GuzzleHttp\ClientInterface which is incompatible with the type-hinted return Psr\Http\Client\ClientInterface.
Loading history...
47
    }
48
}
49