RegexValidator.php 972 B

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. namespace Symfony\Component\Validator\Constraints;
  3. use Symfony\Component\Validator\Constraint;
  4. use Symfony\Component\Validator\ConstraintValidator;
  5. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  6. class RegexValidator extends ConstraintValidator
  7. {
  8. public function isValid($value, Constraint $constraint)
  9. {
  10. if ($value === null) {
  11. return true;
  12. }
  13. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
  14. throw new UnexpectedTypeException($value, 'string');
  15. }
  16. $value = (string)$value;
  17. if (
  18. ($constraint->match && !preg_match($constraint->pattern, $value))
  19. ||
  20. (!$constraint->match && preg_match($constraint->pattern, $value))
  21. )
  22. {
  23. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  24. return false;
  25. }
  26. return true;
  27. }
  28. }