-
Notifications
You must be signed in to change notification settings - Fork 21
Custom Input
Paul Crovella edited this page Jan 13, 2019
·
1 revision
Input in this package is abstracted away behind the InputStream
interface.
namespace pcrov\JsonReader\InputStream;
interface InputStream
{
/**
* @return string|null A chunk of bytes or null when there's nothing left to read.
*/
public function read();
}
If you've got an input that isn't supported out of the box it's generally pretty easy to make an adapter for it. The interface consists of a single public method, read
, which returns either a string (a bunch of bytes which gets read into the lexer's buffer), or null at the end of the input.
To then use your custom input stream you'll initialize the reader via init
, e.g.:
$reader = new JsonReader;
$reader->init(new JsonParser(new Lexer($yerCustomInputStream)));
For example, adding support for PSR-7 streams was as simple as:
use Psr\Http\Message\StreamInterface;
final class Psr7Stream implements InputStream
{
const CHUNK_SIZE = 8192;
private $stream;
public function __construct(StreamInterface $stream)
{
if (!$stream->isReadable()) {
throw new IOException("Stream must be readable.");
}
$this->stream = $stream;
}
public function read()
{
$stream = $this->stream;
try {
return $stream->eof() ? null : $stream->read(self::CHUNK_SIZE);
} catch (\RuntimeException $e) {
return null;
}
}
}
It and others can be found in src/InputStream.