Passed
Push — master ( 17e6cc...350d8b )
by Aleksandr
41:29 queued 06:24
created

Validator::validateAll()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9

Importance

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