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