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//! A Rust caller that wants the value back in its type, not a `bool`, uses a [`Validator`]:
39//! [`Boolean`], [`Integer`], [`Float`], [`Range`], [`Port`], [`Text`], [`Hostname`] and
40//! [`WhiteList`], which run the same checks.
41//!
42//! Comparing a value with the PHP values a validator holds (the loose `in_array()` of `Text`'s
43//! allow list and of `WhiteList`, `(string)` of a pattern, `Domain`'s restrictions) is left to
44//! the PHP engine.
45
46mod compose;
47mod network;
48#[cfg(feature = "object")]
49pub mod object;
50mod scalar;
51mod text;
52mod validator;
53
54pub use compose::{
55 ASSOC_DESCRIPTION, FCM_DESCRIPTION, FCM_EMAIL_ERROR, FCM_KEY_ERROR, FCM_OPTIONAL, FCM_REQUIRED, FCM_TYPE_ERROR,
56 FCM_URL, GLOBSTAR_DESCRIPTION, JSON_DESCRIPTION, PEM_BEGIN, PEM_END, array_list_description, exclusion,
57 fcm_optional_error, fcm_required_error, fcm_url_error, globstar_regex, https_scheme, json_array_description,
58 json_length, json_object_description, non_empty, pem_private_key, preg_quote, trim, wildcard,
59};
60pub use network::{
61 DOMAIN_DESCRIPTION, HOST_DESCRIPTION_PREFIX, HOSTNAME_DESCRIPTION, IP_DESCRIPTION, IpType, LOOPBACK_HOSTS,
62 PHONE_DESCRIPTION, domain, explode_count, host_description, hostname, hostname_allowed, ip, ip_str, phone,
63 phone_normalize, private_use_scheme, url, url_ascii, url_component, url_description, url_str,
64};
65pub use php_std::filter::Value as FilterValue;
66pub use php_std::url::Component as UrlComponent;
67pub use php_std::value::Number;
68pub use scalar::{
69 Integer, IntegerError, boolean, float, hex_color, number_le, numeric, port, port_host, port_number, range,
70 range_description, range_number,
71};
72pub use text::{
73 LABEL_DESCRIPTION, LABEL_MAX_LENGTH, WHITE_LIST_DESCRIPTION, ascii_lower, chars, contains, contains_description,
74 identifier, identifier_description, is_blank, label, lower, text_description, text_length, white_list_description,
75};
76
77pub use validator::{Boolean, Float, Hostname, Port, Range, Text, Validator, WhiteList};
78
79/// `$int` as PHP interpolates it into a string, appended to `out` without going through
80/// `format!`: what every description that names a length or a size does.
81pub(crate) fn decimal(int: i64, out: &mut Vec<u8>) {
82 if int < 0 {
83 out.push(b'-');
84 }
85 let mut digits = [0u8; 20];
86 let mut n = int.unsigned_abs();
87 let mut start = digits.len();
88 loop {
89 start -= 1;
90 digits[start] = b'0' + (n % 10) as u8;
91 n /= 10;
92 if n == 0 {
93 break;
94 }
95 }
96 out.extend_from_slice(&digits[start..]);
97}
98
99/// A PHP value as the validators look at it: scalars by value, strings as bytes, and
100/// everything else (arrays, objects, resources) as [`Input::Other`], which no check here
101/// accepts as a number or a string.
102#[derive(Debug, Clone, Copy, PartialEq)]
103pub enum Input<'a> {
104 /// `null`.
105 Null,
106 /// A `bool`.
107 Bool(bool),
108 /// An `int`.
109 Int(i64),
110 /// A `float`.
111 Float(f64),
112 /// A `string`, as bytes.
113 Str(&'a [u8]),
114 /// An array, an object or a resource.
115 Other,
116}
117
118impl Input<'_> {
119 /// PHP `is_numeric($value) ? $value + 0 : null`: ints and floats as they are, numeric
120 /// strings (leading and trailing whitespace allowed, no hex) parsed as the engine
121 /// parses them, an integer that overflows becoming a float.
122 pub fn numeric(self) -> Option<Number> {
123 match self {
124 Input::Int(i) => Some(Number::Int(i)),
125 Input::Float(f) => Some(Number::Float(f)),
126 Input::Str(s) => php_std::value::numeric_bytes_ex(s).map(|(n, _)| n),
127 Input::Null | Input::Bool(_) | Input::Other => None,
128 }
129 }
130}