utopia_validators/lib.rs
1//! The checks of `utopia-php/validators` (`packages/validators`), as PHP runs them.
2//!
3//! Each function is the body of a PHP validator's method over a value as PHP sees it
4//! ([`Input`]): the same coercions (`is_numeric()`, `$value + 0`), the same comparisons and
5//! the same messages. The validator classes themselves, and the state their constructors
6//! keep, live in the PHP extension (`crates/extension`), which passes that state in.
7//!
8//! | PHP | Rust |
9//! |---|---|
10//! | `Boolean::isValid()` | [`boolean`] |
11//! | `Integer::isValid()`, `getDescription()`, `getFormat()` | [`Integer`] |
12//! | `FloatValidator::isValid()` | [`float`] |
13//! | `Numeric::isValid()` | [`numeric`] |
14//! | `Range::isValid()`, `getDescription()` | [`range`], [`range_description`] |
15//! | `Port::isValid()` | [`port`] |
16//! | `HexColor::isValid()` | [`hex_color`] |
17//! | `Text::isValid()`, `getDescription()` | [`is_blank`], [`text_length`], [`text_description`] |
18//! | `Identifier::isValid()`, `getDescription()` | [`identifier`], [`identifier_description`] |
19//! | `WhiteList::__construct()`, `getDescription()` | [`ascii_lower`], [`white_list_description`] |
20//! | `Contains::isValid()`, `getDescription()` | [`lower`], [`contains`], [`contains_description`] |
21//! | `Label::isValid()`, `getDescription()` | [`label`], [`LABEL_DESCRIPTION`] |
22//! | `Hostname::isValid()` | [`hostname`], [`hostname_allowed`] |
23//! | `Domain::isValid()` | [`domain`], [`explode_count`] |
24//! | `IP::isValid()` | [`ip`] |
25//! | `URL::isValid()`, `getDescription()`, `isPrivateUseSchemeURI()` | [`url_ascii`], [`url`], [`url_component`], [`private_use_scheme`], [`url_description`] |
26//! | `Host::getDescription()` | [`host_description`] |
27//! | `Phone::isValid()`, `normalize()` | [`phone`], [`phone_normalize`] |
28//! | `ArrayList::getDescription()` | [`array_list_description`] |
29//! | `JSON\ArrayValidator`, `JSON\ObjectValidator`: `getDescription()`, `hasValidLength()` | [`json_array_description`], [`json_object_description`], [`json_length`] |
30//! | `JSON\FCM::isValid()` | [`FCM_REQUIRED`], [`FCM_OPTIONAL`], [`FCM_URL`], [`non_empty`], [`pem_private_key`], [`https_scheme`] |
31//! | `Globstar::matchGlobstar()` | [`globstar_regex`], [`exclusion`], [`wildcard`] |
32//!
33//! The composing validators (`Nullable`, `ArrayList`, `AllOf`, `AnyOf`, `NoneOf`, `Multiple`)
34//! mostly ask the validators they wrap, which the extension does through the engine, as do the
35//! PHP functions whose state is observable (`json_decode()`, `json_encode()`, `preg_match()`,
36//! `filter_var()`).
37//!
38//! Comparing a value with the PHP values a validator holds (the loose `in_array()` of `Text`'s
39//! allow list and of `WhiteList`, `(string)` of a pattern, `Domain`'s restrictions) is left to
40//! the PHP engine.
41
42mod compose;
43mod network;
44mod scalar;
45mod text;
46
47pub use compose::{
48 ASSOC_DESCRIPTION, FCM_DESCRIPTION, FCM_EMAIL_ERROR, FCM_KEY_ERROR, FCM_OPTIONAL, FCM_REQUIRED, FCM_TYPE_ERROR,
49 FCM_URL, GLOBSTAR_DESCRIPTION, JSON_DESCRIPTION, PEM_BEGIN, PEM_END, array_list_description, exclusion,
50 fcm_optional_error, fcm_required_error, fcm_url_error, globstar_regex, https_scheme, json_array_description,
51 json_length, json_object_description, non_empty, pem_private_key, preg_quote, trim, wildcard,
52};
53pub use network::{
54 DOMAIN_DESCRIPTION, HOST_DESCRIPTION_PREFIX, HOSTNAME_DESCRIPTION, IP_DESCRIPTION, IpType, LOOPBACK_HOSTS,
55 PHONE_DESCRIPTION, domain, explode_count, host_description, hostname, hostname_allowed, ip, ip_str, phone,
56 phone_normalize, private_use_scheme, url, url_ascii, url_component, url_description, url_str,
57};
58pub use php_std::filter::Value as FilterValue;
59pub use php_std::url::Component as UrlComponent;
60pub use php_std::value::Number;
61pub use scalar::{
62 Integer, IntegerError, boolean, float, hex_color, number_le, numeric, port, port_host, port_number, range,
63 range_description, range_number,
64};
65pub use text::{
66 LABEL_DESCRIPTION, LABEL_MAX_LENGTH, WHITE_LIST_DESCRIPTION, ascii_lower, chars, contains, contains_description,
67 identifier, identifier_description, is_blank, label, lower, text_description, text_length, white_list_description,
68};
69
70/// `$int` as PHP interpolates it into a string, appended to `out` without going through
71/// `format!`: what every description that names a length or a size does.
72pub(crate) fn decimal(int: i64, out: &mut Vec<u8>) {
73 if int < 0 {
74 out.push(b'-');
75 }
76 let mut digits = [0u8; 20];
77 let mut n = int.unsigned_abs();
78 let mut start = digits.len();
79 loop {
80 start -= 1;
81 digits[start] = b'0' + (n % 10) as u8;
82 n /= 10;
83 if n == 0 {
84 break;
85 }
86 }
87 out.extend_from_slice(&digits[start..]);
88}
89
90/// A PHP value as the validators look at it: scalars by value, strings as bytes, and
91/// everything else (arrays, objects, resources) as [`Input::Other`], which no check here
92/// accepts as a number or a string.
93#[derive(Debug, Clone, Copy, PartialEq)]
94pub enum Input<'a> {
95 /// `null`.
96 Null,
97 /// A `bool`.
98 Bool(bool),
99 /// An `int`.
100 Int(i64),
101 /// A `float`.
102 Float(f64),
103 /// A `string`, as bytes.
104 Str(&'a [u8]),
105 /// An array, an object or a resource.
106 Other,
107}
108
109impl Input<'_> {
110 /// PHP `is_numeric($value) ? $value + 0 : null`: ints and floats as they are, numeric
111 /// strings (leading and trailing whitespace allowed, no hex) parsed as the engine
112 /// parses them, an integer that overflows becoming a float.
113 pub fn numeric(self) -> Option<Number> {
114 match self {
115 Input::Int(i) => Some(Number::Int(i)),
116 Input::Float(f) => Some(Number::Float(f)),
117 Input::Str(s) => php_std::value::numeric_bytes_ex(s).map(|(n, _)| n),
118 Input::Null | Input::Bool(_) | Input::Other => None,
119 }
120 }
121}