]> jfr.im git - irc/unrealircd/unrealircd-rpc-php.git/blame - lib/Connection.php
Add Spamfilter support
[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
a18591f9 12 public function __construct(string $uri, string $api_login, array $options = null)
50d6d455
D
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
a18591f9
D
37 * @param array|null $params
38 *
8d5a112f
D
39 * @return object|array|bool
40 * @throws Exception
41 */
a18591f9 42 public function query(string $method, array|null $params = null): object|array|bool
50d6d455 43 {
8d5a112f
D
44 $id = random_int(1, 99999);
45
50d6d455
D
46 $rpc = [
47 "jsonrpc" => "2.0",
48 "method" => $method,
49 "params" => $params,
8d5a112f 50 "id" => $id
50d6d455
D
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
65cc0295 60 if (property_exists($reply, 'result')) {
b2be0552 61 if($id !== $reply->id) {
8d5a112f
D
62 throw new Exception('Invalid ID. This is not the expected reply.');
63 }
657dad63 64 return $reply->result;
50d6d455 65 }
bea99f3a
D
66
67 if(property_exists($reply, 'error')) {
68 return $reply->error;
69 }
70
71 return false;
50d6d455 72 }
7c7017a2
BM
73
74 public function user(): User
75 {
76 return new User($this);
77 }
78
79 public function channel(): Channel
80 {
81 return new Channel($this);
82 }
83
e4de690d 84 public function serverban(): ServerBan
7c7017a2 85 {
e4de690d 86 return new ServerBan($this);
7c7017a2
BM
87 }
88
89 public function spamfilter(): Spamfilter
90 {
91 return new Spamfilter($this);
92 }
562c96c0 93}