RegexValidator.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  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, Regex::class);
  30. }
  31. if (null === $value || '' === $value) {
  32. return;
  33. }
  34. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  35. throw new UnexpectedValueException($value, 'string');
  36. }
  37. $value = (string) $value;
  38. if (null !== $constraint->normalizer) {
  39. $value = ($constraint->normalizer)($value);
  40. }
  41. if ($constraint->match xor preg_match($constraint->pattern, $value)) {
  42. $this->context->buildViolation($constraint->message)
  43. ->setParameter('{{ value }}', $this->formatValue($value))
  44. ->setCode(Regex::REGEX_FAILED_ERROR)
  45. ->addViolation();
  46. }
  47. }
  48. }