1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE file |
9
|
|
|
* that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use Respect\Validation\Exceptions\EachException; |
17
|
|
|
use Respect\Validation\Exceptions\ValidationException; |
18
|
|
|
use Respect\Validation\Helpers\CanValidateIterable; |
19
|
|
|
use Respect\Validation\Validatable; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Validates whether each value in the input is valid according to another rule. |
23
|
|
|
* |
24
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
25
|
|
|
* @author Henrique Moody <[email protected]> |
26
|
|
|
* @author Nick Lombard <[email protected]> |
27
|
|
|
* @author William Espindola <[email protected]> |
28
|
|
|
*/ |
29
|
|
|
final class Each extends AbstractRule |
30
|
|
|
{ |
31
|
|
|
use CanValidateIterable; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var Validatable |
35
|
|
|
*/ |
36
|
|
|
private $rule; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Initializes the constructor. |
40
|
|
|
*/ |
41
|
4 |
|
public function __construct(Validatable $rule) |
42
|
|
|
{ |
43
|
4 |
|
$this->rule = $rule; |
44
|
4 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritDoc} |
48
|
|
|
*/ |
49
|
12 |
|
public function assert($input): void |
50
|
|
|
{ |
51
|
12 |
|
if (!$this->isIterable($input)) { |
52
|
5 |
|
throw $this->reportError($input); |
53
|
|
|
} |
54
|
|
|
|
55
|
8 |
|
$exceptions = []; |
56
|
8 |
|
foreach ($input as $value) { |
57
|
|
|
try { |
58
|
7 |
|
$this->rule->assert($value); |
59
|
3 |
|
} catch (ValidationException $exception) { |
60
|
3 |
|
$exceptions[] = $exception; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
8 |
|
if (!empty($exceptions)) { |
65
|
|
|
/** @var EachException $eachException */ |
66
|
3 |
|
$eachException = $this->reportError($input); |
67
|
3 |
|
$eachException->addChildren($exceptions); |
68
|
|
|
|
69
|
3 |
|
throw $eachException; |
70
|
|
|
} |
71
|
5 |
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* {@inheritDoc} |
75
|
|
|
*/ |
76
|
11 |
|
public function check($input): void |
77
|
|
|
{ |
78
|
|
|
if (!$this->isIterable($input)) { |
79
|
11 |
|
throw $this->reportError($input); |
80
|
6 |
|
} |
81
|
6 |
|
|
82
|
|
|
foreach ($input as $value) { |
83
|
|
|
$this->rule->check($value); |
84
|
5 |
|
} |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* {@inheritDoc} |
89
|
|
|
*/ |
90
|
|
|
public function validate($input): bool |
91
|
|
|
{ |
92
|
|
|
try { |
93
|
|
|
$this->check($input); |
94
|
|
|
} catch (ValidationException $exception) { |
95
|
|
|
return false; |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return true; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|