1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace SlevomatCsobGateway\Api\Driver; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use GuzzleHttp\Psr7\Request; |
7
|
|
|
use GuzzleHttp\RequestOptions; |
8
|
|
|
use SlevomatCsobGateway\Api\ApiClientDriver; |
9
|
|
|
use SlevomatCsobGateway\Api\HttpMethod; |
10
|
|
|
use SlevomatCsobGateway\Api\Response; |
11
|
|
|
use SlevomatCsobGateway\Api\ResponseCode; |
12
|
|
|
use Throwable; |
13
|
|
|
use function array_map; |
14
|
|
|
use function array_shift; |
15
|
|
|
use function count; |
16
|
|
|
use function json_decode; |
17
|
|
|
use function json_encode; |
18
|
|
|
|
19
|
|
|
class GuzzleDriver implements ApiClientDriver |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** @var Client */ |
23
|
|
|
private $client; |
24
|
|
|
|
25
|
|
|
public function __construct(Client $client) |
26
|
|
|
{ |
27
|
|
|
$this->client = $client; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param HttpMethod $method |
32
|
|
|
* @param string $url |
33
|
|
|
* @param mixed[]|null $data |
34
|
|
|
* @param string[] $headers |
35
|
|
|
* @return Response |
36
|
|
|
* |
37
|
|
|
* @throws GuzzleDriverException |
38
|
|
|
*/ |
39
|
|
|
public function request(HttpMethod $method, string $url, ?array $data, array $headers = []): Response |
40
|
|
|
{ |
41
|
|
|
$postData = null; |
42
|
|
|
if ($method->equalsValue(HttpMethod::POST) || $method->equalsValue(HttpMethod::PUT)) { |
43
|
|
|
$postData = (string) json_encode($data); |
44
|
|
|
} |
45
|
|
|
$headers += ['Content-Type' => 'application/json']; |
46
|
|
|
$request = new Request($method->getValue(), $url, $headers, $postData); |
47
|
|
|
|
48
|
|
|
try { |
49
|
|
|
$httpResponse = $this->client->send($request, [ |
50
|
|
|
RequestOptions::HTTP_ERRORS => false, |
51
|
|
|
RequestOptions::ALLOW_REDIRECTS => false, |
52
|
|
|
]); |
53
|
|
|
|
54
|
|
|
$responseCode = ResponseCode::get($httpResponse->getStatusCode()); |
55
|
|
|
|
56
|
|
|
$responseHeaders = array_map(static function ($item) { |
57
|
|
|
return count($item) > 1 |
58
|
|
|
? $item |
59
|
|
|
: array_shift($item); |
60
|
|
|
}, $httpResponse->getHeaders()); |
61
|
|
|
|
62
|
|
|
return new Response( |
63
|
|
|
$responseCode, |
64
|
|
|
json_decode((string) $httpResponse->getBody(), true), |
65
|
|
|
$responseHeaders |
66
|
|
|
); |
67
|
|
|
} catch (Throwable $e) { |
68
|
|
|
throw new GuzzleDriverException($e); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} |
73
|
|
|
|