-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidator.php
More file actions
90 lines (74 loc) · 2.69 KB
/
Copy pathValidator.php
File metadata and controls
90 lines (74 loc) · 2.69 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
/*
* This file is part of the univeros/framework
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Altair\Validation;
use Altair\Middleware\Contracts\PayloadInterface as MiddlewarePayloadInterface;
use Altair\Middleware\Payload;
use Altair\Validation\Contracts\PayloadInterface;
use Altair\Validation\Contracts\RulesRunnerInterface;
use Altair\Validation\Contracts\ValidatableInterface;
use Altair\Validation\Contracts\ValidatorInterface;
use Override;
class Validator implements ValidatorInterface
{
protected MiddlewarePayloadInterface $payload;
/**
* Validator constructor.
*/
public function __construct(protected RulesRunnerInterface $runner) {}
#[Override]
public function validate(ValidatableInterface $validatable): bool
{
$this->payload = $this->buildPayload($validatable);
foreach ($validatable->getRules() as $key => $value) {
$keys = explode(',', $this->sanitize($key));
foreach ($keys as $attribute) {
$rules = \is_array($value) ? $value : [$value];
$runner = $this->runner->withRules($rules);
$payload = $this->payload->withAttribute(PayloadInterface::ATTRIBUTE_KEY, $attribute);
$this->payload = \call_user_func($runner, $payload);
}
}
return $this->payload->getAttribute(PayloadInterface::ATTRIBUTE_RESULT) === true;
}
/**
* @inheritDoc
*/
#[Override]
public function getPayload(): ?MiddlewarePayloadInterface
{
return $this->payload;
}
/**
* Create a Payload instance with ValidatableInterface as its subject and add the rest of the subject's attributes
* that are going to be validated. That way we could make use of a LoggingMiddleware class and extract the
* attributes using "Payload::getAttributes()".
*
*
*/
protected function buildPayload(ValidatableInterface $validatable): MiddlewarePayloadInterface
{
$attributes = [
PayloadInterface::ATTRIBUTE_SUBJECT => $validatable,
];
foreach ($validatable->getRules()->keys() as $key) {
$keys = explode(',', $this->sanitize($key));
foreach ($keys as $attribute) {
if (isset($attributes[$attribute])) {
continue;
}
$attributes[$attribute] = $validatable->$attribute;
}
}
return new Payload($attributes);
}
protected function sanitize(string $value): string
{
return preg_replace('/\s+/', '', $value) ?? $value;
}
}