<?php
namespace nur\data\types;

class MailType extends RegexpType {
  const PATTERN = '/^.+/';
  const PATTERN_NORMALIZED = '/^(\S+)$/';

  protected function extractParsedValue(array $ms) {
    $mail = $ms[0];
    $mail = filter_var($mail, FILTER_SANITIZE_EMAIL);
    //$mail = filter_var($mail, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
    if ($mail === false) return false;
    if (preg_match('/^([^@+]+)(\+[^@]*)?(@.+)$/', $mail, $ms)) {
      return [$ms[1], $ms[2], $ms[3]];
    } else {
      return false;
      #return $mail;
    }
  }

  function verifixConvert(&$value): bool {
    if ($value === null) return true;
    elseif ($value === false) return false;
    if (is_array($value)) {
      [$local, $alias, $domain] = $value;
      if (strpos($local, ".") !== false) $local = strtolower($local);
      $domain = strtolower($domain);
      $value = "$local$alias$domain";
    }
    return true;
  }
}
