Passed
Push — master ( 3bffb6...f32028 )
by Aleksandr
31:58
created

Validator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Drobotik\Eav\Validation;
4
5
use Drobotik\Eav\Interface\ConstraintInterface;
6
use Drobotik\Eav\Validation\Constraints\RequiredConstraint;
7
8
class Validator
9
{
10
11
    /**
12
     * @param $value
13
     * @param array $constraints
14
     * @return Violation[]
15
     */
16
    public function validate($value, array $constraints)
17
    {
18
        foreach ($constraints as $constraint) {
19
            if ($constraint instanceof ConstraintInterface) {
20
                $violation = $constraint->validate($value);
21
                if ($violation !== null) {
22
                    return new Violation(get_class($constraint), $violation);
0 ignored issues
show
Bug Best Practice introduced by
The expression return new Drobotik\Eav\...onstraint), $violation) returns the type Drobotik\Eav\Validation\Violation which is incompatible with the documented return type Drobotik\Eav\Validation\Violation[].
Loading history...
23
                }
24
            }
25
        }
26
27
        return null;
28
    }
29
30
    public function validateAll(array $data, array $rules): array
31
    {
32
        $violations = [];
33
34
        foreach ($rules as $field => $constraints) {
35
            $isRequired = false;
36
37
            // Check if RequiredConstraint is present
38
            foreach ($constraints as $constraint) {
39
                if ($constraint instanceof RequiredConstraint) {
40
                    $isRequired = true;
41
                    break;
42
                }
43
            }
44
45
            // If required but missing, add an error
46
            if ($isRequired && !isset($data[$field])) {
47
                $violations[] = new Violation($field, "The field '$field' is required.");
48
                continue;
49
            }
50
51
            // If the field is not required and missing, skip validation
52
            if (!$isRequired && !isset($data[$field])) {
53
                continue;
54
            }
55
56
            // Validate the field if present
57
            $violation = $this->validate($data[$field], $constraints);
58
            if (!empty($violation)) {
59
                $violations[] = new Violation($field, $violation);
60
            }
61
        }
62
63
        return $violations;
64
    }
65
}