Completed
Push — master ( e124f5...aee4a1 )
by Nico
01:27
created

Rule   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 64
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A isTrue() 0 7 2
A isFalse() 0 4 1
A isValid() 0 11 2
A getError() 0 4 1
A registerToken() 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;
14
15
class Rule
16
{
17
    /** @var string */
18
    private $rule;
19
20
    /** @var Parser */
21
    private $parser;
22
23
    /** @var Evaluator */
24
    private $evaluator;
25
26
    /** @var string */
27
    private $parsedRule = '';
28
29
    /** @var string */
30
    private $error = '';
31
32 36
    public function __construct(string $rule, array $variables = [])
33
    {
34 36
        $this->rule = $rule;
35 36
        $this->parser = new Parser(new Tokenizer(new JavaScript()), new Expressions\Factory());
36 36
        $this->evaluator = new Evaluator();
37
38 36
        $this->parser->assignVariables($variables);
39 36
    }
40
41 6
    public function isTrue(): bool
42
    {
43 6
        return $this->evaluator->evaluate(
44 6
            $this->parsedRule ?:
45 6
            $this->parser->parse($this->rule)
46
        );
47
    }
48
49 2
    public function isFalse(): bool
50
    {
51 2
        return !$this->isTrue();
52
    }
53
54
    /**
55
     * Tells whether a rule is valid (as in "can be parsed without error") or not.
56
     */
57 32
    public function isValid(): bool
58
    {
59
        try {
60 32
            $this->parsedRule = $this->parser->parse($this->rule);
61 30
        } catch (Exception $e) {
62 30
            $this->error = $e->getMessage();
63 30
            return false;
64
        }
65
66 2
        return true;
67
    }
68
69 32
    public function getError(): string
70
    {
71 32
        return $this->error;
72
    }
73
74 2
    public function registerToken(string $class, string $regex, int $priority = 10)
75
    {
76 2
        $this->parser->registerToken($class, $regex, $priority);
77 2
    }
78
}
79