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
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* HttpEngine constructor. |
26
|
|
|
* |
27
|
|
|
* @param string $url URL of RPC server |
28
|
|
|
* @param int $timeout HTTP timeout |
29
|
|
|
*/ |
30
|
|
|
public function __construct(string $url, int $timeout = null) |
31
|
|
|
{ |
32
|
|
|
parent::__construct(); |
33
|
|
|
|
34
|
|
|
$this->headers = $this->getDefaultHeaders(); |
35
|
|
|
$this->url = $url; |
36
|
|
|
$this->timeout = $timeout ?? 5; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Send request |
41
|
|
|
* |
42
|
|
|
* @param string $request |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function send(string $request): string |
47
|
|
|
{ |
48
|
|
|
$stream = fopen(trim($this->url), 'rb', false, $this->buildContext($request)); |
49
|
|
|
|
50
|
|
|
if (!is_resource($stream)) { |
51
|
|
|
throw new ConnectionFailureException('Unable to establish a connection'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->headers = $this->getDefaultHeaders(); |
55
|
|
|
|
56
|
|
|
return stream_get_contents($stream); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Add headers to any request |
61
|
|
|
* |
62
|
|
|
* @param array $headers |
63
|
|
|
*/ |
64
|
|
|
public function addHeaders(array $headers) |
65
|
|
|
{ |
66
|
|
|
$this->headers = array_merge($this->headers, $headers); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param string $payload |
71
|
|
|
* @return resource |
72
|
|
|
*/ |
73
|
|
|
private function buildContext(string $payload) |
74
|
|
|
{ |
75
|
|
|
$options = array( |
76
|
|
|
'http' => array( |
77
|
|
|
'method' => 'POST', |
78
|
|
|
'protocol_version' => 1.1, |
79
|
|
|
'timeout' => $this->timeout, |
80
|
|
|
'max_redirects' => 2, |
81
|
|
|
'header' => implode("\r\n", $this->headers), |
82
|
|
|
'content' => $payload, |
83
|
|
|
'ignore_errors' => true, |
84
|
|
|
) |
85
|
|
|
); |
86
|
|
|
return stream_context_create($options); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
private function getDefaultHeaders(): array |
90
|
|
|
{ |
91
|
|
|
return [ |
92
|
|
|
'User-Agent: PhpJsonRpc client <https://github.com/vaderangry/PhpJsonRpc>', |
93
|
|
|
'Content-Type: application/json', |
94
|
|
|
'Accept: application/json', |
95
|
|
|
'Connection: close', |
96
|
|
|
]; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|