]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | ||
3 | namespace UnrealIRCd; | |
4 | ||
5 | use Exception; | |
6 | use WebSocket; | |
7 | ||
8 | class Connection | |
9 | { | |
10 | protected WebSocket\Client $connection; | |
11 | ||
12 | public function __construct(string $uri, string $api_login, array $options = null) | |
13 | { | |
14 | $context = $options["context"] ?? stream_context_create(); | |
15 | ||
16 | if (isset($options["tls_verify"]) && !$options["tls_verify"]) { | |
17 | stream_context_set_option($context, 'ssl', 'verify_peer', false); | |
18 | stream_context_set_option($context, 'ssl', 'verify_peer_name', false); | |
19 | } | |
20 | ||
21 | $this->connection = new WebSocket\Client($uri, [ | |
22 | 'context' => $context, | |
23 | 'headers' => [ | |
24 | 'Authorization' => sprintf('Basic %s', base64_encode($api_login)), | |
25 | ], | |
26 | 'timeout' => 10, | |
27 | ]); | |
28 | ||
29 | } | |
30 | ||
31 | /** | |
32 | * Encode and send a query to the RPC server. | |
33 | * | |
34 | * @note I'm not sure on the response type except that it may be either an object or array. | |
35 | * | |
36 | * @param string $method | |
37 | * @param array|null $params | |
38 | * | |
39 | * @return object|array|bool | |
40 | * @throws Exception | |
41 | */ | |
42 | public function query(string $method, array|null $params = null): object|array|bool | |
43 | { | |
44 | $id = random_int(1, 99999); | |
45 | ||
46 | $rpc = [ | |
47 | "jsonrpc" => "2.0", | |
48 | "method" => $method, | |
49 | "params" => $params, | |
50 | "id" => $id | |
51 | ]; | |
52 | ||
53 | $json_rpc = json_encode($rpc); | |
54 | ||
55 | $this->connection->text($json_rpc); | |
56 | $reply = $this->connection->receive(); | |
57 | ||
58 | $reply = json_decode($reply); | |
59 | ||
60 | if (property_exists($reply, 'reply')) { | |
61 | if($id !== $reply->id) { | |
62 | throw new Exception('Invalid ID. This is not the expected reply.'); | |
63 | } | |
64 | return $reply->response; | |
65 | } | |
66 | ||
67 | if(property_exists($reply, 'error')) { | |
68 | return $reply->error; | |
69 | } | |
70 | ||
71 | return false; | |
72 | } | |
73 | } |