Repository navigation
Expand file tree
/
Copy pathReadsJsonDocuments.php
More file actions
63 lines (51 loc) · 1.61 KB
/
Copy pathReadsJsonDocuments.php
File metadata and controls
63 lines (51 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
declare(strict_types=1);
namespace Docker\Stream;
/**
* Split a body containing consecutive JSON documents into single documents.
*/
trait ReadsJsonDocuments
{
/**
* Read the next complete JSON document from $this->stream.
*
* Returns null when the body ends before a document is complete.
*/
protected function readJsonDocument(): ?string
{
$jsonFrameEnd = false;
$lastJsonChar = '';
$inquote = false;
$jsonFrame = '';
$level = 0;
while (!$jsonFrameEnd && !$this->stream->eof()) {
$jsonChar = $this->stream->read(1);
if ('"' === $jsonChar && '\\' !== $lastJsonChar) {
$inquote = !$inquote;
}
// We ignore white space when it is not part of a quoted string.
if (!$inquote && \in_array($jsonChar, [' ', "\r", "\n", "\t"], true)) {
continue;
}
if (!$inquote && \in_array($jsonChar, ['{', '['], true)) {
++$level;
}
if (!$inquote && \in_array($jsonChar, ['}', ']'], true)) {
--$level;
if (0 === $level) {
$jsonFrameEnd = true;
$jsonFrame .= $jsonChar;
$lastJsonChar = '';
continue;
}
}
$jsonFrame .= $jsonChar;
$lastJsonChar = $jsonChar;
}
// Invalid last json, or timeout, or connection close before receiving
if (!$jsonFrameEnd) {
return null;
}
return $jsonFrame;
}
}