Completed
Pull Request — master (#4)
by Nico
02:45 queued 31s
created

Rule::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 1
1
<?php
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
declare(strict_types=1);
9
10
namespace nicoSWD\Rules;
11
12
use Closure;
13
use Exception;
14
use nicoSWD\Rules\Expressions\BaseExpression;
15
16
class Rule
17
{
18
    /**
19
     * @var string
20
     */
21
    private $rule;
22
23
    /**
24
     * @var Parser
25
     */
26
    private $parser;
27
28
    /**
29
     * @var Evaluator
30
     */
31
    private $evaluator;
32
33
    /**
34
     * @var string
35
     */
36
    private $parsedRule = '';
37
38
    /**
39
     * @var string
40
     */
41
    private $error = '';
42
43 8
    public function __construct(string $rule, array $variables = [])
44
    {
45 8
        $this->rule = $rule;
46 8
        $this->parser = new Parser(new Tokenizer(), new Expressions\Factory());
47 8
        $this->evaluator = new Evaluator();
48
49 8
        $this->parser->assignVariables($variables);
50 8
    }
51
52 6
    public function isTrue() : bool
53
    {
54 6
        return $this->evaluator->evaluate(
55 6
            $this->parsedRule ?:
56 6
            $this->parser->parse($this->rule)
57
        );
58
    }
59
60 2
    public function isFalse() : bool
61
    {
62 2
        return !$this->isTrue();
63
    }
64
65
    /**
66
     * Tells whether a rule is valid (as in "can be parsed without error") or not.
67
     */
68 4
    public function isValid() : bool
69
    {
70
        try {
71 4
            $this->parsedRule = $this->parser->parse($this->rule);
72 2
        } catch (Exception $e) {
73 2
            $this->error = $e->getMessage();
74 2
            return false;
75
        }
76
77 2
        return true;
78
    }
79
80
    public function registerFunction(string $name, Closure $callback)
81
    {
82
        $this->parser->registerFunction($name, $callback);
83
    }
84
85 2
    public function registerToken(string $class, string $regex, int $priority = 10)
86
    {
87 2
        $this->parser->registerToken($class, $regex, $priority);
88 2
    }
89
90 4
    public function getError() : string
91
    {
92 4
        return $this->error;
93
    }
94
}
95