Passed
Push — master ( ad4fe0...8948f6 )
by Petr
08:16
created

TRules   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 61
ccs 22
cts 22
cp 1
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A addRules() 0 8 4
A addRule() 0 6 2
A getRules() 0 3 1
A getRulesFactory() 0 7 2
A removeRules() 0 3 1
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;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->rulesFactory could return the type null which is incompatible with the type-hinted return kalanis\kw_rules\Interfaces\IRuleFactory. Consider adding an additional type-check to rule them out.
Loading history...
69
    }
70
71
    /**
72
     * Set which factory will be used
73
     * @return Interfaces\IRuleFactory
74
     */
75
    abstract protected function whichRulesFactory(): Interfaces\IRuleFactory;
76
}
77