-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputValidator.php
80 lines (66 loc) · 2.34 KB
/
InputValidator.php
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
<?php
declare(strict_types=1);
/*
* This file is part of the RollerworksSearch package.
*
* (c) Sebastiaan Stok <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Rollerworks\Component\Search\Extension\Symfony\Validator;
use Rollerworks\Component\Search\ConditionErrorMessage;
use Rollerworks\Component\Search\ErrorList;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\Input\Validator;
use Rollerworks\Component\Search\Value\PatternMatch;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Validates input values using the Symfony Validator.
*
* The search field must have a `constraints` option set
* or else it's ignored.
*
* @author Sebastiaan Stok <[email protected]>
*/
final class InputValidator implements Validator
{
private ValidatorInterface $validator;
private FieldConfig $field;
private ErrorList $errorList;
/** @var Constraint[]|null */
private ?array $constraints = [];
/** @var Constraint[]|null */
private ?array $patternMatchConstraints;
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
public function initializeContext(FieldConfig $field, ErrorList $errorList): void
{
$this->field = $field;
$this->errorList = $errorList;
$this->constraints = $field->getOption('constraints');
$this->patternMatchConstraints = $field->getOption('pattern_match_constraints');
}
public function validate($value, string $type, $originalValue, string $path): bool
{
$constraints = $type === PatternMatch::class ? $this->patternMatchConstraints : $this->constraints;
if ($constraints === null) {
return true;
}
$violations = $this->validator->validate($value, $constraints);
foreach ($violations as $violation) {
$this->errorList[] = new ConditionErrorMessage(
$path,
$violation->getMessage(),
$violation->getMessageTemplate(),
$violation->getParameters(),
$violation->getPlural(),
$violation
);
}
return ! \count($violations);
}
}