|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the slince/spike package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Slince <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Spike\Common\Protocol; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* {@link https://github.com/clue/php-json-stream/blob/master/src/StreamingJsonParser.php}. |
|
16
|
|
|
*/ |
|
17
|
|
|
class StreamingJsonParser |
|
18
|
|
|
{ |
|
19
|
|
|
private $buffer = ''; |
|
20
|
|
|
private $endCharacter = null; |
|
21
|
|
|
|
|
22
|
|
|
private $assoc = true; |
|
23
|
|
|
|
|
24
|
|
|
public function push($chunk) |
|
25
|
|
|
{ |
|
26
|
|
|
$objects = array(); |
|
27
|
|
|
|
|
28
|
|
|
while ('' !== $chunk) { |
|
29
|
|
|
if (null === $this->endCharacter) { |
|
30
|
|
|
// trim leading whitespace |
|
31
|
|
|
$chunk = ltrim($chunk); |
|
32
|
|
|
|
|
33
|
|
|
if ('' === $chunk) { |
|
34
|
|
|
// only whitespace => skip chunk |
|
35
|
|
|
break; |
|
36
|
|
|
} elseif ('[' === $chunk[0]) { |
|
37
|
|
|
// array/list delimiter |
|
38
|
|
|
$this->endCharacter = ']'; |
|
39
|
|
|
} elseif ('{' === $chunk[0]) { |
|
40
|
|
|
// object/hash delimiter |
|
41
|
|
|
$this->endCharacter = '}'; |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$pos = strpos($chunk, $this->endCharacter); |
|
46
|
|
|
|
|
47
|
|
|
// no end found in chunk => must be part of segment, wait for next chunk |
|
48
|
|
|
if (false === $pos) { |
|
49
|
|
|
$this->buffer .= $chunk; |
|
50
|
|
|
break; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
// possible end found in chunk => select possible segment from buffer, keep remaining chunk |
|
54
|
|
|
$this->buffer .= substr($chunk, 0, $pos + 1); |
|
55
|
|
|
$chunk = substr($chunk, $pos + 1); |
|
56
|
|
|
|
|
57
|
|
|
// try to parse |
|
58
|
|
|
$json = json_decode($this->buffer, $this->assoc); |
|
59
|
|
|
|
|
60
|
|
|
// successfully parsed |
|
61
|
|
|
if (null !== $json) { |
|
62
|
|
|
$objects[] = $json; |
|
63
|
|
|
|
|
64
|
|
|
// clear parsed buffer and continue checking remaining chunk |
|
65
|
|
|
$this->buffer = ''; |
|
66
|
|
|
$this->endCharacter = null; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $objects; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function isEmpty() |
|
74
|
|
|
{ |
|
75
|
|
|
return '' === $this->buffer; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* Get the reset of data. |
|
80
|
|
|
* |
|
81
|
|
|
* @return string |
|
82
|
|
|
*/ |
|
83
|
|
|
public function getRemainingChunk() |
|
84
|
|
|
{ |
|
85
|
|
|
return $this->buffer; |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|