GuzzleTransport::getResponseContents()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/*
3
 * This file is part of JSON RPC Client.
4
 *
5
 * (c) Igor Lazarev <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Strider2038\JsonRpcClient\Transport\Http;
12
13
use GuzzleHttp\ClientInterface;
14
use GuzzleHttp\Exception\RequestException;
15
use Psr\Http\Message\ResponseInterface;
16
use Strider2038\JsonRpcClient\Exception\RemoteProcedureCallFailedException;
17
use Strider2038\JsonRpcClient\Transport\TransportInterface;
18
19
/**
20
 * @internal
21
 *
22
 * @author Igor Lazarev <[email protected]>
23
 */
24
class GuzzleTransport implements TransportInterface
25
{
26
    private ClientInterface $client;
27
28
    public function __construct(ClientInterface $client)
29 9
    {
30
        $this->client = $client;
31 9
    }
32 9
33
    /**
34
     * @throws RemoteProcedureCallFailedException
35
     * @throws \GuzzleHttp\Exception\GuzzleException
36
     */
37
    public function send(string $request): string
38 8
    {
39
        $response = $this->sendRequest($request);
40 8
41
        return $this->getResponseContents($response);
42 6
    }
43
44
    /**
45
     * @throws RemoteProcedureCallFailedException
46
     * @throws \GuzzleHttp\Exception\GuzzleException
47
     */
48
    private function sendRequest(string $request): ResponseInterface
49 8
    {
50
        try {
51
            $response = $this->client->request('POST', '', [
52 8
                'body'    => $request,
53 8
                'headers' => [
54
                    'Content-Type' => 'application/json',
55
                ],
56
            ]);
57
        } catch (RequestException $exception) {
58 2
            throw new RemoteProcedureCallFailedException(
59 2
                sprintf('JSON RPC request failed with error: %s.', $exception->getMessage()),
60 2
                0,
61 2
                $exception
62 2
            );
63
        }
64
65
        return $response;
66 6
    }
67
68
    /**
69
     * @throws RemoteProcedureCallFailedException
70
     */
71
    private function getResponseContents(ResponseInterface $response): string
72 6
    {
73
        $statusCode = $response->getStatusCode();
74 6
        $body = $response->getBody();
75 6
        $contents = $body->getContents();
76 6
77
        if (200 !== $statusCode) {
78 6
            throw new RemoteProcedureCallFailedException(
79 1
                sprintf('JSON RPC request failed with error %d: %s.', $statusCode, $contents)
80 1
            );
81
        }
82
83
        return $contents;
84 5
    }
85
}
86