RegexValidator.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace Symfony\Component\Validator\Constraints;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. class RegexValidator extends ConstraintValidator
  15. {
  16. public function isValid($value, Constraint $constraint)
  17. {
  18. if ($value === null || $value === '') {
  19. return true;
  20. }
  21. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
  22. throw new UnexpectedTypeException($value, 'string');
  23. }
  24. $value = (string)$value;
  25. if (
  26. ($constraint->match && !preg_match($constraint->pattern, $value))
  27. ||
  28. (!$constraint->match && preg_match($constraint->pattern, $value))
  29. )
  30. {
  31. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  32. return false;
  33. }
  34. return true;
  35. }
  36. }