RegexValidator.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. class RegexValidator extends ConstraintValidator
  15. {
  16. public function isValid($value, Constraint $constraint)
  17. {
  18. if (null === $value || '' === $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. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  31. return false;
  32. }
  33. return true;
  34. }
  35. }