1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Marcosh\PhpValidationDSL\Combinator; |
6
|
|
|
|
7
|
|
|
use Marcosh\PhpValidationDSL\Result\ValidationResult; |
8
|
|
|
use Marcosh\PhpValidationDSL\Validation; |
9
|
|
|
use function is_callable; |
10
|
|
|
|
11
|
|
|
final class AnyElement implements Validation |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Validation |
15
|
|
|
*/ |
16
|
|
|
private $elementValidation; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var callable with signature $key -> $resultMessages -> $validationMessages -> array |
20
|
|
|
*/ |
21
|
|
|
private $errorFormatter; |
22
|
|
|
|
23
|
|
|
private function __construct(Validation $validation, ?callable $errorFormatter = null) |
24
|
|
|
{ |
25
|
|
|
$this->elementValidation = $validation; |
26
|
|
|
$this->errorFormatter = is_callable($errorFormatter) ? |
27
|
|
|
$errorFormatter : |
28
|
|
|
/** |
29
|
|
|
* @template K |
30
|
|
|
* @template V |
31
|
|
|
* @psalm-param K $key |
32
|
|
|
* @param array<K, V> $resultMessages |
33
|
|
|
* @param array $validationMessages |
34
|
|
|
* @return array<K, V> |
35
|
|
|
*/ |
36
|
|
|
function ($key, array $resultMessages, array $validationMessages): array { |
37
|
|
|
$resultMessages[$key] = $validationMessages; |
38
|
|
|
|
39
|
|
|
return $resultMessages; |
40
|
|
|
}; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public static function validation(Validation $validation): self |
44
|
|
|
{ |
45
|
|
|
return new self($validation); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public static function validationWithFormatter(Validation $validation, callable $errorFormatter): self |
49
|
|
|
{ |
50
|
|
|
return new self($validation, $errorFormatter); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @template T |
55
|
|
|
* @psalm-param T $data |
56
|
|
|
* @param mixed $data should receive an array; the type hint is mixed because of contravariance |
57
|
|
|
* @param array $context |
58
|
|
|
* @return ValidationResult |
59
|
|
|
*/ |
60
|
|
|
public function validate($data, array $context = []): ValidationResult |
61
|
|
|
{ |
62
|
|
|
$errorFormatter = $this->errorFormatter; |
63
|
|
|
|
64
|
|
|
$result = ValidationResult::errors([]); |
65
|
|
|
|
66
|
|
|
foreach ($data as $key => $element) { |
67
|
|
|
$result = $result->meet( |
68
|
|
|
$this->elementValidation->validate($data[$key], $context), |
69
|
|
|
/** |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
|
|
function (array $resultMessages, array $validationMessages) use ($key, $errorFormatter) { |
73
|
|
|
return $errorFormatter($key, $resultMessages, $validationMessages); |
74
|
|
|
} |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $result->map( |
79
|
|
|
/** |
80
|
|
|
* @return T |
81
|
|
|
*/ |
82
|
|
|
function () use ($data) { |
83
|
|
|
return $data; |
84
|
|
|
} |
85
|
|
|
); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|