SourceBuffer   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 62
ccs 31
cts 31
cp 1
rs 10
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A nextBuffer() 0 8 2
A __construct() 0 5 1
A key() 0 3 1
A next() 0 8 3
A current() 0 7 2
A rewind() 0 4 1
A valid() 0 4 2
1
<?php
2
declare(strict_types=1);
3
4
5
namespace JsonDecodeStream\Internal;
6
7
use Iterator;
8
use JsonDecodeStream\Source\SourceInterface;
9
10
class SourceBuffer implements Iterator
11
{
12
    protected $source;
13
    protected $bufferMaxSize;
14
    protected $bufferSize;
15
    protected $buffer;
16
    protected $bufferPosition;
17
    protected $sourcePosition;
18
19 118
    public function __construct(SourceInterface $source, int $bufferSize = 4096)
20
    {
21 118
        $this->source = $source;
22 118
        $this->bufferMaxSize = $bufferSize;
23 118
        $this->sourcePosition = 0;
24 118
    }
25
26 116
    protected function nextBuffer()
27
    {
28 116
        if ($this->source->isEof()) {
29 113
            $this->buffer = null;
30
        } else {
31 115
            $this->buffer = $this->source->read($this->bufferMaxSize);
32 115
            $this->bufferPosition = 0;
33 115
            $this->bufferSize = strlen($this->buffer);
34
        }
35 116
    }
36
37 114
    public function current()
38
    {
39 114
        if (!$this->valid()) {
40 1
            return null;
41
        }
42
43 113
        return $this->buffer[$this->bufferPosition];
44
    }
45
46 112
    public function next()
47
    {
48 112
        $this->bufferPosition++;
49 112
        if ($this->bufferPosition == min($this->bufferMaxSize, $this->bufferSize)) {
50 112
            $this->nextBuffer();
51
        }
52 112
        if ($this->buffer !== null) {
53 103
            $this->sourcePosition++;
54
        }
55 112
    }
56
57 4
    public function key()
58
    {
59 4
        return $this->sourcePosition;
60
    }
61
62 118
    public function valid()
63
    {
64 118
        return $this->buffer !== null
65 118
            && $this->bufferPosition < $this->bufferSize;
66
    }
67
68 116
    public function rewind()
69
    {
70 116
        $this->source->rewind();
71 116
        $this->nextBuffer();
72 116
    }
73
}
74