icecave/duct

增量流式JSON解析器。

2.0.2 2015-04-23 00:16 UTC

This package is auto-updated.

Last update: 2024-08-29 03:59:16 UTC


README

Build Status Code Coverage Latest Version

Duct 是一个用于增量解析连续JSON值流的PHP库。

composer require icecave/duct

Duct 设计用于从数据流中解析顺序JSON值,而无需在JSON规范之外进行帧或标记。

示例

简单解析

Duct 可以在单个 Parser::parse() 调用中使用来解析多个JSON文档。提供的JSON字符串必须包含完整的值。

use Icecave\Duct\Parser;

$parser = new Parser;
$values = $parser->parse('[ 1, 2, 3 ] [ 4, 5, 6 ]');

assert($values[0] === [1, 2, 3]);
assert($values[1] === [4, 5, 6]);

增量解析

使用 Parser::feed()values()finalize() 方法也可以实现异步、增量解析。

use Icecave\Duct\Parser;

$parser = new Parser;

// JSON data can be fed to the parser incrementally.
$parser->feed('[ 1, ');

// An array of completed values can be retreived using the values() method.
// At this point no complete object has been parsed so the array is empty.
$values = $parser->values();
assert(0 === count($values));

// As more data is fed to the parser, we now have one value available, an array
// of elements 1, 2, 3.
$parser->feed('2, 3 ][ 4, 5');
$values = $parser->values();
assert(1 === count($values));
assert($values[0] == [1, 2, 3]);

// Note that calling values() is destructive, in that any complete objects are
// removed from the parser and will not be returned by future calls to values().
$values = $parser->values();
assert(0 === count($values));

// Finally we feed the remaining part of the second object to the parser and the
// second value becomes available.
$parser->feed(', 6 ]');
$values = $parser->values();
assert(1 === count($values));
assert($values[0] == [4, 5, 6]);

// At the end of the JSON stream, finalize is called to parse any data remaining
// in the buffer. An exception is thrown if the buffer contains an incomplete
// value.
$parser->finalize();

// In this case there were no additional values.
$values = $parser->values();
assert(0 === count($values));

基于事件解析

Duct 还提供了 EventedParser,这是一个类似于JavaScript库 Clarinet 的事件驱动增量解析器。事件管理由流行的PHP事件库 Événement 提供。

根据上面的示例,使用了 feed()finalize() 方法,但是没有 values() 方法。相反,以下事件在解析缓冲区时发出。

  • document-open:在开始JSON文档时发出
  • document-close:在解析完整个JSON文档后发出
  • array-open:在遇到数组开方括号时发出
  • array-close:在遇到数组闭方括号时发出
  • object-open:在遇到对象开花括号时发出
  • object-close:在遇到对象闭花括号时发出
  • object-key(字符串 $key):在遇到对象键时发出
  • value(混合 $value):在遇到标量或null时发出,包括在对象和数组内部
  • error(Exception $error):在遇到语法错误时发出