|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\kw_rules; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\kw_rules\Interfaces; |
|
7
|
|
|
use kalanis\kw_rules\Rules; |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Trait TRules |
|
12
|
|
|
* @package kalanis\kw_rules |
|
13
|
|
|
* Main class for processing rules - use it as include for your case |
|
14
|
|
|
*/ |
|
15
|
|
|
trait TRules |
|
16
|
|
|
{ |
|
17
|
|
|
protected ?Interfaces\IRuleFactory $rulesFactory = null; |
|
18
|
|
|
/** @var Rules\ARule[]|Rules\File\AFileRule[] */ |
|
19
|
|
|
protected array $rules = []; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param string $ruleName |
|
23
|
|
|
* @param string $errorText |
|
24
|
|
|
* @param mixed ...$args |
|
25
|
|
|
*/ |
|
26
|
7 |
|
public function addRule(string $ruleName, string $errorText, ...$args): void |
|
27
|
|
|
{ |
|
28
|
7 |
|
$rule = $this->getRulesFactory()->getRule($ruleName); |
|
29
|
7 |
|
$rule->setErrorText($errorText); |
|
30
|
7 |
|
$rule->setAgainstValue(empty($args) ? null : reset($args)); |
|
31
|
7 |
|
$this->rules[] = $rule; |
|
32
|
7 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param array<Rules\ARule|Rules\File\AFileRule> $rules |
|
36
|
|
|
*/ |
|
37
|
2 |
|
public function addRules(array $rules = []): void |
|
38
|
|
|
{ |
|
39
|
2 |
|
foreach ($rules as $rule) { |
|
40
|
2 |
|
if ($rule instanceof Rules\ARule) { |
|
41
|
1 |
|
$this->rules[] = $rule; |
|
42
|
|
|
} |
|
43
|
2 |
|
if ($rule instanceof Rules\File\AFileRule) { |
|
44
|
1 |
|
$this->rules[] = $rule; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
2 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @return array<Rules\ARule|Rules\File\AFileRule> |
|
51
|
|
|
*/ |
|
52
|
7 |
|
public function getRules(): array |
|
53
|
|
|
{ |
|
54
|
7 |
|
return $this->rules; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
public function removeRules(): void |
|
58
|
|
|
{ |
|
59
|
2 |
|
$this->rules = []; |
|
60
|
2 |
|
} |
|
61
|
|
|
|
|
62
|
7 |
|
protected function getRulesFactory(): Interfaces\IRuleFactory |
|
63
|
|
|
{ |
|
64
|
|
|
// @phpstan-ignore-next-line |
|
65
|
7 |
|
if (empty($this->rulesFactory)) { |
|
66
|
7 |
|
$this->rulesFactory = $this->whichRulesFactory(); |
|
67
|
|
|
} |
|
68
|
7 |
|
return $this->rulesFactory; |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Set which factory will be used |
|
73
|
|
|
* @return Interfaces\IRuleFactory |
|
74
|
|
|
*/ |
|
75
|
|
|
abstract protected function whichRulesFactory(): Interfaces\IRuleFactory; |
|
76
|
|
|
} |
|
77
|
|
|
|