Passed
Pull Request — master (#115)
by Daniel
41:55 queued 26:56
created

HttpTransporter::requestContent()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 24
rs 9.8666
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
    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
    }
36
37
    /**
38
     * {@inheritDoc}
39
     */
40
    public function requestObject(Payload $payload): array
41
    {
42
        $request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);
43
44
        try {
45
            $response = $this->client->sendRequest($request);
46
        } catch (ClientExceptionInterface $clientException) {
47
            throw new TransporterException($clientException);
48
        }
49
50
        $contents = (string) $response->getBody();
51
52
        if ($response->getHeader('Content-Type')[0] === 'text/plain; charset=utf-8') {
53
            return $contents;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $contents returns the type string which is incompatible with the type-hinted return array.
Loading history...
54
        }
55
56
        try {
57
            /** @var array{error?: array{message: string, type: string, code: string}} $response */
58
            $response = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
59
        } catch (JsonException $jsonException) {
60
            throw new UnserializableResponse($jsonException);
61
        }
62
63
        if (isset($response['error'])) {
64
            throw new ErrorException($response['error']);
65
        }
66
67
        return $response;
68
    }
69
}
70