Completed
Push — master ( e5de66...386907 )
by Nico
02:02
created

Rule   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 9
dl 0
loc 76
ccs 31
cts 31
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 25 1
A isTrue() 0 7 2
A isFalse() 0 4 1
A isValid() 0 11 2
A getError() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @license     http://opensource.org/licenses/mit-license.php MIT
7
 * @link        https://github.com/nicoSWD
8
 * @author      Nicolas Oelgart <[email protected]>
9
 */
10
namespace nicoSWD\Rules;
11
12
use Exception;
13
use nicoSWD\Rules\Grammar\JavaScript\JavaScript;
14
use nicoSWD\Rules\Tokens\TokenFactory;
15
16
class Rule
17
{
18
    /** @var string */
19
    private $rule;
20
21
    /** @var Parser */
22
    private $parser;
23
24
    /** @var Evaluator */
25
    private $evaluator;
26
27
    /** @var string */
28
    private $parsedRule = '';
29
30
    /** @var string */
31
    private $error = '';
32
33 60
    public function __construct(string $rule, array $variables = [])
34
    {
35 60
        $this->rule = $rule;
36
37 60
        $grammar = new JavaScript();
38 60
        $tokenFactory = new TokenFactory();
39 60
        $ruleGenerator = new Compiler();
40 60
        $expressionFactory = new Expressions\ExpressionFactory();
41
42 60
        $tokenizer = new Tokenizer(
43 60
            $grammar,
44 60
            $tokenFactory
45
        );
46
47 60
        $ast = new AST($tokenizer, $tokenFactory, new TokenStream());
48 60
        $ast->setVariables($variables);
49
50 60
        $this->parser = new Parser(
51 60
            $ast,
52 60
            $expressionFactory,
53 60
            $ruleGenerator
54
        );
55
56 60
        $this->evaluator = new Evaluator();
57 60
    }
58
59 4
    public function isTrue(): bool
60
    {
61 4
        return $this->evaluator->evaluate(
62 4
            $this->parsedRule ?:
63 4
            $this->parser->parse($this->rule)
64
        );
65
    }
66
67 2
    public function isFalse(): bool
68
    {
69 2
        return !$this->isTrue();
70
    }
71
72
    /**
73
     * Tells whether a rule is valid (as in "can be parsed without error") or not.
74
     */
75 58
    public function isValid(): bool
76
    {
77
        try {
78 58
            $this->parsedRule = $this->parser->parse($this->rule);
79 56
        } catch (Exception $e) {
80 56
            $this->error = $e->getMessage();
81 56
            return false;
82
        }
83
84 2
        return true;
85
    }
86
87 58
    public function getError(): string
88
    {
89 58
        return $this->error;
90
    }
91
}
92