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

Rule   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 88.46%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 4
dl 0
loc 79
ccs 23
cts 26
cp 0.8846
rs 10
c 0
b 0
f 0

7 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 registerFunction() 0 4 1
A registerToken() 0 4 1
A getError() 0 4 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