Passed
Pull Request — master (#22)
by Nico
18:37 queued 03:42
created

Rule   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 52
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 8
1
<?php declare(strict_types=1);
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
namespace nicoSWD\Rule;
9
10
use Exception;
11
use nicoSWD\Rule\Evaluator\EvaluatorInterface;
12
13
class Rule
14
{
15
    private readonly Parser\Parser $parser;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 15 at column 21
Loading history...
16
    private string $rule;
17
    private string $parsedRule = '';
18
    private string $error = '';
19
    private static object $container;
20
21
    public function __construct(string $rule, array $variables = [])
22
    {
23
        if (!isset(self::$container)) {
24
            self::$container = require __DIR__ . '/container.php';
25
        }
26 280
27
        $this->parser = self::$container->parser($variables);
28 280
        $this->rule = $rule;
29 2
    }
30
31
    /** @throws Parser\Exception\ParserException */
32 280
    public function isTrue(): bool
33 280
    {
34 280
        /** @var EvaluatorInterface $evaluator */
35
        $evaluator = self::$container->evaluator();
36 212
37
        return $evaluator->evaluate(
38
            $this->parsedRule ?:
39 212
            $this->parser->parse($this->rule)
40
        );
41 212
    }
42 212
43 212
    /** @throws Parser\Exception\ParserException */
44
    public function isFalse(): bool
45
    {
46
        return !$this->isTrue();
47 2
    }
48
49 2
    /**
50
     * Tells whether a rule is valid (as in "can be parsed without error") or not.
51
     */
52
    public function isValid(): bool
53
    {
54
        try {
55 74
            $this->parsedRule = $this->parser->parse($this->rule);
56
        } catch (Exception $e) {
57
            $this->error = $e->getMessage();
58 74
            return false;
59 68
        }
60 68
61 68
        return true;
62
    }
63
64 6
    public function getError(): string
65
    {
66
        return $this->error;
67 74
    }
68
}
69