lochmueller /
language_detection
| 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
Loading history...
|
|||
| 47 | } |
||
| 48 | } |
||
| 49 |