violet-php/streaming-json-encoder

JsonStream should not always be seekable

georgebarbarosie opened this issue · 1 comments

If a BufferJsonEncoder encodes a Generator, or a value that points to a Generator, JsonStream is no longer seekable. This breaks passing JsonStream as the response body of some frameworks. Slim v4 in particular attempts to read the first byte of a seekable body to determine if the response is empty, then rewinds.

The exception triggered is Cannot rewind a generator that was already run, caused by calling AbstractJsonEncoder::getIterator() twice on the same generator (JsonBuffer::rewind() calls AbstractJsonEncoder::rewind() which resets the stack).

I am pretty sure it's impossible to make JsonStream detect if it's safe to return isSeekable()==true, but I think it would be useful to have a setSeekable(bool $value) method to mark a stream as unseekable for such cases.

The fact that this library even attempts to seek shows it's not a streaming library. We should probably use skolodyazhnyy/json-stream instead, except it's even more dead than this library.