]> jfr.im git - irc/unrealircd/unrealircd-rpc-php.git/blame - lib/Connection.php
This should be everything working now.
[irc/unrealircd/unrealircd-rpc-php.git] / lib / Connection.php
CommitLineData
562c96c0
BM
1<?php
2
50d6d455 3namespace UnrealIRCd;
562c96c0 4
8d5a112f 5use Exception;
562c96c0
BM
6use WebSocket;
7
8class Connection
9{
50d6d455
D
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
8d5a112f 16 if (isset($options["tls_verify"]) && !$options["tls_verify"]) {
50d6d455
D
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
8d5a112f
D
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
50d6d455 42 {
8d5a112f
D
43 $id = random_int(1, 99999);
44
50d6d455
D
45 $rpc = [
46 "jsonrpc" => "2.0",
47 "method" => $method,
48 "params" => $params,
8d5a112f 49 "id" => $id
50d6d455
D
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 ($reply->response) {
b2be0552 60 if($id !== $reply->id) {
8d5a112f
D
61 throw new Exception('Invalid ID. This is not the expected reply.');
62 }
63
50d6d455
D
64 return $reply->response;
65 } else {
66 return false;
67 }
68 }
562c96c0 69}