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

Rule::isTrue()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 1
nop 0
crap 2
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