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\RelayInterface as Relay; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* RPC bridge to Golang net/rpc package over Goridge protocol. |
14
|
|
|
*/ |
15
|
|
|
class RPC |
16
|
|
|
{ |
17
|
|
|
/** @var Relay */ |
18
|
|
|
private $relay; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param Relay $relay |
22
|
|
|
*/ |
23
|
|
|
public function __construct(Relay $relay) |
24
|
|
|
{ |
25
|
|
|
$this->relay = $relay; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $method |
30
|
|
|
* @param mixed $payload An binary data or array of arguments for complex types. |
31
|
|
|
* @param int $flags Payload control flags. |
32
|
|
|
* |
33
|
|
|
* @return mixed |
34
|
|
|
* |
35
|
|
|
* @throws Exceptions\RelayException |
36
|
|
|
* @throws Exceptions\ServiceException |
37
|
|
|
*/ |
38
|
|
|
public function call(string $method, $payload, int $flags = 0) |
39
|
|
|
{ |
40
|
|
|
$this->relay->send($method, Relay::PAYLOAD_CONTROL | Relay::PAYLOAD_RAW); |
41
|
|
|
|
42
|
|
|
if ($flags & Relay::PAYLOAD_RAW) { |
43
|
|
|
$this->relay->send($payload, $flags); |
44
|
|
|
} else { |
45
|
|
|
$body = json_encode($payload); |
46
|
|
|
if ($body === false) { |
47
|
|
|
throw new Exceptions\ServiceException(sprintf("json encode: %s", json_last_error_msg())); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$this->relay->send($body); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// wait for the response |
54
|
|
|
$body = $this->relay->receiveSync($flags); |
55
|
|
|
|
56
|
|
|
return $this->handleBody($body, $flags); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Handle response body. |
61
|
|
|
* |
62
|
|
|
* @param string $body |
63
|
|
|
* @param int $flags |
64
|
|
|
* |
65
|
|
|
* @return mixed |
66
|
|
|
* |
67
|
|
|
* @throws Exceptions\ServiceException |
68
|
|
|
*/ |
69
|
|
|
protected function handleBody($body, int $flags) |
70
|
|
|
{ |
71
|
|
|
if ($flags & Relay::PAYLOAD_ERROR && $flags & Relay::PAYLOAD_RAW) { |
72
|
|
|
throw new Exceptions\ServiceException("error '$body' on '{$this->relay}'"); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
if ($flags & Relay::PAYLOAD_RAW) { |
76
|
|
|
return $body; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return json_decode($body, true); |
80
|
|
|
} |
81
|
|
|
} |