-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathEvaluator.php
68 lines (57 loc) · 1.83 KB
/
Evaluator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php declare(strict_types=1);
/**
* @license http://opensource.org/licenses/mit-license.php MIT
* @link https://github.com/nicoSWD
* @author Nicolas Oelgart <[email protected]>
*/
namespace nicoSWD\Rule\Evaluator;
use Closure;
final class Evaluator implements EvaluatorInterface
{
public function evaluate(string $group): bool
{
$evalGroup = $this->evalGroup();
$count = 0;
do {
$group = preg_replace_callback(
'~\((?<match>[^()]+)\)~',
$evalGroup,
$group,
limit: -1,
count: $count
);
} while ($count > 0);
return (bool) $evalGroup(['match' => $group]);
}
private function evalGroup(): Closure
{
return function (array $group): ?int {
$result = null;
$operator = null;
$offset = 0;
while (isset($group['match'][$offset])) {
$value = $group['match'][$offset++];
$possibleOperator = Operator::tryFrom($value);
if ($possibleOperator) {
$operator = $possibleOperator;
} elseif (Boolean::tryFrom($value)) {
$result = $this->setResult($result, (int) $value, $operator);
} else {
throw new Exception\UnknownSymbolException(sprintf('Unexpected "%s"', $value));
}
}
return $result;
};
}
private function setResult(?int $result, int $value, ?Operator $operator): int
{
if (!isset($result)) {
$result = $value;
} elseif (Operator::isAnd($operator)) {
$result &= $value;
} elseif (Operator::isOr($operator)) {
$result |= $value;
}
return $result;
}
}