Created
March 26, 2017 14:09
-
-
Save shadowhand/daa43f0a5c4fe51aa9cda470fc434899 to your computer and use it in GitHub Desktop.
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 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); | |
} |
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 | |
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