|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Dead simple, high performance, drop-in bridge to Golang RPC with zero dependencies |
|
4
|
|
|
* |
|
5
|
|
|
* @author Wolfy-J |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace Spiral\Goridge; |
|
9
|
|
|
|
|
10
|
|
|
use Spiral\Goridge\Exceptions\ServiceException; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Packs client requests and responses using JSON. |
|
14
|
|
|
*/ |
|
15
|
|
|
class JsonRPC |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var \Spiral\Goridge\ConnectionInterface */ |
|
18
|
|
|
private $conn; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @param \Spiral\Goridge\ConnectionInterface $conn |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct(ConnectionInterface $conn) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->conn = $conn; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param string $method |
|
30
|
|
|
* @param mixed $argument An input argument or array of arguments for complex types. |
|
31
|
|
|
* @param int $flags Payload control flags. |
|
32
|
|
|
* |
|
33
|
|
|
* @return mixed |
|
34
|
|
|
* |
|
35
|
|
|
* @throws \Spiral\Goridge\Exceptions\TransportException |
|
36
|
|
|
* @throws \Spiral\Goridge\Exceptions\ServiceException |
|
37
|
|
|
*/ |
|
38
|
|
|
public function call(string $method, $argument, int $flags = 0) |
|
39
|
|
|
{ |
|
40
|
|
|
$this->conn->send($method); |
|
41
|
|
|
|
|
42
|
|
|
if ($flags & ConnectionInterface::RAW_BODY) { |
|
43
|
|
|
$this->conn->send($argument, $flags); |
|
44
|
|
|
} else { |
|
45
|
|
|
$body = json_encode($argument); |
|
46
|
|
|
if ($body === false) { |
|
47
|
|
|
throws new ServiceException(sprintf( |
|
|
|
|
|
|
48
|
|
|
"json error: %s", |
|
49
|
|
|
json_last_error_msg() |
|
50
|
|
|
)); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
$this->conn->send(json_encode($argument)); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
$body = $this->conn->receiveSync($flags); |
|
57
|
|
|
|
|
58
|
|
|
return $this->handleBody($body, $flags); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Handle response body. |
|
63
|
|
|
* |
|
64
|
|
|
* @param string|binary $body |
|
65
|
|
|
* @param int $flags |
|
66
|
|
|
* |
|
67
|
|
|
* @return mixed |
|
68
|
|
|
* |
|
69
|
|
|
* @throws \Spiral\Goridge\Exceptions\ServiceException |
|
70
|
|
|
*/ |
|
71
|
|
|
protected function handleBody($body, int $flags) |
|
72
|
|
|
{ |
|
73
|
|
|
if ($flags & ConnectionInterface::ERROR_BODY) { |
|
74
|
|
|
throw new ServiceException("error '$body' on '{$this->conn}'"); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
if ($flags & ConnectionInterface::RAW_BODY) { |
|
78
|
|
|
return $body; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
return json_decode($body, true); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|