Passed
Pull Request — master (#22)
by Nico
14:21
created

Grammar::getQueue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php declare(strict_types=1);
2
3
/**
4
 * @license     http://opensource.org/licenses/mit-license.php MIT
5
 * @link        https://github.com/nicoSWD
6
 * @author      Nicolas Oelgart <[email protected]>
7
 */
8
namespace nicoSWD\Rule\Grammar;
9
10
use SplPriorityQueue;
11
12
abstract class Grammar
13
{
14
    private string $compiledRegex = '';
15
    /** @var Definition[] */
16 2
    private array $tokens = [];
17
18 2
    /** @return Definition[] */
19
    abstract public function getDefinition(): array;
20
21
    /** @return InternalFunction[] */
22 2
    abstract public function getInternalFunctions(): array;
23
24 2
    /** @return InternalMethod[] */
25
    abstract public function getInternalMethods(): array;
26
27
    public function buildRegex(): string
28
    {
29
        if (!$this->compiledRegex) {
30
            $this->registerTokens();
31
            $regex = [];
32
33
            foreach ($this->getQueue() as $token) {
34
                $regex[] = "(?<{$token->token->value}>{$token->regex})";
35
            }
36
37
            $this->compiledRegex = '~(' . implode('|', $regex) . ')~As';
38
        }
39
40
        return $this->compiledRegex;
41
    }
42
43
    private function getQueue(): SplPriorityQueue
44
    {
45
        $queue = new SplPriorityQueue();
46
47
        foreach ($this->tokens as $token) {
48
            $queue->insert($token, $token->priority);
49
        }
50
51
        return $queue;
52
    }
53
54
    private function registerTokens(): void
55
    {
56
        foreach ($this->getDefinition() as $definition) {
57
            $this->tokens[$definition->token->value] = $definition;
58
        }
59
    }
60
}
61