Passed
Push — master ( 8b9f9e...586d0a )
by Edward
07:14 queued 04:23
created

MatcherSelector::setMatcher()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
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 6
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
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
        // @codeCoverageIgnoreStart
48
        throw new Exception\MatcherNotFoundException($matcherKey);
49
        // @codeCoverageIgnoreEnd
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     *
55
     * @return TokenMatcherInterface
56
     * @psalm-pure
57
     */
58 3
    public function getMatcher(): TokenMatcherInterface
59
    {
60 3
        if (isset($this->matcherKeys[0])) {
61 3
            return $this->getMatcherByKey($this->matcherKeys[0]);
62
        }
63
64
        // @codeCoverageIgnoreStart
65
        throw new Exception\MatcherKeyNotFoundException();
66
        // @codeCoverageIgnoreEnd
67
    }
68
69
    /**
70
     * {@inheritDoc}
71
     *
72
     * @param string $matcherKey
73
     */
74 6
    public function setMatcher(string $matcherKey): void
75
    {
76 6
        if (!isset($this->matchers[$matcherKey])) {
77 2
            throw new Exception\MatcherNotFoundException($matcherKey);
78
        }
79 5
        array_unshift($this->matcherKeys, $matcherKey);
80 5
    }
81
82
    /**
83
     * {@inheritDoc}
84
     */
85 2
    public function restoreMatcher(): void
86
    {
87 2
        if (count($this->matcherKeys) == 1) {
88 1
            throw new Exception\MatcherNotRestoredException();
89
        }
90 1
        array_shift($this->matcherKeys);
91 1
    }
92
}
93