StringInput::read()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\Lexer\Runtime\IO;
6
7
use Iterator;
8
use IteratorAggregate;
9
10
use function strlen;
11
12
final class StringInput implements IteratorAggregate, SymbolReaderInterface
13
{
14
15
    /**
16
     * @var string
17
     */
18
    private $data;
19
20
    /**
21
     * @var int
22
     */
23
    private $offset = 0;
24
25
    /**
26
     * @var int
27
     */
28
    private $length;
29
30 20
    public function __construct(string $data)
31
    {
32 20
        $this->data = $data;
33 20
        $this->length = strlen($data);
34 20
    }
35
36
    /**
37
     * @return bool
38
     * @psalm-pure
39
     */
40 6
    public function isFinished(): bool
41
    {
42 6
        return $this->length == $this->offset;
43
    }
44
45 14
    public function read(): SymbolInterface
46
    {
47 14
        if ($this->length == $this->offset) {
48 2
            throw new Exception\UnexpectedEndOfInputException($this->offset);
49
        }
50
51 13
        return new Symbol($this->offset, ord($this->data[$this->offset++]), new NullLexeme());
52
    }
53
54
    /**
55
     * @return int
56
     * @psalm-pure
57
     */
58 5
    public function getOffset(): int
59
    {
60 5
        return $this->offset;
61
    }
62
63
    /**
64
     * @return LexemeInterface
65
     * @psalm-pure
66
     */
67 4
    public function getEmptyLexeme(): LexemeInterface
68
    {
69 4
        return new EmptyLexeme($this->offset, new NullLexeme());
70
    }
71
72
    /**
73
     * @return Iterator
74
     * @psalm-return Iterator<int,SymbolInterface>
75
     */
76 3
    public function getIterator(): Iterator
77
    {
78 3
        while (!$this->isFinished()) {
79 2
            yield $this->getOffset() => $this->read();
80
        }
81 3
    }
82
}
83