-
Notifications
You must be signed in to change notification settings - Fork 1
/
AllConstraint.php
73 lines (63 loc) · 1.84 KB
/
AllConstraint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace Chubbyphp\Validation\Constraint;
use Chubbyphp\Validation\Error\Error;
use Chubbyphp\Validation\Error\ErrorInterface;
use Chubbyphp\Validation\ValidatorContextInterface;
use Chubbyphp\Validation\ValidatorInterface;
use Chubbyphp\Validation\ValidatorLogicException;
final class AllConstraint implements ConstraintInterface
{
/**
* @var array<ConstraintInterface>
*/
private array $constraints;
/**
* @param array<ConstraintInterface> $constraints
*/
public function __construct(array $constraints = [])
{
$this->constraints = [];
foreach ($constraints as $constraint) {
$this->addConstraint($constraint);
}
}
/**
* @param mixed $value
*
* @throws ValidatorLogicException
*
* @return array<ErrorInterface>
*/
public function validate(
string $path,
$value,
ValidatorContextInterface $context,
?ValidatorInterface $validator = null
) {
if (null === $value) {
return [];
}
if (!\is_array($value) && !$value instanceof \Traversable) {
return [new Error(
$path.'[_all]',
'constraint.all.invalidtype',
['type' => \is_object($value) ? \get_class($value) : \gettype($value)]
)];
}
$errors = [];
foreach ($value as $i => $subValue) {
foreach ($this->constraints as $constraint) {
$errors = array_merge(
$errors,
$constraint->validate($path.'['.$i.']', $subValue, $context, $validator)
);
}
}
return $errors;
}
private function addConstraint(ConstraintInterface $constraint): void
{
$this->constraints[] = $constraint;
}
}