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 Marcosh\PhpValidationDSL\Validation; |
10
|
|
|
use function is_callable; |
11
|
|
|
|
12
|
|
|
final class IsAsAsserted implements Validation |
13
|
|
|
{ |
14
|
|
|
public const NOT_AS_ASSERTED = 'is-as-asserted.not-as-asserted'; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var callable $data -> bool |
18
|
|
|
*/ |
19
|
|
|
private $assertion; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var callable $data -> string[] |
23
|
|
|
*/ |
24
|
|
|
private $errorFormatter; |
25
|
|
|
|
26
|
|
|
private function __construct(callable $assertion, ?callable $errorFormatter = null) |
27
|
|
|
{ |
28
|
|
|
$this->assertion = $assertion; |
29
|
|
|
$this->errorFormatter = is_callable($errorFormatter) ? |
30
|
|
|
$errorFormatter : |
31
|
|
|
function ($data) { |
|
|
|
|
32
|
|
|
return [self::NOT_AS_ASSERTED]; |
33
|
|
|
}; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public static function withAssertion(callable $assertion): self |
37
|
|
|
{ |
38
|
|
|
return new self($assertion); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public static function withAssertionAndErrorFormatter(callable $assertion, callable $errorFormatter): self |
42
|
|
|
{ |
43
|
|
|
return new self($assertion, $errorFormatter); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public static function withAssertionAndTranslator(callable $assertion, Translator $translator): self |
47
|
|
|
{ |
48
|
|
|
return new self( |
49
|
|
|
$assertion, |
50
|
|
|
function ($data) use ($translator) { |
|
|
|
|
51
|
|
|
return [$translator->translate(self::NOT_AS_ASSERTED)]; |
52
|
|
|
} |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function validate($data, array $context = []): ValidationResult |
57
|
|
|
{ |
58
|
|
|
if (! ($this->assertion)($data)) { |
59
|
|
|
return ValidationResult::errors(($this->errorFormatter)($data)); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return ValidationResult::valid($data); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.