SourceBuffer::key()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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