Validator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 3
b 0
f 0
nc 4
nop 1
dl 0
loc 16
rs 9.6111
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation;
5
6
use ReflectionException;
7
8
final class Validator
9
{
10
    /** @var ValidationSet[] */
11
    private array $ruleSets;
12
13
    public static function new(): self
14
    {
15
        return new self;
16
    }
17
18
    public function ruleSet(string $field): ValidationSet
19
    {
20
        foreach ($this->ruleSets as $ruleSet) {
21
            if ($ruleSet->getField() === $field) {
22
                return $ruleSet;
23
            }
24
        }
25
26
        return $this->ruleSets[] = (new ValidationSet)->setField($field);
27
    }
28
29
    public function field(string $field, Validation|ValidationSet ...$rules): self
30
    {
31
        $ruleset = $this->ruleSet($field);
32
        foreach ($rules as $rule) {
33
            if ($rule instanceof Validation) {
34
                $ruleset->add($rule);
35
            }
36
37
            if ($rule instanceof ValidationSet) {
38
                $ruleset->add(...$rule->rules());
39
            }
40
        }
41
42
        return $this;
43
    }
44
45
    public function validate(array $data = []): ValidationResultSet
46
    {
47
        $validationResultSet = new ValidationResultSet();
48
        foreach ($this->ruleSets as $ruleSet) {
49
            $field = $ruleSet->getField();
50
            if (!$ruleSet->isRequired() && !array_key_exists($field, $data)) {
51
                continue;
52
            }
53
54
            $result = $ruleSet->validate($data[$field] ?? null, $data);
55
            if (!$result->isOk()) {
56
                $validationResultSet->add($result);
57
            }
58
        }
59
60
        return $validationResultSet;
61
    }
62
63
    /**
64
     * @param array $data
65
     * @param ?string $message
66
     * @return void
67
     * @throws ValidationException
68
     */
69
    public function validateOrFail(array $data = [], ?string $message = null)
70
    {
71
        $result = $this->validate($data);
72
        if (!$result->isOk()) {
73
            throw new ValidationException($result, $message);
74
        }
75
    }
76
77
    /**
78
     * @param string|object $objectOrClass
79
     * @return static
80
     * @throws ReflectionException
81
     */
82
    public static function fromProperties(string|object $objectOrClass): self
83
    {
84
        $instance = new self;
85
        $instance->ruleSets = ValidationSet::fromProperties($objectOrClass);
86
        return $instance;
87
    }
88
}
89