Completed
Push — 1.x ( ee8545...084efb )
by Joel
02:48
created

MultiJsonStream::readFrame()   C

Complexity

Conditions 13
Paths 30

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 44
rs 5.1234
cc 13
eloc 24
nc 30
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Docker\Stream;
4
5
/**
6
 * Represent a stream that decode a stream with multiple json in it
7
 *
8
 * Callable passed to this stream will take a stdClass object as first argument (decoded from the json)
9
 */
10
class MultiJsonStream extends CallbackStream
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    protected function readFrame()
16
    {
17
        $jsonFrameEnd = false;
18
        $lastJsonChar = '';
19
        $inquote      = false;
20
        $jsonFrame    = "";
21
        $level        = 0;
22
23
        while (!$jsonFrameEnd && !$this->stream->eof()) {
24
            $jsonChar   = $this->stream->read(1);
25
26
            if ((boolean)($jsonChar == '"' && $lastJsonChar != '\\')) {
27
                $inquote = !$inquote;
28
            }
29
30
            if (!$inquote && in_array($jsonChar, [" ", "\r", "\n", "\t"])) {
31
                continue;
32
            }
33
34
            if (!$inquote && in_array($jsonChar, ['{', '['])) {
35
                $level++;
36
            }
37
38
            if (!$inquote && in_array($jsonChar, ['}', ']'])) {
39
                $level--;
40
41
                if ($level == 0) {
42
                    $jsonFrameEnd = true;
43
                    $jsonFrame .= $jsonChar;
44
45
                    continue;
46
                }
47
            }
48
49
            $jsonFrame .= $jsonChar;
50
        }
51
52
        // Invalid last json, or timeout, or connection close before receiving
53
        if (!$jsonFrameEnd) {
54
            return null;
55
        }
56
57
        return json_decode($jsonFrame);
58
    }
59
}
60