Passed
Push — master ( d2779f...9acd42 )
by Edward
06:48
created

MatcherSelector::getMatcherByKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 10
cc 2
nc 2
nop 1
crap 2.0625
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\Lexer\Runtime\Token;
6
7
use function array_shift;
8
use function array_unshift;
9
use function count;
10
11
final class MatcherSelector implements MatcherSelectorInterface
12
{
13
14
    /**
15
     * @var TokenMatcherInterface[]
16
     * @psalm-var array<string,TokenMatcherInterface>
17
     */
18
    private $matchers;
19
20
    /**
21
     * @var string[]
22
     * @psalm-var array<int,string>
23
     */
24
    private $matcherKeys = [];
25
26
    /**
27
     * @param TokenMatcherInterface[] $matchers
28
     * @psalm-param array<string,TokenMatcherInterface> $matchers
29
     * @param string                  $startMatcherKey
30
     */
31 6
    public function __construct(array $matchers, string $startMatcherKey)
32
    {
33 6
        $this->matchers = $matchers;
34 6
        $this->setMatcher($startMatcherKey);
35 5
    }
36
37
    /**
38
     * @param string $matcherKey
39
     * @return TokenMatcherInterface
40
     * @psalm-pure
41
     */
42 3
    private function getMatcherByKey(string $matcherKey): TokenMatcherInterface
43
    {
44 3
        if (isset($this->matchers[$matcherKey])) {
45 3
            return $this->matchers[$matcherKey];
46
        }
47
        throw new Exception\MatcherNotFoundException($matcherKey);
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     *
53
     * @return TokenMatcherInterface
54
     * @psalm-pure
55
     */
56 3
    public function getMatcher(): TokenMatcherInterface
57
    {
58 3
        if (!isset($this->matcherKeys[0])) {
59
            throw new Exception\MatcherKeyNotFoundException();
60
        }
61
62 3
        return $this->getMatcherByKey($this->matcherKeys[0]);
63
    }
64
65
    /**
66
     * {@inheritDoc}
67
     *
68
     * @param string $matcherKey
69
     */
70 6
    public function setMatcher(string $matcherKey): void
71
    {
72 6
        if (!isset($this->matchers[$matcherKey])) {
73 2
            throw new Exception\MatcherNotFoundException($matcherKey);
74
        }
75 5
        array_unshift($this->matcherKeys, $matcherKey);
76 5
    }
77
78
    /**
79
     * {@inheritDoc}
80
     */
81 2
    public function restoreMatcher(): void
82
    {
83 2
        if (count($this->matcherKeys) == 1) {
84 1
            throw new Exception\MatcherNotRestoredException();
85
        }
86 1
        array_shift($this->matcherKeys);
87 1
    }
88
}
89