1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace InShore\Bookwhen\Transporters; |
6
|
|
|
|
7
|
|
|
use JsonException; |
8
|
|
|
use InShore\Bookwhen\Contracts\TransporterContract; |
9
|
|
|
use InShore\Bookwhen\Exceptions\ErrorException; |
10
|
|
|
use InShore\Bookwhen\Exceptions\TransporterException; |
11
|
|
|
use InShore\Bookwhen\Exceptions\UnserializableResponse; |
12
|
|
|
use InShore\Bookwhen\ValueObjects\Transporter\BaseUri; |
13
|
|
|
use InShore\Bookwhen\ValueObjects\Transporter\Headers; |
14
|
|
|
use InShore\Bookwhen\ValueObjects\Transporter\Payload; |
15
|
|
|
use InShore\Bookwhen\ValueObjects\Transporter\QueryParams; |
16
|
|
|
use Psr\Http\Client\ClientExceptionInterface; |
17
|
|
|
use Psr\Http\Client\ClientInterface; |
18
|
|
|
use Psr\Http\Message\ResponseInterface; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @internal |
22
|
|
|
*/ |
23
|
|
|
final class HttpTransporter implements TransporterContract |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Creates a new Http Transporter instance. |
27
|
|
|
*/ |
28
|
20 |
|
public function __construct( |
29
|
|
|
private readonly ClientInterface $client, |
30
|
|
|
private readonly BaseUri $baseUri, |
31
|
|
|
private readonly Headers $headers, |
32
|
|
|
private readonly QueryParams $queryParams, |
33
|
|
|
) { |
34
|
|
|
// .. |
35
|
20 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritDoc} |
39
|
|
|
*/ |
40
|
11 |
|
public function requestObject(Payload $payload): array |
41
|
|
|
{ |
42
|
11 |
|
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams); |
43
|
|
|
|
44
|
|
|
try { |
45
|
11 |
|
$response = $this->client->sendRequest($request); |
46
|
|
|
} catch (ClientExceptionInterface $clientException) { |
47
|
|
|
throw new TransporterException($clientException); |
48
|
|
|
} |
49
|
|
|
|
50
|
11 |
|
$contents = (string) $response->getBody(); |
51
|
|
|
|
52
|
|
|
// if ('text/plain; charset=utf-8' === $response->getHeader('Content-Type')[0]) { |
53
|
|
|
// return $contents; |
54
|
|
|
// } |
55
|
|
|
|
56
|
|
|
try { |
57
|
|
|
/** @var array{error?: array{message: string, type: string, code: string}} $response */ |
58
|
11 |
|
$response = json_decode($contents, true, 512, JSON_THROW_ON_ERROR); |
59
|
|
|
} catch (JsonException $jsonException) { |
60
|
|
|
throw new UnserializableResponse($jsonException); |
61
|
|
|
} |
62
|
|
|
|
63
|
11 |
|
if (isset($response['error'])) { |
64
|
|
|
throw new ErrorException($response['error']); |
65
|
|
|
} |
66
|
|
|
|
67
|
11 |
|
return $response; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|