1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CodeblogPro\GeoLocation\Application\GeoIpRemoteServices; |
4
|
|
|
|
5
|
|
|
use CodeblogPro\GeoLocation\Application\Exceptions\ConnectException; |
6
|
|
|
use CodeblogPro\GeoLocation\Application\Interfaces\IpAddressInterface; |
7
|
|
|
use CodeblogPro\GeoLocation\Application\Interfaces\LanguageInterface; |
8
|
|
|
use CodeblogPro\GeoLocation\Application\Interfaces\RemoteServicesOptions; |
9
|
|
|
use CodeblogPro\GeoLocation\Application\Exceptions\IncorrectResponseContent; |
10
|
|
|
use CodeblogPro\GeoLocationAddress\LocationInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Psr\Http\Message\RequestInterface; |
13
|
|
|
use GuzzleHttp; |
14
|
|
|
|
15
|
|
|
abstract class TemplateOfWorkingWithRemoteServiceApi |
16
|
|
|
{ |
17
|
|
|
protected RemoteServicesOptions $options; |
|
|
|
|
18
|
|
|
|
19
|
|
|
abstract protected function getLocationByResponse( |
20
|
|
|
ResponseInterface $response, |
21
|
|
|
LanguageInterface $language |
22
|
|
|
): LocationInterface; |
23
|
|
|
|
24
|
|
|
abstract protected function prepareRequest(IpAddressInterface $ipAddress): RequestInterface; |
25
|
|
|
|
26
|
3 |
|
public function __construct(RemoteServicesOptions $options) |
27
|
|
|
{ |
28
|
3 |
|
$this->options = $options; |
29
|
3 |
|
} |
30
|
|
|
|
31
|
|
|
public function getLocation(IpAddressInterface $ipAddress, LanguageInterface $language): LocationInterface |
32
|
|
|
{ |
33
|
|
|
$request = $this->prepareRequest($ipAddress); |
34
|
|
|
$response = $this->request($request); |
35
|
|
|
|
36
|
|
|
return $this->getLocationByResponse($response, $language); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function tryToRequest(RequestInterface $request): ResponseInterface |
40
|
|
|
{ |
41
|
|
|
$client = new GuzzleHttp\Client(); |
42
|
|
|
|
43
|
|
|
return $client->send($request, ['timeout' => 2]); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
protected function request(RequestInterface $request): ResponseInterface |
47
|
|
|
{ |
48
|
|
|
try { |
49
|
|
|
$response = $this->tryToRequest($request); |
50
|
|
|
|
51
|
|
|
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) { |
52
|
|
|
throw new ConnectException('Response statud code = ' . $response->getStatusCode()); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $response; |
56
|
|
|
} catch (\Throwable $exception) { |
57
|
|
|
throw new ConnectException($exception->getMessage()); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected function getContentFromJson(string $contentJson): object |
62
|
|
|
{ |
63
|
|
|
$content = json_decode($contentJson); |
64
|
|
|
|
65
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
66
|
|
|
throw new IncorrectResponseContent(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $content; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|