RegexValidator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. /**
  16. * Validates whether a value match or not given regexp pattern.
  17. *
  18. * @author Bernhard Schussek <bschussek@gmail.com>
  19. * @author Joseph Bielawski <stloyd@gmail.com>
  20. */
  21. class RegexValidator extends ConstraintValidator
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function validate($value, Constraint $constraint)
  27. {
  28. if (!$constraint instanceof Regex) {
  29. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Regex');
  30. }
  31. if (null === $value || '' === $value) {
  32. return;
  33. }
  34. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
  35. throw new UnexpectedTypeException($value, 'string');
  36. }
  37. $value = (string) $value;
  38. if ($constraint->match xor preg_match($constraint->pattern, $value)) {
  39. if ($this->context instanceof ExecutionContextInterface) {
  40. $this->context->buildViolation($constraint->message)
  41. ->setParameter('{{ value }}', $this->formatValue($value))
  42. ->setCode(Regex::REGEX_FAILED_ERROR)
  43. ->addViolation();
  44. } else {
  45. $this->buildViolation($constraint->message)
  46. ->setParameter('{{ value }}', $this->formatValue($value))
  47. ->setCode(Regex::REGEX_FAILED_ERROR)
  48. ->addViolation();
  49. }
  50. }
  51. }
  52. }