EmailValidator.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 EmailValidator 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. $valid = filter_var($value, FILTER_VALIDATE_EMAIL);
  26. if ($valid) {
  27. $host = substr($value, strpos($value, '@') + 1);
  28. if (version_compare(PHP_VERSION, '5.3.3', '<') && strpos($host, '.') === false) {
  29. // Likely not a FQDN, bug in PHP FILTER_VALIDATE_EMAIL prior to PHP 5.3.3
  30. $valid = false;
  31. }
  32. // Check MX records
  33. if ($valid && $constraint->checkMX) {
  34. $valid = $this->checkMX($host);
  35. }
  36. }
  37. if (!$valid) {
  38. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  39. return false;
  40. }
  41. return true;
  42. }
  43. /**
  44. * Check DNS Records for MX type.
  45. *
  46. * @param string $host Host name
  47. *
  48. * @return Boolean
  49. */
  50. private function checkMX($host)
  51. {
  52. if (function_exists('checkdnsrr')) {
  53. return checkdnsrr($host, 'MX');
  54. }
  55. throw new \LogicException('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning');
  56. }
  57. }