Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Created March 26, 2017 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadowhand/daa43f0a5c4fe51aa9cda470fc434899 to your computer and use it in GitHub Desktop.
Save shadowhand/daa43f0a5c4fe51aa9cda470fc434899 to your computer and use it in GitHub Desktop.
<?php
use Acme\JsonStreamParser;
use Bcn\Component\Json\Reader;
// Request is a PSR-7 request with a JSON body.
// The JSON body must be a list! Something like:
//
// [{...}, ...]
//
$stream = $request->getBody()->detach();
// Create the Reader instance.
// https://github.com/skolodyazhnyy/json-stream#json-reader
$reader = new Reader($stream);
// Wrap the reader in a parser.
$parser = new JsonStreamParser($reader);
// Calling parse() will start a generator.
foreach ($parser->parse() as $item) {
print_r($item);
}
<?php
namespace Acme;
use Bcn\Component\Json\Reader;
use Generator;
class JsonStreamParser
{
/**
* @var Reader
*/
private $reader;
public function __construct(Reader $reader)
{
$this->reader = $reader;
}
/**
* Parse the JSON stream, yielding each item in the list.
*/
public function parse(): Generator
{
// https://github.com/skolodyazhnyy/json-stream#json-reader
$this->reader->enter(Reader::TYPE_ARRAY);
while ($item = $this->reader->read()) {
yield $item;
}
$this->reader->leave();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment