X-Git-Url: https://jfr.im/git/irc/unrealircd/unrealircd-rpc-php.git/blobdiff_plain/50d6d455cb1467608911a838ba626d5ad85f6cdb..65cc029518c695d21785172ac42701f067b0a885:/lib/Connection.php diff --git a/lib/Connection.php b/lib/Connection.php index 774d33e..3b0066c 100644 --- a/lib/Connection.php +++ b/lib/Connection.php @@ -2,17 +2,18 @@ namespace UnrealIRCd; +use Exception; use WebSocket; class Connection { protected WebSocket\Client $connection; - public function __construct(string $uri, string $api_login, array $options = []) + public function __construct(string $uri, string $api_login, array $options = null) { $context = $options["context"] ?? stream_context_create(); - if (isset($options["tls_verify"]) && ($options["tls_verify"] == false)) { + if (isset($options["tls_verify"]) && !$options["tls_verify"]) { stream_context_set_option($context, 'ssl', 'verify_peer', false); stream_context_set_option($context, 'ssl', 'verify_peer_name', false); } @@ -27,13 +28,26 @@ class Connection } - public function query(string $method, array $params = []) + /** + * Encode and send a query to the RPC server. + * + * @note I'm not sure on the response type except that it may be either an object or array. + * + * @param string $method + * @param array|null $params + * + * @return object|array|bool + * @throws Exception + */ + public function query(string $method, array|null $params = null): object|array|bool { + $id = random_int(1, 99999); + $rpc = [ "jsonrpc" => "2.0", "method" => $method, "params" => $params, - "id" => 123 + "id" => $id ]; $json_rpc = json_encode($rpc); @@ -43,10 +57,17 @@ class Connection $reply = json_decode($reply); - if ($reply->response) { + if (property_exists($reply, 'result')) { + if($id !== $reply->id) { + throw new Exception('Invalid ID. This is not the expected reply.'); + } return $reply->response; - } else { - return false; } + + if(property_exists($reply, 'error')) { + return $reply->error; + } + + return false; } }