1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace SergeyNezbritskiy\NovaPoshta; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Client as HttpClient; |
8
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
9
|
|
|
use GuzzleHttp\RequestOptions; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class Connection |
14
|
|
|
*/ |
15
|
|
|
class Connection |
16
|
|
|
{ |
17
|
|
|
private const API_URI = 'https://api.novaposhta.ua/v2.0/json/'; |
18
|
|
|
private const ERROR_MSG_TEMPLATE = 'Connection to Nova Poshta API failed: %s'; |
19
|
|
|
private string $apiKey; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string $apiKey |
23
|
|
|
*/ |
24
|
1 |
|
public function __construct(string $apiKey) |
25
|
|
|
{ |
26
|
1 |
|
$this->apiKey = $apiKey; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $model |
31
|
|
|
* @param string $method |
32
|
|
|
* @param array $params |
33
|
|
|
* @return array |
34
|
|
|
* @throws NovaPoshtaApiException |
35
|
|
|
*/ |
36
|
1 |
|
public function post(string $model, string $method, array $params = []): array |
37
|
|
|
{ |
38
|
|
|
try { |
39
|
1 |
|
$request = [ |
40
|
1 |
|
'apiKey' => $this->apiKey, |
41
|
1 |
|
'modelName' => $model, |
42
|
1 |
|
'calledMethod' => $method, |
43
|
1 |
|
'methodProperties' => $params |
44
|
1 |
|
]; |
45
|
1 |
|
$response = $this->getClient()->request('POST', self::API_URI, [RequestOptions::JSON => $request]); |
46
|
1 |
|
if ($response->getStatusCode() !== 200) { |
47
|
|
|
throw new NovaPoshtaApiException(sprintf(self::ERROR_MSG_TEMPLATE, $response->getReasonPhrase())); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
$body = $this->getResponseBody($response); |
51
|
|
|
|
52
|
1 |
|
if ($body['success'] === false) { |
53
|
|
|
$error = array_shift($body['errors']) ?: array_shift($body['warnings']); |
54
|
|
|
throw new NovaPoshtaApiException(sprintf(self::ERROR_MSG_TEMPLATE, $error)); |
55
|
1 |
|
} |
56
|
|
|
return $body['data']; |
57
|
|
|
} catch (GuzzleException $e) { |
58
|
|
|
throw new NovaPoshtaApiException(sprintf(self::ERROR_MSG_TEMPLATE, $e->getMessage()), $e->getCode(), $e); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return HttpClient |
64
|
1 |
|
*/ |
65
|
|
|
private function getClient(): HttpClient |
66
|
1 |
|
{ |
67
|
|
|
return new HttpClient(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param ResponseInterface $response |
72
|
|
|
* @return array |
73
|
|
|
* @throws NovaPoshtaApiException |
74
|
1 |
|
*/ |
75
|
|
|
private function getResponseBody(ResponseInterface $response): array |
76
|
1 |
|
{ |
77
|
1 |
|
$content = $response->getBody()->getContents(); |
78
|
1 |
|
$result = json_decode($content, true); |
79
|
|
|
if (empty($result)) { |
80
|
|
|
throw new NovaPoshtaApiException('Invalid response from Nova Poshta API'); |
81
|
1 |
|
} |
82
|
|
|
return $result; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|