1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Oliverde8\Component\RuleEngine\Rules; |
6
|
|
|
|
7
|
|
|
use Oliverde8\Component\RuleEngine\Exceptions\RuleOptionMissingException; |
8
|
|
|
use Oliverde8\Component\RuleEngine\RuleApplier; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class AbstractRule |
13
|
|
|
* |
14
|
|
|
* @author de Cramer Oliver<[email protected]> |
15
|
|
|
* @copyright 2018 Oliverde8 |
16
|
|
|
* @package Oliverde8\Component\RuleEngine\Rules |
17
|
|
|
*/ |
18
|
|
|
abstract class AbstractRule implements RuleInterface |
19
|
|
|
{ |
20
|
|
|
protected RuleApplier $ruleApplier; |
21
|
|
|
|
22
|
|
|
protected LoggerInterface $logger; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* AbstractRule constructor. |
26
|
|
|
* |
27
|
|
|
* @param LoggerInterface $logger Standard logger to log information. |
28
|
|
|
*/ |
29
|
21 |
|
public function __construct(LoggerInterface $logger) |
30
|
|
|
{ |
31
|
21 |
|
$this->logger = $logger; |
32
|
21 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Set the rule applier. |
36
|
|
|
* |
37
|
|
|
* @param RuleApplier $ruleApplier The rule applier that is using this rule. |
38
|
|
|
* @return $this |
39
|
|
|
*/ |
40
|
|
|
public function setApplier(RuleApplier $ruleApplier): self |
41
|
21 |
|
{ |
42
|
|
|
$this->ruleApplier = $ruleApplier; |
43
|
21 |
|
return $this; |
44
|
21 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Check if require option is set. |
48
|
|
|
* |
49
|
|
|
* @param string|string[] $option The option that needs to be set. |
50
|
|
|
* if list is given then one of the options needs to be set. |
51
|
|
|
* @param array $options Options that were passed in parameter. |
52
|
|
|
* |
53
|
|
|
* @return bool |
54
|
|
|
* @throws RuleOptionMissingException |
55
|
|
|
*/ |
56
|
14 |
|
protected function requireOption($option, array $options): bool |
57
|
|
|
{ |
58
|
14 |
|
if (is_array($option)) { |
59
|
|
|
foreach ($option as $key) { |
60
|
|
|
if (isset($options[$key])) { |
61
|
|
|
return true; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->throwMissingFieldException(implode(' or ', $option)); |
66
|
14 |
|
} elseif (!isset($options[$option])) { |
67
|
1 |
|
$this->throwMissingFieldException($option); |
68
|
|
|
} |
69
|
|
|
|
70
|
13 |
|
return true; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Throw a nice missing field exception. |
75
|
|
|
* |
76
|
|
|
* @param string $option The option that is missing. |
77
|
|
|
* |
78
|
|
|
* @throws RuleOptionMissingException |
79
|
|
|
*/ |
80
|
1 |
|
protected function throwMissingFieldException($option) |
81
|
|
|
{ |
82
|
1 |
|
throw new RuleOptionMissingException("Rule '{$this->getRuleCode()}' is missing the '$option' option!"); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|