1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Marcosh\PhpValidationDSL\Basic; |
6
|
|
|
|
7
|
|
|
use Marcosh\PhpValidationDSL\Result\ValidationResult; |
8
|
|
|
use Marcosh\PhpValidationDSL\Translator\Translator; |
9
|
|
|
use function is_callable; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @template T |
13
|
|
|
*/ |
14
|
|
|
abstract class ComposingAssertion |
15
|
|
|
{ |
16
|
|
|
public const MESSAGE = 'composing-assertion.not-as-asserted'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var callable|null with signature $data -> string[] |
20
|
|
|
*/ |
21
|
|
|
private $errorFormatter; |
22
|
|
|
|
23
|
|
|
public function __construct(?callable $errorFormatter = null) |
24
|
|
|
{ |
25
|
|
|
$this->errorFormatter = $errorFormatter; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public static function withFormatter(callable $errorFormatter): self |
29
|
|
|
{ |
30
|
|
|
return new static($errorFormatter); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public static function withTranslator(Translator $translator): self |
34
|
|
|
{ |
35
|
|
|
return new static( |
36
|
|
|
/** |
37
|
|
|
* @param mixed $data |
38
|
|
|
* @psalm-param T $data |
39
|
|
|
* @return string[] |
40
|
|
|
* @psalm-return array{0:mixed} |
41
|
|
|
*/ |
42
|
|
|
function ($data) use ($translator): array { |
|
|
|
|
43
|
|
|
return [$translator->translate(static::MESSAGE)]; |
44
|
|
|
} |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param mixed $data |
50
|
|
|
* @psalm-param T $data |
51
|
|
|
* @param array $context |
52
|
|
|
* @return ValidationResult |
53
|
|
|
*/ |
54
|
|
|
abstract public function validate($data, array $context = []): ValidationResult; |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param callable $assertion |
58
|
|
|
* @param mixed $data |
59
|
|
|
* @psalm-param T $data |
60
|
|
|
* @param array $context |
61
|
|
|
* @return ValidationResult |
62
|
|
|
*/ |
63
|
|
|
protected function validateAssertion(callable $assertion, $data, array $context = []): ValidationResult |
64
|
|
|
{ |
65
|
|
|
return IsAsAsserted::withAssertionAndErrorFormatter( |
66
|
|
|
$assertion, |
67
|
|
|
is_callable($this->errorFormatter) ? |
|
|
|
|
68
|
|
|
$this->errorFormatter : |
69
|
|
|
/** |
70
|
|
|
* @param mixed $data |
71
|
|
|
* @psalm-param T $data |
72
|
|
|
* @return string[] |
73
|
|
|
* @psalm-return array{0:mixed} |
74
|
|
|
*/ |
75
|
|
|
function ($data): array { |
|
|
|
|
76
|
|
|
return [static::MESSAGE]; |
77
|
|
|
} |
78
|
|
|
)->validate($data, $context); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.