forked from docker-php/docker-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiJsonStream.php
More file actions
82 lines (65 loc) · 2.11 KB
/
Copy pathMultiJsonStream.php
File metadata and controls
82 lines (65 loc) · 2.11 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);
namespace Docker\Stream;
use Psr\Http\Message\StreamInterface;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Represent a stream that decode a stream with multiple json in it.
*/
abstract class MultiJsonStream extends CallbackStream
{
/** @var SerializerInterface Serializer to decode incoming json object */
private $serializer;
public function __construct(StreamInterface $stream, SerializerInterface $serializer)
{
parent::__construct($stream);
$this->serializer = $serializer;
}
/**
* {@inheritdoc}
*/
protected function readFrame()
{
$jsonFrameEnd = false;
$lastJsonChar = '';
$inquote = false;
$jsonFrame = '';
$level = 0;
// This is a
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 $this->serializer->deserialize($jsonFrame, 'Docker\\API\\Model\\'.$this->getDecodeClass(), 'json');
}
/**
* Get the decode class to pass to serializer.
*
* @return string
*/
abstract protected function getDecodeClass();
}