1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Smoren\Validator\Checks; |
6
|
|
|
|
7
|
|
|
use Smoren\Validator\Exceptions\CheckError; |
8
|
|
|
use Smoren\Validator\Exceptions\ValidationError; |
9
|
|
|
use Smoren\Validator\Interfaces\CheckInterface; |
10
|
|
|
use Smoren\Validator\Structs\Param; |
11
|
|
|
|
12
|
|
|
class Check implements CheckInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
protected string $name; |
18
|
|
|
/** |
19
|
|
|
* @var callable |
20
|
|
|
*/ |
21
|
|
|
protected $predicate; |
22
|
|
|
/** |
23
|
|
|
* @var array<string, mixed> |
24
|
|
|
*/ |
25
|
|
|
protected array $params; |
26
|
|
|
/** |
27
|
|
|
* @var array<string, callable> |
28
|
|
|
*/ |
29
|
|
|
protected array $calculatedParams; |
30
|
|
|
/** |
31
|
|
|
* @var array<CheckInterface> |
32
|
|
|
*/ |
33
|
|
|
protected array $dependencies; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param string $name |
37
|
|
|
* @param callable $predicate |
38
|
|
|
* @param array<string, mixed> $params |
39
|
|
|
* @param array<string, callable> $calculatedParams |
40
|
|
|
* @param array<CheckInterface> $dependencies |
41
|
|
|
*/ |
42
|
292 |
|
public function __construct( |
43
|
|
|
string $name, |
44
|
|
|
callable $predicate, |
45
|
|
|
array $params = [], |
46
|
|
|
array $calculatedParams = [], |
47
|
|
|
array $dependencies = [] |
48
|
|
|
) { |
49
|
292 |
|
$this->name = $name; |
50
|
292 |
|
$this->predicate = $predicate; |
51
|
292 |
|
$this->params = $params; |
52
|
292 |
|
$this->calculatedParams = $calculatedParams; |
53
|
292 |
|
$this->dependencies = $dependencies; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* {@inheritDoc} |
58
|
|
|
*/ |
59
|
286 |
|
public function __invoke($value, array $previousErrors, bool $preventDuplicate = false): void |
60
|
|
|
{ |
61
|
286 |
|
if ($preventDuplicate) { |
62
|
49 |
|
foreach ($previousErrors as $error) { |
63
|
5 |
|
if ($error->getName() === $this->name) { |
64
|
2 |
|
return; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
286 |
|
foreach ($this->dependencies as $check) { |
70
|
49 |
|
$check( |
71
|
49 |
|
$value, |
72
|
49 |
|
$previousErrors, |
73
|
49 |
|
true |
74
|
49 |
|
); |
75
|
|
|
} |
76
|
|
|
|
77
|
286 |
|
$params = $this->params; |
78
|
286 |
|
foreach ($this->calculatedParams as $key => $paramGetter) { |
79
|
3 |
|
$params[$key] = $paramGetter($value); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
try { |
83
|
286 |
|
if (($this->predicate)($value, ...array_values($params)) === false) { |
84
|
286 |
|
throw new CheckError($this->name, $value, $params); |
85
|
|
|
} |
86
|
160 |
|
} catch (ValidationError $e) { |
87
|
15 |
|
$params[Param::RULE] = $e->getName(); |
88
|
15 |
|
$params[Param::VIOLATED_RESTRICTIONS] = $e->getViolatedRestrictions(); |
89
|
15 |
|
throw new CheckError($this->name, $value, $params); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|