use php_std::filter::{self, FILTER_VALIDATE_EMAIL, Options};
use php_std::{mb, string};
use crate::Error;
use crate::canonicals::{Canonical, PROVIDERS, Provider};
pub const LOCAL_MAX_LENGTH: usize = 64;
pub const DOMAIN_MAX_LENGTH: usize = 253;
fn filtered(value: &[u8]) -> bool {
matches!(
filter::filter_var(&filter::Value::Str(value.to_vec()), FILTER_VALIDATE_EMAIL, &Options::Flags(0)),
Ok(filter::Filtered { value: filter::Value::Str(_), .. })
)
}
fn empty(s: &[u8]) -> bool {
s.is_empty() || s == b"0"
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Email {
email: Vec<u8>,
at: usize,
}
impl Email {
pub fn new(input: impl AsRef<[u8]>) -> Result<Self, Error> {
let input = input.as_ref();
let email = mb::mb_strtolower(string::trim(input, string::TRIM_CHARACTERS));
if empty(&email) {
return Err(Error::Parse(b"Email address cannot be empty".to_vec()));
}
let invalid = || Error::Parse([b"'", input, b"' must be a valid email address"].concat());
let mut ats = email.iter().enumerate().filter(|(_, byte)| **byte == b'@').map(|(at, _)| at);
let (Some(at), None) = (ats.next(), ats.next()) else {
return Err(invalid());
};
if empty(&email[..at]) || empty(&email[at + 1..]) {
return Err(invalid());
}
Ok(Self { email, at })
}
pub fn get(&self) -> &[u8] {
&self.email
}
pub fn local(&self) -> &[u8] {
&self.email[..self.at]
}
pub fn domain(&self) -> &[u8] {
&self.email[self.at + 1..]
}
pub fn is_valid(&self) -> bool {
filtered(&self.email)
}
pub fn has_valid_local(&self) -> bool {
let local = self.local();
if mb::mb_strlen(local) > LOCAL_MAX_LENGTH {
return false;
}
let body = local.strip_suffix(b"\n").unwrap_or(local);
let matched = !body.is_empty()
&& body.iter().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-'));
matched && !local.windows(2).any(|pair| pair == b"..") && !local.starts_with(b".") && !local.ends_with(b".")
}
pub fn has_valid_domain_syntax(&self) -> bool {
let domain = self.domain();
mb::mb_strlen(domain) <= DOMAIN_MAX_LENGTH && filtered(&[b"test@", domain].concat())
}
pub fn canonical(&self) -> Result<Canonical, Error> {
Provider::of(self.domain()).canonical(self.local(), self.domain())
}
pub fn is_canonical_supported(&self) -> bool {
PROVIDERS.iter().any(|provider| provider.supports(self.domain()))
}
pub fn canonical_domain(&self) -> Option<&'static str> {
PROVIDERS.iter().find(|provider| provider.supports(self.domain())).map(|provider| provider.canonical_domain)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parts() {
let email = Email::new(" User.Name+Tag@Mail.Company.CO.UK \n").unwrap();
assert_eq!(email.get(), b"user.name+tag@mail.company.co.uk");
assert_eq!((email.local(), email.domain()), (&b"user.name+tag"[..], &b"mail.company.co.uk"[..]));
assert!(email.is_valid() && email.has_valid_local() && email.has_valid_domain_syntax());
assert_eq!(Email::new("ÄB@X.COM").unwrap().get(), "äb@x.com".as_bytes());
}
#[test]
fn errors() {
let message = |input: &[u8]| Email::new(input).unwrap_err().message().to_vec();
assert_eq!(message(b" \t"), b"Email address cannot be empty");
assert_eq!(message(b"0"), b"Email address cannot be empty");
assert_eq!(message(b"a@b@c"), b"'a@b@c' must be a valid email address");
assert_eq!(message(b" \xff "), b"' \xff ' must be a valid email address");
assert_eq!(message(b"0@x.com"), b"'0@x.com' must be a valid email address");
assert_eq!(message(b"a@0"), b"'a@0' must be a valid email address");
}
#[test]
fn local() {
let valid = |s: &str| Email::new(s).unwrap().has_valid_local();
assert!(valid("a.b_c+d-e@x.com") && valid("abc\n@x.com"));
assert!(!valid("a..b@x.com") && !valid(".a@x.com") && !valid("a.@x.com") && !valid("ä@x.com"));
assert!(!valid(&format!("{}@x.com", "a".repeat(65))));
}
#[test]
fn canonical() {
let email = Email::new("John.Doe+tag@GoogleMail.com").unwrap();
assert_eq!(email.canonical().unwrap().address(), b"johndoe@gmail.com");
assert_eq!(email.canonical_domain(), Some("gmail.com"));
assert!(email.is_canonical_supported());
let other = Email::new("a@example.com").unwrap();
assert_eq!((other.canonical_domain(), other.is_canonical_supported()), (None, false));
}
}