DNSCheckValidation.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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|null
  15. */
  16. private $error;
  17. public function __construct()
  18. {
  19. if (!function_exists('idn_to_ascii')) {
  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. /**
  42. * @param string $host
  43. *
  44. * @return bool
  45. */
  46. protected function checkDNS($host)
  47. {
  48. $variant = INTL_IDNA_VARIANT_2003;
  49. if ( defined('INTL_IDNA_VARIANT_UTS46') ) {
  50. $variant = INTL_IDNA_VARIANT_UTS46;
  51. }
  52. $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.';
  53. $Aresult = true;
  54. $MXresult = checkdnsrr($host, 'MX');
  55. if (!$MXresult) {
  56. $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
  57. $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
  58. if (!$Aresult) {
  59. $this->error = new NoDNSRecord();
  60. }
  61. }
  62. return $MXresult || $Aresult;
  63. }
  64. }