1
0
Fork 0
php-language-server/src/Protocol/Message.php

65 lines
1.5 KiB
PHP
Raw Normal View History

2016-08-22 15:32:31 +00:00
<?php
2016-08-25 13:27:14 +00:00
declare(strict_types = 1);
2016-08-22 15:32:31 +00:00
2016-08-22 20:40:16 +00:00
namespace LanguageServer\Protocol;
2016-08-25 13:27:14 +00:00
use AdvancedJsonRpc\Message as MessageBody;
class Message
2016-08-22 15:32:31 +00:00
{
/**
2016-08-25 13:27:14 +00:00
* @var \AdvancedJsonRpc\Message
*/
public $body;
/**
* @var string[]
2016-08-22 15:32:31 +00:00
*/
2016-08-25 13:27:14 +00:00
public $headers;
2016-08-22 20:40:16 +00:00
/**
2016-08-25 13:27:14 +00:00
* Parses a message
2016-08-22 20:40:16 +00:00
*
2016-08-25 13:27:14 +00:00
* @param string $msg
* @return Message
2016-08-22 20:40:16 +00:00
*/
2016-08-25 13:27:14 +00:00
public static function parse(string $msg): Message
2016-08-22 20:40:16 +00:00
{
2016-08-25 13:27:14 +00:00
$obj = new self;
$parts = explode("\r\n", $msg);
$obj->body = MessageBody::parse(array_pop($parts));
foreach ($parts as $line) {
if ($line) {
$pair = explode(': ', $line);
$obj->headers[$pair[0]] = $pair[1];
2016-08-22 20:40:16 +00:00
}
}
2016-08-25 13:27:14 +00:00
return $obj;
}
2016-08-22 20:40:16 +00:00
2016-08-25 13:27:14 +00:00
/**
* @param \AdvancedJsonRpc\Message $body
* @param string[] $headers
*/
public function __construct(MessageBody $body = null, array $headers = [])
{
$this->body = $body;
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/vscode-jsonrpc; charset=utf8';
}
$this->headers = $headers;
}
2016-08-22 20:40:16 +00:00
2016-08-25 13:27:14 +00:00
public function __toString(): string
{
$body = (string)$this->body;
$contentLength = strlen($body);
$this->headers['Content-Length'] = $contentLength;
$headers = '';
foreach ($this->headers as $name => $value) {
$headers .= "$name: $value\r\n";
}
return $headers . "\r\n" . $body;
2016-08-22 20:40:16 +00:00
}
2016-08-22 15:32:31 +00:00
}