<?php

namespace App\Helpers;

class EmailValidator
{

    public function __construct(){

    }
    
    public function isValidFormat(string $email): bool {
      return filter_var($email, FILTER_VALIDATE_EMAIL);
    }
  
    public function domainExists(string $email): bool {
      list(, $domain) = explode('@', $email);
      return checkdnsrr($domain, 'MX');
    }
  
    public function isDisposable(string $email): bool {
      list(, $domain) = explode('@', $email);
      return in_array($domain, self::getDisposableDomains());
    }
  
    public function validate(string $email): array {
      return [
        'valid' => $this->isValidFormat($email) && $this->domainExists($email),
        'exists' => $this->domainExists($email),
        'disposable' => $this->isDisposable($email)
      ];
    }

    public static function getDisposableDomains() {
      $filename = __DIR__ . '/data/disposable-domains.txt';
      $file = fopen($filename, "r");
      $disposableDomains = array();
    
      while (!feof($file)) {
        $line = fgets($file);
        $disposableDomains[] = trim($line);
      }
    
      fclose($file);
      return $disposableDomains;
    }
}
