Completed
Push — master ( 4bee86...913926 )
by Denis
04:17
created

HttpTransport::buildContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 1
1
<?php
2
3
namespace PhpJsonRpc\Client;
4
5
use PhpJsonRpc\Error\ConnectionFailureException;
6
7
class HttpTransport implements TransportInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    private $url;
13
14
    /**
15
     * @var int
16
     */
17
    private $timeout;
18
19
    /**
20
     * @var array
21
     */
22
    private $headers = [
23
        'User-Agent: PhpJsonRpc client <https://github.com/vaderangry/PhpJsonRpc>',
24
        'Content-Type: application/json',
25
        'Accept: application/json',
26
        'Connection: close',
27
    ];
28
29
    /**
30
     * HttpEngine constructor.
31
     *
32
     * @param string $url     URL of RPC server
33
     * @param int    $timeout HTTP timeout
34
     */
35
    public function __construct(string $url, int $timeout = null)
36
    {
37
        $this->url     = $url;
38
        $this->timeout = $timeout ?? 5;
39
    }
40
41
    public function request(string $request): string
42
    {
43
        $stream = fopen(trim($this->url), 'r', false, $this->buildContext($request));
44
45
        if (!is_resource($stream)) {
46
            throw new ConnectionFailureException('Unable to establish a connection');
47
        }
48
49
        return @json_decode(stream_get_contents($stream), true);
50
    }
51
52
    /**
53
     * @param string $payload
54
     * @return resource
55
     */
56
    private function buildContext(string $payload)
57
    {
58
        $options = array(
59
            'http' => array(
60
                'method'           => 'POST',
61
                'protocol_version' => 1.1,
62
                'timeout'          => $this->timeout,
63
                'max_redirects'    => 2,
64
                'header'           => implode("\r\n", $this->headers),
65
                'content'          => $payload,
66
                'ignore_errors'    => true,
67
            )
68
        );
69
        return stream_context_create($options);
70
    }
71
}
72