1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Marcosh\PhpValidationDSL\Combinator; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Marcosh\PhpValidationDSL\Basic\HasKey; |
9
|
|
|
use Marcosh\PhpValidationDSL\Basic\IsArray; |
10
|
|
|
use Marcosh\PhpValidationDSL\Result\ValidationResult; |
11
|
|
|
use Marcosh\PhpValidationDSL\Validation; |
12
|
|
|
use Webmozart\Assert\Assert; |
13
|
|
|
|
14
|
|
|
final class Associative implements Validation |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Validation[] |
18
|
|
|
*/ |
19
|
|
|
private $validations; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Validation[] $validations |
23
|
|
|
* @throws InvalidArgumentException |
24
|
|
|
*/ |
25
|
|
|
private function __construct(array $validations) |
26
|
|
|
{ |
27
|
|
|
Assert::allIsInstanceOf($validations, Validation::class); |
28
|
|
|
|
29
|
|
|
$this->validations = $validations; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param Validation[] $validations |
34
|
|
|
* @return self |
35
|
|
|
*/ |
36
|
|
|
public static function validations(array $validations) |
37
|
|
|
{ |
38
|
|
|
return new self($validations); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function validate($data, array $context = []): ValidationResult |
42
|
|
|
{ |
43
|
|
|
$wholeValidation = Sequence::validations([ |
44
|
|
|
new IsArray(), |
45
|
|
|
All::validations(array_map( |
46
|
|
|
/** |
47
|
|
|
* @param mixed $key |
48
|
|
|
* @param Validation $validation |
49
|
|
|
* @return Validation |
50
|
|
|
*/ |
51
|
|
|
static function ($key, Validation $validation) { |
52
|
|
|
return MapErrors::to( |
53
|
|
|
Sequence::validations([ |
54
|
|
|
HasKey::withKey($key), |
55
|
|
|
Focus::on( |
56
|
|
|
/** |
57
|
|
|
* @param array $wholeData |
58
|
|
|
* @return mixed |
59
|
|
|
*/ |
60
|
|
|
static function (array $wholeData) use ($key) { |
61
|
|
|
return $wholeData[$key]; |
62
|
|
|
}, |
63
|
|
|
$validation |
64
|
|
|
) |
65
|
|
|
]), |
66
|
|
|
/** |
67
|
|
|
* @param array $messages |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
|
|
static function (array $messages) use ($key) { |
71
|
|
|
return [$key => $messages]; |
72
|
|
|
} |
73
|
|
|
); |
74
|
|
|
}, |
75
|
|
|
array_keys($this->validations), |
76
|
|
|
$this->validations |
77
|
|
|
)) |
78
|
|
|
]); |
79
|
|
|
|
80
|
|
|
return $wholeValidation->validate($data, $context); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|