Passed
Push — master ( 5cce8c...cb0ced )
by Edward
04:53
created

Ll1ParserFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 46
ccs 17
cts 19
cp 0.8947
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createParser() 0 15 2
A createSourceReader() 0 6 1
A getGrammar() 0 7 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Parser;
5
6
use Remorhaz\JSON\Path\Query\AstBuilder;
7
use Remorhaz\JSON\Path\TokenMatcher;
8
use Remorhaz\UniLex\AST\Tree;
9
use Remorhaz\UniLex\Exception as UnilexException;
10
use Remorhaz\UniLex\Grammar\ContextFree\GrammarInterface;
11
use Remorhaz\UniLex\Grammar\ContextFree\GrammarLoader;
12
use Remorhaz\UniLex\Grammar\ContextFree\TokenFactory;
13
use Remorhaz\UniLex\Lexer\TokenReader;
14
use Remorhaz\UniLex\Lexer\TokenReaderInterface;
15
use Remorhaz\UniLex\Parser\LL1\Parser as Ll1Parser;
16
use Remorhaz\UniLex\Parser\LL1\TranslationSchemeApplier;
17
use Remorhaz\UniLex\Unicode\CharBufferFactory;
18
use Throwable;
19
20
final class Ll1ParserFactory implements Ll1ParserFactoryInterface
21
{
22
23
    private $grammar;
24
25 4
    public function createParser(string $source, Tree $queryAst): Ll1Parser
26
    {
27
        try {
28 4
            $scheme = new TranslationScheme(new AstBuilder($queryAst));
29 4
            $parser = new Ll1Parser(
30 4
                $this->getGrammar(),
31 4
                $this->createSourceReader($source),
32 4
                new TranslationSchemeApplier($scheme)
33
            );
34 4
            $parser->loadLookupTable(__DIR__ . '/../../generated/LookupTable.php');
35
        } catch (Throwable $e) {
36
            throw new Exception\ParserCreationFailedException($e);
37
        }
38
39 4
        return $parser;
40
    }
41
42
    /**
43
     * @return GrammarInterface
44
     * @throws UnilexException
45
     */
46 4
    private function getGrammar(): GrammarInterface
47
    {
48 4
        if (!isset($this->grammar)) {
49 4
            $this->grammar = GrammarLoader::loadFile(__DIR__ . '/../../spec/GrammarSpec.php');
50
        }
51
52 4
        return $this->grammar;
53
    }
54
55
    /**
56
     * @param string $source
57
     * @return TokenReaderInterface
58
     * @throws UnilexException
59
     */
60 4
    private function createSourceReader(string $source): TokenReaderInterface
61
    {
62 4
        return new TokenReader(
63 4
            CharBufferFactory::createFromString($source),
64 4
            new TokenMatcher,
65 4
            new TokenFactory($this->getGrammar())
66
        );
67
    }
68
}
69