|
| 1 | +<?php |
| 2 | +declare(strict_types = 1); |
| 3 | + |
| 4 | +namespace LanguageServer; |
| 5 | + |
| 6 | +use AdvancedJsonRpc; |
| 7 | +use Sabre\Event\Promise; |
| 8 | + |
| 9 | +class ClientHandler |
| 10 | +{ |
| 11 | + /** |
| 12 | + * @var ProtocolReader |
| 13 | + */ |
| 14 | + public $protocolReader; |
| 15 | + |
| 16 | + /** |
| 17 | + * @var ProtocolWriter |
| 18 | + */ |
| 19 | + public $protocolWriter; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var IdGenerator |
| 23 | + */ |
| 24 | + public $idGenerator; |
| 25 | + |
| 26 | + public function __construct(ProtocolReader $protocolReader, ProtocolWriter $protocolWriter) |
| 27 | + { |
| 28 | + $this->protocolReader = $protocolReader; |
| 29 | + $this->protocolWriter = $protocolWriter; |
| 30 | + $this->idGenerator = new IdGenerator; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Sends a request to the client and returns a promise that is resolved with the result or rejected with the error |
| 35 | + * |
| 36 | + * @param string $method The method to call |
| 37 | + * @param array|object $params The method parameters |
| 38 | + * @return Promise <mixed> Resolved with the result of the request or rejected with an error |
| 39 | + */ |
| 40 | + public function request(string $method, $params): Promise |
| 41 | + { |
| 42 | + $id = $this->idGenerator->generate(); |
| 43 | + return $this->protocolWriter->write( |
| 44 | + new Protocol\Message( |
| 45 | + new AdvancedJsonRpc\Request($id, $method, (object)$params) |
| 46 | + ) |
| 47 | + )->then(function () use ($id) { |
| 48 | + $promise = new Promise; |
| 49 | + $listener = function (Protocol\Message $msg) use ($id, $promise, &$listener) { |
| 50 | + if (AdvancedJsonRpc\Response::isResponse($msg->body) && $msg->body->id === $id) { |
| 51 | + // Received a response |
| 52 | + $this->protocolReader->removeListener('message', $listener); |
| 53 | + if (AdvancedJsonRpc\SuccessResponse::isSuccessResponse($msg->body)) { |
| 54 | + $promise->fulfill($msg->body->result); |
| 55 | + } else { |
| 56 | + $promise->reject($msg->body->error); |
| 57 | + } |
| 58 | + } |
| 59 | + }; |
| 60 | + $this->protocolReader->on('message', $listener); |
| 61 | + return $promise; |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Sends a notification to the client |
| 67 | + * |
| 68 | + * @param string $method The method to call |
| 69 | + * @param array|object $params The method parameters |
| 70 | + * @return Promise <null> Will be resolved as soon as the notification has been sent |
| 71 | + */ |
| 72 | + public function notify(string $method, $params): Promise |
| 73 | + { |
| 74 | + $id = $this->idGenerator->generate(); |
| 75 | + return $this->protocolWriter->write( |
| 76 | + new Protocol\Message( |
| 77 | + new AdvancedJsonRpc\Notification($method, (object)$params) |
| 78 | + ) |
| 79 | + ); |
| 80 | + } |
| 81 | +} |
0 commit comments