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.md" |
9
|
|
|
* file 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\ValidationException; |
17
|
|
|
use Respect\Validation\Validatable; |
18
|
|
|
|
19
|
|
|
class Each extends IterableType |
20
|
|
|
{ |
21
|
|
|
public $itemValidator; |
22
|
|
|
public $keyValidator; |
23
|
|
|
|
24
|
7 |
|
public function __construct(Validatable $itemValidator = null, Validatable $keyValidator = null) |
25
|
|
|
{ |
26
|
7 |
|
$this->itemValidator = $itemValidator; |
27
|
7 |
|
$this->keyValidator = $keyValidator; |
28
|
7 |
|
} |
29
|
|
|
|
30
|
6 |
|
public function assert($input): void |
31
|
|
|
{ |
32
|
6 |
|
$exceptions = []; |
33
|
|
|
|
34
|
6 |
|
if (!parent::validate($input)) { |
35
|
1 |
|
throw $this->reportError($input); |
36
|
|
|
} |
37
|
|
|
|
38
|
5 |
|
foreach ($input as $key => $item) { |
39
|
5 |
|
if (isset($this->itemValidator)) { |
40
|
|
|
try { |
41
|
3 |
|
$this->itemValidator->assert($item); |
42
|
1 |
|
} catch (ValidationException $e) { |
43
|
1 |
|
$exceptions[] = $e; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
5 |
|
if (isset($this->keyValidator)) { |
48
|
|
|
try { |
49
|
3 |
|
$this->keyValidator->assert($key); |
50
|
1 |
|
} catch (ValidationException $e) { |
51
|
5 |
|
$exceptions[] = $e; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
5 |
|
if (!empty($exceptions)) { |
57
|
2 |
|
throw $this->reportError($input)->setRelated($exceptions); |
|
|
|
|
58
|
|
|
} |
59
|
3 |
|
} |
60
|
|
|
|
61
|
4 |
|
public function check($input): void |
62
|
|
|
{ |
63
|
4 |
|
if (!parent::validate($input)) { |
64
|
1 |
|
throw $this->reportError($input); |
65
|
|
|
} |
66
|
|
|
|
67
|
3 |
|
foreach ($input as $key => $item) { |
68
|
3 |
|
if (isset($this->itemValidator)) { |
69
|
2 |
|
$this->itemValidator->check($item); |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
if (isset($this->keyValidator)) { |
73
|
3 |
|
$this->keyValidator->check($key); |
74
|
|
|
} |
75
|
|
|
} |
76
|
3 |
|
} |
77
|
|
|
|
78
|
11 |
|
public function validate($input): bool |
79
|
|
|
{ |
80
|
11 |
|
if (!parent::validate($input)) { |
81
|
4 |
|
return false; |
82
|
|
|
} |
83
|
|
|
|
84
|
7 |
|
foreach ($input as $key => $item) { |
85
|
7 |
|
if (isset($this->itemValidator) && !$this->itemValidator->validate($item)) { |
86
|
1 |
|
return false; |
87
|
|
|
} |
88
|
|
|
|
89
|
6 |
|
if (isset($this->keyValidator) && !$this->keyValidator->validate($key)) { |
90
|
6 |
|
return false; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|
94
|
5 |
|
return true; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|