DNSCheckValidation.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Egulias\EmailValidator\Validation;
  3. use Egulias\EmailValidator\EmailLexer;
  4. use Egulias\EmailValidator\Exception\InvalidEmail;
  5. use Egulias\EmailValidator\Warning\NoDNSMXRecord;
  6. use Egulias\EmailValidator\Exception\NoDNSRecord;
  7. class DNSCheckValidation implements EmailValidation
  8. {
  9. /**
  10. * @var array
  11. */
  12. private $warnings = [];
  13. /**
  14. * @var InvalidEmail
  15. */
  16. private $error;
  17. public function __construct()
  18. {
  19. if (!extension_loaded('intl')) {
  20. throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
  21. }
  22. }
  23. public function isValid($email, EmailLexer $emailLexer)
  24. {
  25. // use the input to check DNS if we cannot extract something similar to a domain
  26. $host = $email;
  27. // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
  28. if (false !== $lastAtPos = strrpos($email, '@')) {
  29. $host = substr($email, $lastAtPos + 1);
  30. }
  31. return $this->checkDNS($host);
  32. }
  33. public function getError()
  34. {
  35. return $this->error;
  36. }
  37. public function getWarnings()
  38. {
  39. return $this->warnings;
  40. }
  41. protected function checkDNS($host)
  42. {
  43. $variant = INTL_IDNA_VARIANT_2003;
  44. if ( defined('INTL_IDNA_VARIANT_UTS46') ) {
  45. $variant = INTL_IDNA_VARIANT_UTS46;
  46. }
  47. $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.';
  48. $Aresult = true;
  49. $MXresult = checkdnsrr($host, 'MX');
  50. if (!$MXresult) {
  51. $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
  52. $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
  53. if (!$Aresult) {
  54. $this->error = new NoDNSRecord();
  55. }
  56. }
  57. return $MXresult || $Aresult;
  58. }
  59. }