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

Validator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 56
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 13

2 Methods

Rating   Name   Duplication   Size   Complexity  
B validateAll() 0 34 9
A validate() 0 12 4
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
}