Completed
Pull Request — master (#7)
by Igor
04:25
created

SymfonyTransport::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
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
    /** @var HttpClientInterface */
27
    private $client;
28
29
    public function __construct(HttpClientInterface $client)
30
    {
31
        $this->client = $client;
32
    }
33
34
    /**
35
     * @throws RemoteProcedureCallFailedException
36
     */
37
    public function send(string $request): string
38
    {
39
        try {
40
            $response = $this->client->request('POST', '', [
41
                'body'    => $request,
42
                'headers' => [
43
                    'Content-Type' => 'application/json',
44
                ],
45
            ]);
46
47
            $this->validateResponse($response);
48
            $content = $response->getContent();
49
        } catch (ExceptionInterface $exception) {
50
            throw new RemoteProcedureCallFailedException(
51
                sprintf('JSON RPC request failed with error: %s.', $exception->getMessage()),
52
                0,
53
                $exception
54
            );
55
        }
56
57
        return $content;
58
    }
59
60
    /**
61
     * @throws RemoteProcedureCallFailedException
62
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
63
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
64
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
65
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
66
     */
67
    private function validateResponse(ResponseInterface $response): void
68
    {
69
        $statusCode = $response->getStatusCode();
70
71
        if (200 !== $statusCode) {
72
            throw new RemoteProcedureCallFailedException(
73
                sprintf('JSON RPC request failed with error %d: %s.', $statusCode, $response->getContent(false))
74
            );
75
        }
76
    }
77
}
78