SymfonyTransport::send()   A
last analyzed

Complexity

Conditions 2
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 21
ccs 10
cts 10
cp 1
rs 9.8666
cc 2
nc 4
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 Strider2038\JsonRpcClient\Exception\RemoteProcedureCallFailedException;
14
use Strider2038\JsonRpcClient\Transport\TransportInterface;
15
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
16
use Symfony\Contracts\HttpClient\HttpClientInterface;
17
use Symfony\Contracts\HttpClient\ResponseInterface;
18
19
/**
20
 * @internal
21
 *
22
 * @author Igor Lazarev <[email protected]>
23
 */
24
class SymfonyTransport implements TransportInterface
25
{
26
    private HttpClientInterface $client;
27
28
    public function __construct(HttpClientInterface $client)
29 19
    {
30
        $this->client = $client;
31 19
    }
32 19
33
    /**
34
     * @throws RemoteProcedureCallFailedException
35
     */
36
    public function send(string $request): string
37 13
    {
38
        try {
39
            $response = $this->client->request('POST', '', [
40 13
                'body'    => $request,
41 13
                'headers' => [
42
                    'Content-Type' => 'application/json',
43
                ],
44
            ]);
45
46
            $this->validateResponse($response);
47 12
            $content = $response->getContent();
48 9
        } catch (ExceptionInterface $exception) {
49 4
            throw new RemoteProcedureCallFailedException(
50 3
                sprintf('JSON RPC request failed with error: %s.', $exception->getMessage()),
51 3
                0,
52 3
                $exception
53 3
            );
54
        }
55
56
        return $content;
57 9
    }
58
59
    /**
60
     * @throws RemoteProcedureCallFailedException
61
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
62
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
63
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
64
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
65
     */
66
    private function validateResponse(ResponseInterface $response): void
67 12
    {
68
        $statusCode = $response->getStatusCode();
69 12
70
        if (200 !== $statusCode) {
71 10
            throw new RemoteProcedureCallFailedException(
72 1
                sprintf('JSON RPC request failed with error %d: %s.', $statusCode, $response->getContent(false))
73 1
            );
74
        }
75
    }
76
}
77