Skip to main content

utopia_emails/
email.rs

1//! An address split at its `@`, and what can be asked of it without its
2//! domain's public suffix.
3//!
4//! PHP: `Utopia\Emails\Email`.
5
6use php_std::filter::{self, FILTER_VALIDATE_EMAIL, Options};
7use php_std::{mb, string};
8
9use crate::Error;
10use crate::canonicals::{Canonical, PROVIDERS, Provider};
11
12/// The most characters allowed before the `@`.
13///
14/// PHP: `Email::LOCAL_MAX_LENGTH`.
15pub const LOCAL_MAX_LENGTH: usize = 64;
16
17/// The most characters allowed after the `@`.
18///
19/// PHP: `Email::DOMAIN_MAX_LENGTH`.
20pub const DOMAIN_MAX_LENGTH: usize = 253;
21
22/// Whether the email filter accepts `value`.
23///
24/// PHP: `filter_var($value, FILTER_VALIDATE_EMAIL) !== false`.
25fn 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
32/// PHP `empty()` of a string.
33fn empty(s: &[u8]) -> bool {
34    s.is_empty() || s == b"0"
35}
36
37/// An address: trimmed, lower-cased (`mb_strtolower`) and split at its
38/// single `@`. It can hold any bytes, as a PHP string does.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Email {
41    email: Vec<u8>,
42    /// Byte offset of the `@`.
43    at: usize,
44}
45
46impl Email {
47    /// Parses an address.
48    ///
49    /// # Errors
50    ///
51    /// [`Error::Parse`] for an empty address (or `"0"`), or one without
52    /// exactly one `@` and something (not `"0"`) on both sides of it.
53    ///
54    /// PHP: `new Email($email)`, up to `new Domain()` of its domain.
55    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    /// The whole address.
73    ///
74    /// PHP: `get()`.
75    pub fn get(&self) -> &[u8] {
76        &self.email
77    }
78
79    /// The part before the `@`.
80    ///
81    /// PHP: `getLocal()`.
82    pub fn local(&self) -> &[u8] {
83        &self.email[..self.at]
84    }
85
86    /// The part after the `@`.
87    ///
88    /// PHP: `getDomain()`.
89    pub fn domain(&self) -> &[u8] {
90        &self.email[self.at + 1..]
91    }
92
93    /// Whether PHP's email filter accepts the address.
94    ///
95    /// PHP: `isValid()`.
96    pub fn is_valid(&self) -> bool {
97        filtered(&self.email)
98    }
99
100    /// Whether the local part has at most [`LOCAL_MAX_LENGTH`] characters,
101    /// all of `[a-zA-Z0-9._+-]`, no `..`, and no dot at either end.
102    ///
103    /// PHP: `hasValidLocal()`.
104    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        // `/^[a-zA-Z0-9._+-]+$/`: without `/D`, `$` also matches before one final newline.
110        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    /// Whether the domain has at most [`DOMAIN_MAX_LENGTH`] characters and
117    /// PHP's email filter accepts it after `test@`. `hasValidDomain()` then
118    /// also asks that the domain be known or a test domain.
119    ///
120    /// PHP: `hasValidDomain()`, up to `$this->domainInstance->isKnown()`.
121    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    /// The address with the aliases of its provider removed.
127    ///
128    /// # Errors
129    ///
130    /// [`Error::EmptyLocal`] (see [`Provider::canonical`]).
131    ///
132    /// PHP: `getCanonical()`.
133    pub fn canonical(&self) -> Result<Canonical, Error> {
134        Provider::of(self.domain()).canonical(self.local(), self.domain())
135    }
136
137    /// Whether one of [`PROVIDERS`] has the domain.
138    ///
139    /// PHP: `isCanonicalSupported()`.
140    pub fn is_canonical_supported(&self) -> bool {
141        PROVIDERS.iter().any(|provider| provider.supports(self.domain()))
142    }
143
144    /// The canonical domain of the provider of [`PROVIDERS`] that has the
145    /// domain, if one does.
146    ///
147    /// PHP: `getCanonicalDomain()`.
148    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}