-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathReferenceValidator.php
40 lines (32 loc) · 1.39 KB
/
ReferenceValidator.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
<?php declare(strict_types=1);
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class ReferenceValidator extends ConstraintValidator
{
const PATTERN = '/^[a-zA-Z0-9]+$/';
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Reference) {
throw new UnexpectedTypeException($constraint, Reference::class);
}
// custom constraints should ignore null and empty values to allow
// other constraints (NotBlank, NotNull, etc.) take care of that
if (null === $value || '' === $value) {
return;
}
if (!is_string($value)) {
// throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
throw new UnexpectedValueException($value, 'string');
// separate multiple types using pipes
// throw new UnexpectedValueException($value, 'string|int');
}
if (!preg_match(self::PATTERN, $value, $matches)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value)
->addViolation();
}
}
}