|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Drobotik\Eav\Validation; |
|
4
|
|
|
|
|
5
|
|
|
use Drobotik\Eav\Interfaces\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
|
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); |
|
|
|
|
|
|
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
|
|
|
} |