Completed
Push — master ( 450e0e...3bb600 )
by Kirill
05:06
created

MultistateLexer::getTokenDefinitions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Lexer\Driver;
11
12
use Railt\Lexer\Definition\MultistateTokenDefinition;
13
use Railt\Lexer\MultistateLexerInterface;
14
15
/**
16
 * Class MultistateLexer
17
 */
18
abstract class MultistateLexer extends SimpleLexer implements MultistateLexerInterface
19
{
20
    /**
21
     * @var int
22
     */
23
    protected const DEFAULT_STATE = 0x00;
24
25
    /**
26
     * @var array|int[]
27
     */
28
    protected $states = [];
29
30
    /**
31
     * @var array|int[]
32
     */
33
    protected $transitions = [];
34
35
    /**
36
     * @param string $token
37
     * @param int $state
38
     * @param int|null $nextState
39
     * @return MultistateLexerInterface
40
     */
41
    public function state(string $token, int $state, int $nextState = null): MultistateLexerInterface
42
    {
43
        $this->states[$token] = $state;
44
45
        if ($nextState !== null) {
46
            $this->transitions[$token] = $nextState;
47
        }
48
49
        return $this;
50
    }
51
52
    /**
53
     * @return iterable
54
     */
55
    public function getTokenDefinitions(): iterable
56
    {
57
        foreach ($this->tokens as $name => $pcre) {
58
            $keep  = ! \in_array($name, $this->skipped, true);
59
            $state = $this->getTokenState($name);
60
            $next  = $this->getNextState($name);
61
62
            yield new MultistateTokenDefinition($name, $pcre, $keep, $state, $next);
63
        }
64
    }
65
66
    /**
67
     * @param string $token
68
     * @return int
69
     */
70
    protected function getTokenState(string $token): int
71
    {
72
        return $this->states[$token] ?? static::DEFAULT_STATE;
73
    }
74
75
    /**
76
     * @param string $token
77
     * @return int
78
     */
79
    protected function getNextState(string $token): int
80
    {
81
        return $this->transitions[$this->getTokenState($token)] ?? static::DEFAULT_STATE;
82
    }
83
}
84