|
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 string |
|
20
|
|
|
*/ |
|
21
|
|
|
protected string $errorName; |
|
22
|
|
|
/** |
|
23
|
|
|
* @var callable |
|
24
|
|
|
*/ |
|
25
|
|
|
protected $predicate; |
|
26
|
|
|
/** |
|
27
|
|
|
* @var array<string, mixed> |
|
28
|
|
|
*/ |
|
29
|
|
|
protected array $params; |
|
30
|
|
|
/** |
|
31
|
|
|
* @var array<CheckInterface> |
|
32
|
|
|
*/ |
|
33
|
|
|
protected array $dependsOnChecks; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param string $name |
|
37
|
|
|
* @param string $errorName |
|
38
|
|
|
* @param callable $predicate |
|
39
|
|
|
* @param array<string, mixed> $params |
|
40
|
|
|
* @param array<CheckInterface> $dependsOnChecks |
|
41
|
|
|
*/ |
|
42
|
101 |
|
public function __construct( |
|
43
|
|
|
string $name, |
|
44
|
|
|
string $errorName, |
|
45
|
|
|
callable $predicate, |
|
46
|
|
|
array $params = [], |
|
47
|
|
|
array $dependsOnChecks = [] |
|
48
|
|
|
) { |
|
49
|
101 |
|
$this->name = $name; |
|
50
|
101 |
|
$this->errorName = $errorName; |
|
51
|
101 |
|
$this->predicate = $predicate; |
|
52
|
101 |
|
$this->params = $params; |
|
53
|
101 |
|
$this->dependsOnChecks = $dependsOnChecks; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* {@inheritDoc} |
|
58
|
|
|
*/ |
|
59
|
98 |
|
public function execute($value, array $previousErrors): void |
|
60
|
|
|
{ |
|
61
|
98 |
|
foreach ($this->dependsOnChecks as $check) { |
|
62
|
11 |
|
$check->execute($value, $previousErrors); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
try { |
|
66
|
98 |
|
if (($this->predicate)($value, ...array_values($this->params)) === false) { |
|
67
|
98 |
|
throw new CheckError($this->errorName, $value, $this->params); |
|
68
|
|
|
} |
|
69
|
56 |
|
} catch (ValidationError $e) { |
|
70
|
3 |
|
$params = $this->params; |
|
71
|
3 |
|
$params[Param::RULE] = $e->getName(); |
|
72
|
3 |
|
$params[Param::VIOLATIONS] = $e->getSummary(); |
|
73
|
3 |
|
throw new CheckError($this->errorName, $value, $params); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|