1use php_std::filter::{self, FILTER_VALIDATE_EMAIL, Options};
7use php_std::{mb, string};
8
9use crate::Error;
10use crate::canonicals::{Canonical, PROVIDERS, Provider};
11
12pub const LOCAL_MAX_LENGTH: usize = 64;
16
17pub const DOMAIN_MAX_LENGTH: usize = 253;
21
22fn filtered(value: &[u8]) -> bool {
26 matches!(
27 filter::filter_var(&filter::Value::Str(value.to_vec()), FILTER_VALIDATE_EMAIL, &Options::Flags(0)),
28 Ok(filter::Filtered { value: filter::Value::Str(_), .. })
29 )
30}
31
32fn empty(s: &[u8]) -> bool {
34 s.is_empty() || s == b"0"
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Email {
41 email: Vec<u8>,
42 at: usize,
44}
45
46impl Email {
47 pub fn new(input: impl AsRef<[u8]>) -> Result<Self, Error> {
56 let input = input.as_ref();
57 let email = mb::mb_strtolower(string::trim(input, string::TRIM_CHARACTERS));
58 if empty(&email) {
59 return Err(Error::Parse(b"Email address cannot be empty".to_vec()));
60 }
61 let invalid = || Error::Parse([b"'", input, b"' must be a valid email address"].concat());
62 let mut ats = email.iter().enumerate().filter(|(_, byte)| **byte == b'@').map(|(at, _)| at);
63 let (Some(at), None) = (ats.next(), ats.next()) else {
64 return Err(invalid());
65 };
66 if empty(&email[..at]) || empty(&email[at + 1..]) {
67 return Err(invalid());
68 }
69 Ok(Self { email, at })
70 }
71
72 pub fn get(&self) -> &[u8] {
76 &self.email
77 }
78
79 pub fn local(&self) -> &[u8] {
83 &self.email[..self.at]
84 }
85
86 pub fn domain(&self) -> &[u8] {
90 &self.email[self.at + 1..]
91 }
92
93 pub fn is_valid(&self) -> bool {
97 filtered(&self.email)
98 }
99
100 pub fn has_valid_local(&self) -> bool {
105 let local = self.local();
106 if mb::mb_strlen(local) > LOCAL_MAX_LENGTH {
107 return false;
108 }
109 let body = local.strip_suffix(b"\n").unwrap_or(local);
111 let matched = !body.is_empty()
112 && body.iter().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-'));
113 matched && !local.windows(2).any(|pair| pair == b"..") && !local.starts_with(b".") && !local.ends_with(b".")
114 }
115
116 pub fn has_valid_domain_syntax(&self) -> bool {
122 let domain = self.domain();
123 mb::mb_strlen(domain) <= DOMAIN_MAX_LENGTH && filtered(&[b"test@", domain].concat())
124 }
125
126 pub fn canonical(&self) -> Result<Canonical, Error> {
134 Provider::of(self.domain()).canonical(self.local(), self.domain())
135 }
136
137 pub fn is_canonical_supported(&self) -> bool {
141 PROVIDERS.iter().any(|provider| provider.supports(self.domain()))
142 }
143
144 pub fn canonical_domain(&self) -> Option<&'static str> {
149 PROVIDERS.iter().find(|provider| provider.supports(self.domain())).map(|provider| provider.canonical_domain)
150 }
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 #[test]
158 fn parts() {
159 let email = Email::new(" User.Name+Tag@Mail.Company.CO.UK \n").unwrap();
160 assert_eq!(email.get(), b"user.name+tag@mail.company.co.uk");
161 assert_eq!((email.local(), email.domain()), (&b"user.name+tag"[..], &b"mail.company.co.uk"[..]));
162 assert!(email.is_valid() && email.has_valid_local() && email.has_valid_domain_syntax());
163 assert_eq!(Email::new("ÄB@X.COM").unwrap().get(), "äb@x.com".as_bytes());
164 }
165
166 #[test]
167 fn errors() {
168 let message = |input: &[u8]| Email::new(input).unwrap_err().message().to_vec();
169 assert_eq!(message(b" \t"), b"Email address cannot be empty");
170 assert_eq!(message(b"0"), b"Email address cannot be empty");
171 assert_eq!(message(b"a@b@c"), b"'a@b@c' must be a valid email address");
172 assert_eq!(message(b" \xff "), b"' \xff ' must be a valid email address");
173 assert_eq!(message(b"0@x.com"), b"'0@x.com' must be a valid email address");
174 assert_eq!(message(b"a@0"), b"'a@0' must be a valid email address");
175 }
176
177 #[test]
178 fn local() {
179 let valid = |s: &str| Email::new(s).unwrap().has_valid_local();
180 assert!(valid("a.b_c+d-e@x.com") && valid("abc\n@x.com"));
181 assert!(!valid("a..b@x.com") && !valid(".a@x.com") && !valid("a.@x.com") && !valid("ä@x.com"));
182 assert!(!valid(&format!("{}@x.com", "a".repeat(65))));
183 }
184
185 #[test]
186 fn canonical() {
187 let email = Email::new("John.Doe+tag@GoogleMail.com").unwrap();
188 assert_eq!(email.canonical().unwrap().address(), b"johndoe@gmail.com");
189 assert_eq!(email.canonical_domain(), Some("gmail.com"));
190 assert!(email.is_canonical_supported());
191 let other = Email::new("a@example.com").unwrap();
192 assert_eq!((other.canonical_domain(), other.is_canonical_supported()), (None, false));
193 }
194}