Passed
Push — master ( 586d0a...d8e937 )
by Edward
04:02
created

TokenInput::__construct()   A

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
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\Lexer\Runtime\Token;
6
7
use Iterator;
8
use IteratorAggregate;
9
use Remorhaz\Lexer\Runtime\IO\Exception;
10
use Remorhaz\Lexer\Runtime\IO\LexemeInterface;
11
use Remorhaz\Lexer\Runtime\IO\Symbol;
12
use Remorhaz\Lexer\Runtime\IO\SymbolInterface;
13
use Remorhaz\Lexer\Runtime\IO\SymbolReaderInterface;
14
15
use function is_int;
16
17
final class TokenInput implements IteratorAggregate, SymbolReaderInterface
18
{
19
20
    public const ATTRIBUTE_SYMBOL_CODE = 'symbol.code';
21
22
    /**
23
     * @var TokenReaderInterface
24
     */
25
    private $tokenReader;
26
27 10
    public function __construct(TokenReaderInterface $tokenReader)
28
    {
29 10
        $this->tokenReader = $tokenReader;
30 10
    }
31
32 5
    public function read(): SymbolInterface
33
    {
34 5
        $token = $this->tokenReader->read();
35
        /** @psalm-var mixed $symbolCode */
36 5
        $symbolCode = $token->getAttribute(self::ATTRIBUTE_SYMBOL_CODE);
37 5
        if (is_int($symbolCode)) {
38 4
            return new Symbol($token->getOffset(), $symbolCode, $token->getLexeme());
39
        }
40
41 1
        throw new Exception\InvalidSymbolCodeException($symbolCode);
42
    }
43
44
    /**
45
     * @return int
46
     * @psalm-pure
47
     */
48 3
    public function getOffset(): int
49
    {
50 3
        return $this->tokenReader->getOffset();
51
    }
52
53
    /**
54
     * @return bool
55
     * @psalm-pure
56
     */
57 5
    public function isFinished(): bool
58
    {
59 5
        return $this->tokenReader->isFinished();
60
    }
61
62
    /**
63
     * @return LexemeInterface
64
     * @psalm-pure
65
     */
66 1
    public function getEmptyLexeme(): LexemeInterface
67
    {
68 1
        return $this->tokenReader->getEmptyLexeme();
69
    }
70
71
    /**
72
     * @return Iterator
73
     * @psalm-return Iterator<int,SymbolInterface>
74
     */
75 3
    public function getIterator(): Iterator
76
    {
77 3
        while (!$this->isFinished()) {
78 2
            yield $this->getOffset() => $this->read();
79
        }
80 3
    }
81
}
82