Created
June 6, 2017 11:19
-
-
Save kelunik/0f043950e006c198b66e823d7d18d15d to your computer and use it in GitHub Desktop.
A simple RESP parser based on Amp\Parser.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Amp\Parser\Parser; | |
class RespParser extends Parser { | |
private $onResponse; | |
public function __construct(callable $onResponse) { | |
$this->onResponse = $onResponse; | |
parent::__construct($this->parse()); | |
} | |
private function parse() { | |
while (true) { | |
$response = yield from $this->parseSingle(); | |
($this->onResponse)($response); | |
} | |
} | |
private function parseSingle() { | |
$firstLine = yield "\r\n"; | |
\assert(\strlen($firstLine) > 0); | |
$type = $firstLine[0]; | |
$value = \substr($firstLine, 1); | |
switch ($type) { | |
case "+": | |
return $value; | |
case ":": | |
return (int) $value; | |
case "*": | |
$arraySize = (int) $value; | |
$values = []; | |
while ($arraySize-- > 0) { | |
$values[] = yield from $this->parseSingle(); | |
} | |
return $values; | |
case "$": | |
$length = (int) $value; | |
if ($length === -1) { | |
$payload = null; | |
} else { | |
$payload = yield ($length + 2); | |
$payload = \substr($payload, 0, -2); | |
} | |
return $payload; | |
case "-": | |
return new RespError($value); | |
default: | |
throw new ParseException(\sprintf( | |
"Unknown RESP data type: %s", | |
$type | |
)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment