]> jfr.im git - irc/unrealircd/unrealircd-rpc-php.git/blob - lib/Connection.php
Update Connection::query to listen for a "reply" response rather than "response"...
[irc/unrealircd/unrealircd-rpc-php.git] / lib / Connection.php
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)
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 $params
38 * @return object|array|bool
39 * @throws Exception
40 */
41 public function query(string $method, array $params): object|array|bool
42 {
43 $id = random_int(1, 99999);
44
45 $rpc = [
46 "jsonrpc" => "2.0",
47 "method" => $method,
48 "params" => $params,
49 "id" => $id
50 ];
51
52 $json_rpc = json_encode($rpc);
53
54 $this->connection->text($json_rpc);
55 $reply = $this->connection->receive();
56
57 $reply = json_decode($reply);
58
59 if (property_exists($reply, 'reply')) {
60 if($id !== $reply->id) {
61 throw new Exception('Invalid ID. This is not the expected reply.');
62 }
63 return $reply->response;
64 }
65
66 if(property_exists($reply, 'error')) {
67 return $reply->error;
68 }
69
70 return false;
71 }
72 }