-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooked-rule-validation.php
More file actions
68 lines (54 loc) · 1.48 KB
/
hooked-rule-validation.php
File metadata and controls
68 lines (54 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
use TinyTalkMessages\Validation\Data\ErrorField;
use TinyTalkMessages\Validation\Data\Errors;
use TinyTalkMessages\Validation\Interfaces\RuleInterface;
use TinyTalkMessages\Validation\Interfaces\ValidatorInterface;
// Example rule
final readonly class Required implements RuleInterface
{
public function __construct(private ExampleValidator $validator)
{
}
public function check(string $field, mixed $value): bool
{
if ($value === null) {
$this->validator->getErrors()->add(new ErrorField($field, "$field is required."));
return false;
}
return true;
}
public function message(): ?string
{
return null;
}
}
final class ExampleValidator implements ValidatorInterface
{
private const array REQUIRED_FIELDS = [
'email',
'password',
];
private Errors $errors;
public function __construct()
{
$this->errors = new Errors();
}
public function validate(array $data): bool
{
$hasNotErrors = false;
$rule = new Required($this);
foreach (self::REQUIRED_FIELDS as $field) {
if ($rule->check($field, $data['field'] ?? null)) {
$hasNotErrors = true;
}
}
return $hasNotErrors;
}
public function getErrors(): Errors
{
return $this->errors;
}
}
$validator = new ExampleValidator();
$validator->validate([]); // false
echo count($validator->getErrors()); // -> 2