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