Validator::validateAll()   B
last analyzed

Complexity

Conditions 9
Paths 13

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 9

Importance

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