MultiJsonStream   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 14
c 2
b 0
f 2
lcom 1
cbo 3
dl 0
loc 67
ccs 32
cts 32
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
C readFrame() 0 44 13
getDecodeClass() 0 1 ?
1
<?php
2
3
namespace Docker\Stream;
4
use Psr\Http\Message\StreamInterface;
5
use Symfony\Component\Serializer\SerializerInterface;
6
7
/**
8
 * Represent a stream that decode a stream with multiple json in it
9
 */
10
abstract class MultiJsonStream extends CallbackStream
11
{
12
    /** @var SerializerInterface Serializer to decode incoming json object */
13
    private $serializer;
14
15 8
    public function __construct(StreamInterface $stream, SerializerInterface $serializer)
16
    {
17 8
        parent::__construct($stream);
18
19 8
        $this->serializer = $serializer;
20 8
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 8
    protected function readFrame()
26
    {
27 8
        $jsonFrameEnd = false;
28 8
        $lastJsonChar = '';
29 8
        $inquote      = false;
30 8
        $jsonFrame    = "";
31 8
        $level        = 0;
32
33 8
        while (!$jsonFrameEnd && !$this->stream->eof()) {
34 8
            $jsonChar   = $this->stream->read(1);
35
36 8
            if ((boolean)($jsonChar == '"' && $lastJsonChar != '\\')) {
37 8
                $inquote = !$inquote;
38 8
            }
39
40 8
            if (!$inquote && in_array($jsonChar, [" ", "\r", "\n", "\t"])) {
41 8
                continue;
42
            }
43
44 8
            if (!$inquote && in_array($jsonChar, ['{', '['])) {
45 8
                $level++;
46 8
            }
47
48 8
            if (!$inquote && in_array($jsonChar, ['}', ']'])) {
49 8
                $level--;
50
51 8
                if ($level == 0) {
52 8
                    $jsonFrameEnd = true;
53 8
                    $jsonFrame .= $jsonChar;
54
55 8
                    continue;
56
                }
57 6
            }
58
59 8
            $jsonFrame .= $jsonChar;
60 8
        }
61
62
        // Invalid last json, or timeout, or connection close before receiving
63 8
        if (!$jsonFrameEnd) {
64 8
            return null;
65
        }
66
67 8
        return $this->serializer->deserialize($jsonFrame, $this->getDecodeClass(), 'json');
68
    }
69
70
    /**
71
     * Get the decode class to pass to serializer
72
     *
73
     * @return string
74
     */
75
    abstract protected function getDecodeClass();
76
}
77