1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Marcosh\PhpValidationDSL\Combinator; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Marcosh\PhpValidationDSL\Result\ValidationResult; |
9
|
|
|
use Marcosh\PhpValidationDSL\Validation; |
10
|
|
|
use Webmozart\Assert\Assert; |
11
|
|
|
use function is_callable; |
12
|
|
|
|
13
|
|
|
final class All implements Validation |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var Validation[] |
17
|
|
|
*/ |
18
|
|
|
private $validations; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var callable ...array -> array |
22
|
|
|
*/ |
23
|
|
|
private $errorFormatter; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param Validation[] $validations |
27
|
|
|
* @param callable|null $errorFormatter |
28
|
|
|
* @throws InvalidArgumentException |
29
|
|
|
*/ |
30
|
|
|
private function __construct(array $validations, ?callable $errorFormatter = null) |
31
|
|
|
{ |
32
|
|
|
Assert::allIsInstanceOf($validations, Validation::class); |
33
|
|
|
|
34
|
|
|
$this->validations = $validations; |
35
|
|
|
$this->errorFormatter = is_callable($errorFormatter) ? |
36
|
|
|
$errorFormatter : |
37
|
|
|
'array_merge'; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param Validation[] $validations |
42
|
|
|
* @return self |
43
|
|
|
* @throws InvalidArgumentException |
44
|
|
|
*/ |
45
|
|
|
public static function validations(array $validations): self |
46
|
|
|
{ |
47
|
|
|
return new self($validations); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param Validation[] $validations |
52
|
|
|
* @param callable $errorFormatter |
53
|
|
|
* @return self |
54
|
|
|
* @throws InvalidArgumentException |
55
|
|
|
*/ |
56
|
|
|
public static function validationsWithFormatter(array $validations, callable $errorFormatter) |
57
|
|
|
{ |
58
|
|
|
return new self($validations, $errorFormatter); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function validate($data, array $context = []): ValidationResult |
62
|
|
|
{ |
63
|
|
|
$result = ValidationResult::valid($data); |
64
|
|
|
|
65
|
|
|
foreach ($this->validations as $validation) { |
66
|
|
|
$result = $result->join( |
67
|
|
|
$validation->validate($data, $context), |
68
|
|
|
/** |
69
|
|
|
* @template T |
70
|
|
|
* @template U |
71
|
|
|
* @psalm-param T $a |
72
|
|
|
* @psalm-param U $b |
73
|
|
|
* @return T |
74
|
|
|
*/ |
75
|
|
|
function ($a, $b) { |
|
|
|
|
76
|
|
|
return $a; |
77
|
|
|
}, |
78
|
|
|
$this->errorFormatter |
79
|
|
|
); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $result; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.