. */ namespace App\Validator\Constraints\Misc; use App\Services\Misc\RangeParser; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Exception\UnexpectedValueException; class ValidRangeValidator extends ConstraintValidator { protected RangeParser $rangeParser; public function __construct(RangeParser $rangeParser) { $this->rangeParser = $rangeParser; } public function validate($value, Constraint $constraint): void { if (!$constraint instanceof ValidRange) { throw new UnexpectedTypeException($constraint, ValidRange::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 new UnexpectedValueException($value, 'string'); } if (!$this->rangeParser->isValidRange($value)) { $this->context->buildViolation($constraint->message) ->addViolation(); } } }