|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Smoren\Validator\Rules; |
|
4
|
|
|
|
|
5
|
|
|
use Smoren\Validator\Exceptions\CheckError; |
|
6
|
|
|
use Smoren\Validator\Exceptions\StopValidationException; |
|
7
|
|
|
use Smoren\Validator\Exceptions\ValidationError; |
|
8
|
|
|
use Smoren\Validator\Interfaces\CheckInterface; |
|
9
|
|
|
use Smoren\Validator\Interfaces\UniformRuleInterface; |
|
10
|
|
|
use Smoren\Validator\Structs\Check; |
|
11
|
|
|
|
|
12
|
|
|
class Rule extends NullableRule implements UniformRuleInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var array<CheckInterface> |
|
16
|
|
|
*/ |
|
17
|
|
|
protected array $checks = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* {@inheritDoc} |
|
21
|
|
|
*/ |
|
22
|
41 |
|
public function validate($value): void |
|
23
|
|
|
{ |
|
24
|
|
|
try { |
|
25
|
41 |
|
parent::validate($value); |
|
26
|
4 |
|
} catch (StopValidationException $e) { |
|
27
|
3 |
|
return; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
40 |
|
$errors = []; |
|
31
|
|
|
|
|
32
|
40 |
|
foreach ($this->checks as $check) { |
|
33
|
|
|
try { |
|
34
|
40 |
|
$check->execute($value); |
|
35
|
24 |
|
} catch (CheckError $e) { |
|
36
|
24 |
|
$errors[] = $e; |
|
37
|
24 |
|
if ($check->isInterrupting()) { |
|
38
|
7 |
|
throw ValidationError::fromCheckErrors($value, $errors); |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
33 |
|
if (\count($errors) > 0) { |
|
44
|
17 |
|
throw ValidationError::fromCheckErrors($value, $errors); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* {@inheritDoc} |
|
50
|
|
|
* |
|
51
|
|
|
* @return static |
|
52
|
|
|
*/ |
|
53
|
|
|
public function add(CheckInterface $check): self |
|
54
|
|
|
{ |
|
55
|
|
|
$this->checks[] = $check; |
|
56
|
|
|
return $this; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* {@inheritDoc} |
|
61
|
|
|
* |
|
62
|
|
|
* @return static |
|
63
|
|
|
*/ |
|
64
|
|
|
public function stopIfAnyPreviousFails(): self |
|
65
|
|
|
{ |
|
66
|
|
|
foreach ($this->checks as $check) { |
|
67
|
|
|
$check->setInterrupting(); |
|
68
|
|
|
} |
|
69
|
|
|
return $this; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* {@inheritDoc} |
|
74
|
|
|
* |
|
75
|
|
|
* @return static |
|
76
|
|
|
*/ |
|
77
|
|
|
public function stopOnFail(): self |
|
78
|
|
|
{ |
|
79
|
|
|
if (\count($this->checks) > 0) { |
|
80
|
|
|
$this->checks[\count($this->checks) - 1]->setInterrupting(); |
|
81
|
|
|
} |
|
82
|
|
|
return $this; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
/** |
|
86
|
|
|
* {@inheritDoc} |
|
87
|
|
|
* |
|
88
|
|
|
* @return static |
|
89
|
|
|
*/ |
|
90
|
|
|
public function check(string $name, callable $predicate, array $params = [], bool $isBlocking = false): self |
|
91
|
|
|
{ |
|
92
|
|
|
return $this->add(new Check($name, $predicate, $params, $isBlocking)); |
|
93
|
|
|
} |
|
94
|
|
|
} |
|
95
|
|
|
|