|
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 IsInstanceOf implements Validation |
|
13
|
|
|
{ |
|
14
|
|
|
public const NOT_AN_INSTANCE = 'is-instance-of.not-an-instance'; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @var string |
|
18
|
|
|
*/ |
|
19
|
|
|
private $className; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var callable $key -> $data -> string[] |
|
23
|
|
|
*/ |
|
24
|
|
|
private $errorFormatter; |
|
25
|
|
|
|
|
26
|
|
|
private function __construct(string $className, ?callable $errorFormatter = null) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->className = $className; |
|
29
|
|
|
$this->errorFormatter = is_callable($errorFormatter) ? |
|
30
|
|
|
$errorFormatter : |
|
31
|
|
|
function (string $className, $data) { |
|
|
|
|
|
|
32
|
|
|
return [self::NOT_AN_INSTANCE]; |
|
33
|
|
|
}; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public static function withClassName(string $className): self |
|
37
|
|
|
{ |
|
38
|
|
|
return new self($className); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public static function withClassNameAndFormatter(string $className, callable $errorFormatter): self |
|
42
|
|
|
{ |
|
43
|
|
|
return new self($className, $errorFormatter); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public static function withClassNameAndTranslator(string $className, Translator $translator): self |
|
47
|
|
|
{ |
|
48
|
|
|
return new self( |
|
49
|
|
|
$className, |
|
50
|
|
|
function (string $className, $data) use ($translator) { |
|
|
|
|
|
|
51
|
|
|
return [$translator->translate(self::NOT_AN_INSTANCE)]; |
|
52
|
|
|
} |
|
53
|
|
|
); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function validate($data, array $context = []): ValidationResult |
|
57
|
|
|
{ |
|
58
|
|
|
if (! $data instanceof $this->className) { |
|
59
|
|
|
return ValidationResult::errors(($this->errorFormatter)($this->className, $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.