|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpJsonRpc\Client; |
|
4
|
|
|
|
|
5
|
|
|
use PhpJsonRpc\Error\ConnectionFailureException; |
|
6
|
|
|
|
|
7
|
|
|
class HttpTransport extends AbstractTransport |
|
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
|
|
|
parent::__construct(); |
|
38
|
|
|
|
|
39
|
|
|
$this->url = $url; |
|
40
|
|
|
$this->timeout = $timeout ?? 5; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Send request |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $request |
|
47
|
|
|
* |
|
48
|
|
|
* @return string |
|
49
|
|
|
*/ |
|
50
|
|
|
public function send(string $request): string |
|
51
|
|
|
{ |
|
52
|
|
|
$stream = fopen(trim($this->url), 'rb', false, $this->buildContext($request)); |
|
53
|
|
|
|
|
54
|
|
|
if (!is_resource($stream)) { |
|
55
|
|
|
throw new ConnectionFailureException('Unable to establish a connection'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return stream_get_contents($stream); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Add headers to any request |
|
63
|
|
|
* |
|
64
|
|
|
* @param array $headers |
|
65
|
|
|
*/ |
|
66
|
|
|
public function addHeaders(array $headers) |
|
67
|
|
|
{ |
|
68
|
|
|
$this->headers = array_merge($this->headers, $headers); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param string $payload |
|
73
|
|
|
* @return resource |
|
74
|
|
|
*/ |
|
75
|
|
|
private function buildContext(string $payload) |
|
76
|
|
|
{ |
|
77
|
|
|
$options = array( |
|
78
|
|
|
'http' => array( |
|
79
|
|
|
'method' => 'POST', |
|
80
|
|
|
'protocol_version' => 1.1, |
|
81
|
|
|
'timeout' => $this->timeout, |
|
82
|
|
|
'max_redirects' => 2, |
|
83
|
|
|
'header' => implode("\r\n", $this->headers), |
|
84
|
|
|
'content' => $payload, |
|
85
|
|
|
'ignore_errors' => true, |
|
86
|
|
|
) |
|
87
|
|
|
); |
|
88
|
|
|
return stream_context_create($options); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|