1
0
Fork 0
php-language-server/src/ProtocolStreamReader.php

67 lines
2.3 KiB
PHP
Raw Normal View History

2016-08-25 13:27:14 +00:00
<?php
declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Protocol\Message;
use AdvancedJsonRpc\Message as MessageBody;
2016-10-31 10:47:21 +00:00
use Sabre\Event\{Loop, Emitter};
2016-08-25 13:27:14 +00:00
2016-10-31 10:47:21 +00:00
class ProtocolStreamReader extends Emitter implements ProtocolReader
2016-08-25 13:27:14 +00:00
{
const PARSE_HEADERS = 1;
const PARSE_BODY = 2;
2016-08-25 13:27:14 +00:00
private $input;
private $parsingMode = self::PARSE_HEADERS;
2016-08-25 13:27:14 +00:00
private $buffer = '';
private $headers = [];
private $contentLength;
/**
* @param resource $input
*/
public function __construct($input)
{
$this->input = $input;
$this->on('close', function () {
Loop\removeReadStream($this->input);
});
Loop\addReadStream($this->input, function () {
if (feof($this->input)) {
// If stream_select reported a status change for this stream,
// but the stream is EOF, it means it was closed.
$this->emit('close');
return;
}
while (($c = fgetc($this->input)) !== false && $c !== '') {
2016-08-25 13:27:14 +00:00
$this->buffer .= $c;
switch ($this->parsingMode) {
case self::PARSE_HEADERS:
2016-08-25 13:27:14 +00:00
if ($this->buffer === "\r\n") {
$this->parsingMode = self::PARSE_BODY;
2016-08-25 13:27:14 +00:00
$this->contentLength = (int)$this->headers['Content-Length'];
$this->buffer = '';
} else if (substr($this->buffer, -2) === "\r\n") {
$parts = explode(':', $this->buffer);
$this->headers[$parts[0]] = trim($parts[1]);
$this->buffer = '';
}
break;
case self::PARSE_BODY:
2016-08-25 13:27:14 +00:00
if (strlen($this->buffer) === $this->contentLength) {
2016-10-31 10:47:21 +00:00
$msg = new Message(MessageBody::parse($this->buffer), $this->headers);
$this->emit('message', [$msg]);
$this->parsingMode = self::PARSE_HEADERS;
2016-08-25 13:27:14 +00:00
$this->headers = [];
$this->buffer = '';
}
break;
}
}
});
}
}