Passed
Push — main ( 93c199...f7f95e )
by Breno
01:50
created

RuleSet::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use BrenoRoosevelt\Validation\Exception\ValidateOrFail;
7
use BrenoRoosevelt\Validation\Rules\AllowsNull;
8
9
class RuleSet implements Rule
10
{
11
    use RuleChain,
12
        ValidateOrFail,
13
        BelongsToField;
14
15
    private array $rules = [];
16
17
    final public function __construct(?string $field = null, Rule | RuleSet ...$rules)
18
    {
19
        $this->attachRules(...$rules);
20
        $this->setField($field);
21
    }
22
23
    public static function new(): self
24
    {
25
        return new self;
26
    }
27
28
    public static function of(string $field, Rule | RuleSet ...$rules): self
29
    {
30
        return new self($field, ...$rules);
31
    }
32
33
    public static function withRules(Rule | RuleSet ...$rules): self
34
    {
35
        return new self(null, ...$rules);
36
    }
37
38
    public function add(Rule | RuleSet ...$rules): static
39
    {
40
        $instance = clone $this;
41
        $instance->attachRules(...$rules);
42
        return $instance;
43
    }
44
45
    private function attachRules(Rule | RuleSet ...$rules): void
46
    {
47
        foreach ($rules as $ruleOrRuleSet) {
48
            array_push(
49
                $this->rules,
50
                ...($ruleOrRuleSet instanceof Rule ? [$ruleOrRuleSet] : $ruleOrRuleSet->rules())
51
            );
52
        }
53
    }
54
55
    /**
56
     * @inheritDoc
57
     */
58
    public function validate(mixed $input, array $context = []): ValidationResult
59
    {
60
        $result = $this->newEmptyResult();
61
        foreach ($this->rules as $rule) {
62
            if (null == $input && $this->isAllowsNull()) {
63
                return $this->newEmptyResult();
64
            }
65
66
            $result = $result->addError(...$rule->validate($input, $context)->getErrors());
67
        }
68
69
        return $result;
70
    }
71
72
    public function isAllowsNull(): bool
73
    {
74
        foreach ($this->rules as $rule) {
75
            if ($rule instanceof AllowsNull) {
76
                return true;
77
            }
78
        }
79
80
        return false;
81
    }
82
83
    public function isEmpty(): bool
84
    {
85
        return empty($this->rules);
86
    }
87
88
    /** @return Rule[] */
89
    public function rules(): array
90
    {
91
        return $this->rules;
92
    }
93
}
94