Skip to main content

utopia_validators/
text.rs

1//! The text leaf validators: `Text`, `Identifier`, `WhiteList`, `Contains` and `Label`.
2//!
3//! The parts that compare a value with the PHP values a validator holds (`in_array()`
4//! over an allow list or a white list, `(string)` of a pattern) stay with the PHP engine, in
5//! the extension; what is left here works on bytes, as the PHP methods do once they have a
6//! string.
7
8use php_std::{mb, pcre};
9
10use crate::decimal;
11
12/// `preg_match('/[^\p{Z}\p{Cf}\s]/u', $value) !== 1`: the value holds only Unicode separators,
13/// format characters and whitespace (nothing at all included), or is not UTF-8, which
14/// `preg_match()` refuses.
15///
16/// PHP: `Text::isValid()` with `$requireNonBlank`.
17pub fn is_blank(value: &[u8]) -> bool {
18    !matches!(
19        pcre::preg_match_bare(br"/[^\p{Z}\p{Cf}\s]/u", value),
20        Ok(result) if result.value == pcre::Value::Int(1)
21    )
22}
23
24/// PHP `mb_strlen($value)`: each sequence that is not UTF-8 counts as one character.
25pub fn chars(value: &[u8]) -> i64 {
26    i64::try_from(mb::mb_strlen(value)).unwrap_or(i64::MAX)
27}
28
29/// `mb_strlen($value) >= $min` and, for a `$length` other than 0, `mb_strlen($value) <= $length`.
30///
31/// PHP: `Text::isValid()`'s length checks.
32pub fn text_length(value: &[u8], min: i64, length: i64) -> bool {
33    let chars = chars(value);
34    chars >= min && !(chars > length && length != 0)
35}
36
37/// `Text::getDescription()`, given `implode(', ', $this->allowList)` when the list is not
38/// empty.
39///
40/// Appended to `message`.
41pub fn text_description(
42    length: i64,
43    min: i64,
44    allow_list: Option<&[u8]>,
45    require_non_blank: bool,
46    message: &mut Vec<u8>,
47) {
48    message.extend_from_slice(b"Value must be a valid string");
49    if min == length {
50        message.extend_from_slice(b" and exactly ");
51        decimal(length, message);
52        message.extend_from_slice(b" chars");
53    } else {
54        if min != 0 {
55            message.extend_from_slice(b" and at least ");
56            decimal(min, message);
57            message.extend_from_slice(b" chars");
58        }
59        if length != 0 {
60            message.extend_from_slice(b" and no longer than ");
61            decimal(length, message);
62            message.extend_from_slice(b" chars");
63        }
64    }
65    if let Some(list) = allow_list {
66        message.extend_from_slice(b" and only consist of '");
67        message.extend_from_slice(list);
68        message.extend_from_slice(b"' chars");
69    }
70    if require_non_blank {
71        message.extend_from_slice(b" and not be blank");
72    }
73}
74
75/// `preg_match('/^[A-Za-z_]\w*$/D', $value) === 1`: an ASCII letter or `_`, then ASCII letters,
76/// digits and `_` (the pattern has no `/u`, so `\w` is ASCII), up to the very end.
77///
78/// PHP: `Identifier::isValid()` after `Text::isValid()`.
79pub fn identifier(value: &[u8]) -> bool {
80    match value.split_first() {
81        Some((first, rest)) => {
82            (first.is_ascii_alphabetic() || *first == b'_')
83                && rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_')
84        }
85        None => false,
86    }
87}
88
89/// `Identifier::getDescription()`, appended to `description`.
90pub fn identifier_description(length: i64, description: &mut Vec<u8>) {
91    description
92        .extend_from_slice(b"Value must contain only letters, digits and underscores and must not start with a digit");
93    if length != 0 {
94        description.extend_from_slice(b", and be at most ");
95        decimal(length, description);
96        description.extend_from_slice(b" chars");
97    }
98    description.push(b'.');
99}
100
101/// PHP `strtolower()`: ASCII only, whatever the locale (PHP 8.2 and later).
102pub fn ascii_lower(value: &[u8]) -> Vec<u8> {
103    value.to_ascii_lowercase()
104}
105
106/// What `WhiteList::getDescription()` puts around `implode(', ', $this->list)`.
107pub const WHITE_LIST_DESCRIPTION: (&str, &str) = ("Value must be one of (", ")");
108
109/// `WhiteList::getDescription()`, given `implode(', ', $this->list)`, appended to `message`.
110pub fn white_list_description(list: &[u8], message: &mut Vec<u8>) {
111    message.extend_from_slice(WHITE_LIST_DESCRIPTION.0.as_bytes());
112    message.extend_from_slice(list);
113    message.extend_from_slice(WHITE_LIST_DESCRIPTION.1.as_bytes());
114}
115
116/// PHP `mb_strtolower($value, 'UTF-8')`: full lower case, the final sigma rule, and `?` for
117/// each sequence that is not UTF-8.
118///
119/// PHP: `Contains::isValid()` when it is not strict.
120pub fn lower(value: &[u8]) -> Vec<u8> {
121    mb::mb_strtolower(value)
122}
123
124/// PHP `str_contains($haystack, $needle)`: an empty needle is in every haystack.
125pub fn contains(haystack: &[u8], needle: &[u8]) -> bool {
126    needle.is_empty() || haystack.windows(needle.len()).any(|window| window == needle)
127}
128
129/// `Contains::getDescription()`, given `implode(', ', $this->patterns)`, appended to `message`.
130pub fn contains_description(patterns: &[u8], strict: bool, message: &mut Vec<u8>) {
131    message.extend_from_slice(b"Value must contain one of (");
132    message.extend_from_slice(patterns);
133    message.push(b')');
134    message.extend_from_slice(if strict { b" (case-sensitive)" } else { b" (case-insensitive)" });
135}
136
137/// `Label::MAX_LENGTH`: the longest DNS label.
138pub const LABEL_MAX_LENGTH: i64 = 63;
139
140/// `Label::isValid()` on a string: 1 to 63 bytes of lowercase ASCII letters, digits and
141/// hyphens, not starting or ending with a hyphen. (`ctype_alnum()` of what is left without the
142/// hyphens, so a label of hyphens only is refused.)
143pub fn label(value: &[u8]) -> bool {
144    if value.is_empty() || value.len() > LABEL_MAX_LENGTH as usize || value.starts_with(b"-") || value.ends_with(b"-") {
145        return false;
146    }
147    let rest: Vec<u8> = value.iter().copied().filter(|b| *b != b'-').collect();
148    !rest.is_empty() && rest.iter().all(u8::is_ascii_alphanumeric) && !value.iter().any(u8::is_ascii_uppercase)
149}
150
151/// `Label::getDescription()`: `Label::MAX_LENGTH` is [`LABEL_MAX_LENGTH`].
152pub const LABEL_DESCRIPTION: &str =
153    "Value must be 1 to 63 lowercase letters, digits and hyphens, and must not start or end with a hyphen.";
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn blank() {
161        assert!(is_blank(b""));
162        assert!(is_blank(b" \t\n\r\x0b\x0c"));
163        assert!(is_blank("\u{00a0}\u{2028}\u{200b}\u{feff}".as_bytes()));
164        assert!(!is_blank(b" a "));
165        // Not UTF-8: `preg_match()` fails, so the value is refused as blank.
166        assert!(is_blank(b"a\xff"));
167    }
168
169    #[test]
170    fn lengths() {
171        assert!(text_length("héllo".as_bytes(), 5, 5));
172        assert!(!text_length("héllo".as_bytes(), 6, 0));
173        assert!(text_length(b"", 0, 0));
174        assert!(!text_length(b"abc", 1, 2));
175        assert!(text_length(b"abc", 1, 0));
176    }
177
178    #[test]
179    fn descriptions() {
180        fn described(describe: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
181            let mut out = Vec::new();
182            describe(&mut out);
183            out
184        }
185        assert_eq!(
186            described(|out| text_description(10, 10, None, false, out)),
187            b"Value must be a valid string and exactly 10 chars"
188        );
189        assert_eq!(
190            described(|out| text_description(10, 1, Some(b"a, b"), true, out)),
191            b"Value must be a valid string and at least 1 chars and no longer than 10 chars and only consist of 'a, b' chars and not be blank"
192        );
193        assert_eq!(
194            described(|out| text_description(0, 0, None, false, out)),
195            b"Value must be a valid string and exactly 0 chars"
196        );
197        assert_eq!(
198            described(|out| text_description(-5, 2, None, false, out)),
199            b"Value must be a valid string and at least 2 chars and no longer than -5 chars"
200        );
201        assert_eq!(
202            described(|out| identifier_description(0, out)),
203            b"Value must contain only letters, digits and underscores and must not start with a digit."
204        );
205        assert_eq!(
206            described(|out| identifier_description(64, out)),
207            b"Value must contain only letters, digits and underscores and must not start with a digit, and be at most 64 chars."
208        );
209        assert_eq!(
210            described(|out| contains_description(b"a, b", false, out)),
211            b"Value must contain one of (a, b) (case-insensitive)"
212        );
213        assert_eq!(described(|out| white_list_description(b"a, b", out)), b"Value must be one of (a, b)");
214        assert_eq!(
215            LABEL_DESCRIPTION,
216            format!(
217                "Value must be 1 to {LABEL_MAX_LENGTH} lowercase letters, digits and hyphens, and must not start or end with a hyphen."
218            )
219        );
220    }
221
222    #[test]
223    fn identifiers() {
224        assert!(identifier(b"_a1"));
225        assert!(identifier(b"A"));
226        assert!(!identifier(b"1a"));
227        assert!(!identifier(b"a-b"));
228        assert!(!identifier(b"a\n"));
229        assert!(!identifier("é".as_bytes()));
230        assert!(!identifier(b""));
231    }
232
233    #[test]
234    fn labels() {
235        assert!(label(b"a-1"));
236        assert!(!label(b"A"));
237        assert!(!label(b"-a"));
238        assert!(!label(b"a-"));
239        assert!(!label(b"a.b"));
240        assert!(!label(&[b'a'; 64]));
241        assert!(label(&[b'a'; 63]));
242        assert!(!label(b""));
243    }
244
245    #[test]
246    fn contains_needles() {
247        assert!(contains(b"abc", b""));
248        assert!(contains(b"abc", b"bc"));
249        assert!(!contains(b"", b"a"));
250        assert_eq!(lower("ÀB\u{03a3}".as_bytes()), "àbς".as_bytes());
251    }
252}