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 EveryElement 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 | * @param mixed $data should receive an array; the type hint is mixed because of contravariance |
||
55 | * @param array $context |
||
56 | * @return ValidationResult |
||
57 | */ |
||
58 | public function validate($data, array $context = []): ValidationResult |
||
59 | { |
||
60 | $errorFormatter = $this->errorFormatter; |
||
61 | |||
62 | $result = ValidationResult::valid($data); |
||
63 | |||
64 | foreach ($data as $key => $element) { |
||
65 | $result = $result->join( |
||
66 | $this->elementValidation->validate($data[$key], $context), |
||
67 | /** |
||
68 | * @template T |
||
69 | * @template U |
||
70 | * @psalm-param T $a |
||
71 | * @psalm-param U $b |
||
72 | * @return T |
||
73 | */ |
||
74 | function ($a, $b) { |
||
0 ignored issues
–
show
|
|||
75 | return $a; |
||
76 | }, |
||
77 | function (array $resultMessages, array $validationMessages) use ($key, $errorFormatter): array { |
||
78 | return $errorFormatter($key, $resultMessages, $validationMessages); |
||
79 | } |
||
80 | ); |
||
81 | } |
||
82 | |||
83 | return $result; |
||
84 | } |
||
85 | } |
||
86 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.