Skip to main content

php_std/
value.rs

1//! PHP value semantics (type juggling) on top of `serde_json::Value`.
2//!
3//! Request parameters reach PHP code as PHP values. These functions answer
4//! the questions libraries ask about them (`is_numeric`, truthiness, string
5//! casts, `==`) the way the engine does.
6
7use std::cmp::Ordering;
8
9use serde_json::{Map, Value};
10
11use crate::number;
12
13/// An empty JSON object: a `stdClass` instance in PHP.
14pub fn is_object(value: &Value) -> bool {
15    matches!(value, Value::Object(map) if map.is_empty())
16}
17
18/// Number of elements of a PHP array value.
19pub fn array_len(value: &Value) -> usize {
20    match value {
21        Value::Array(a) => a.len(),
22        Value::Object(o) => o.len(),
23        _ => 0,
24    }
25}
26
27/// Iterates the elements of a PHP array value (list or map) in order.
28pub fn array_values(value: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
29    match value {
30        Value::Array(a) => Box::new(a.iter()),
31        Value::Object(o) => Box::new(o.values()),
32        _ => Box::new(std::iter::empty()),
33    }
34}
35
36/// A PHP number after `$value + 0`.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub enum Number {
39    /// An integer.
40    Int(i64),
41    /// A float.
42    Float(f64),
43}
44
45impl Number {
46    /// The number as a float.
47    pub fn as_f64(self) -> f64 {
48        match self {
49            Number::Int(i) => i as f64,
50            Number::Float(f) => f,
51        }
52    }
53}
54
55/// A JSON number as PHP sees it: integers beyond `i64` are floats.
56pub fn json_number(n: &serde_json::Number) -> Number {
57    match n.as_i64() {
58        Some(i) => Number::Int(i),
59        None => Number::Float(n.as_f64().unwrap_or(0.0)),
60    }
61}
62
63/// PHP `is_numeric($v) ? $v + 0 : null`.
64pub fn numeric(value: &Value) -> Option<Number> {
65    match value {
66        Value::Number(n) => Some(json_number(n)),
67        Value::String(s) => numeric_str(s),
68        _ => None,
69    }
70}
71
72/// PHP numeric-string parsing (`is_numeric` + `+ 0`).
73pub fn numeric_str(s: &str) -> Option<Number> {
74    numeric_str_ex(s).map(|(n, _)| n)
75}
76
77/// Like [`numeric_str`], also reporting integer overflow as the engine's
78/// `is_numeric_string_ex` does: `1` or `-1` when an integer-looking string
79/// did not fit in `i64` and became a float.
80///
81/// Leading and trailing whitespace (space, `\t`, `\n`, `\r`, `\v`, `\f`) is
82/// allowed; the body is an optional sign and a decimal integer or float with
83/// an optional exponent. Hex, octal and binary literals are not numeric.
84pub fn numeric_str_ex(s: &str) -> Option<(Number, i8)> {
85    numeric_bytes_ex(s.as_bytes())
86}
87
88/// [`numeric_str_ex`] on bytes (a numeric string is ASCII, so bytes that
89/// are not UTF-8 are never numeric).
90pub fn numeric_bytes_ex(s: &[u8]) -> Option<(Number, i8)> {
91    let is_ws = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C);
92    let lead = s.iter().position(|c| !is_ws(c))?;
93    let trail = s.iter().rposition(|c| !is_ws(c)).map_or(0, |i| i + 1);
94    let bytes = &s[lead..trail];
95    let mut i = 0;
96    if bytes[i] == b'+' || bytes[i] == b'-' {
97        i += 1;
98    }
99    let int_start = i;
100    while i < bytes.len() && bytes[i].is_ascii_digit() {
101        i += 1;
102    }
103    let int_digits = i - int_start;
104    let mut is_float = false;
105    let mut frac_digits = 0;
106    if i < bytes.len() && bytes[i] == b'.' {
107        is_float = true;
108        i += 1;
109        let frac_start = i;
110        while i < bytes.len() && bytes[i].is_ascii_digit() {
111            i += 1;
112        }
113        frac_digits = i - frac_start;
114    }
115    if int_digits == 0 && frac_digits == 0 {
116        return None;
117    }
118    if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
119        let mut j = i + 1;
120        if j < bytes.len() && (bytes[j] == b'+' || bytes[j] == b'-') {
121            j += 1;
122        }
123        let exp_start = j;
124        while j < bytes.len() && bytes[j].is_ascii_digit() {
125            j += 1;
126        }
127        if j == exp_start {
128            return None;
129        }
130        is_float = true;
131        i = j;
132    }
133    if i != bytes.len() {
134        return None;
135    }
136    // Only signs, digits, '.' and exponents remain: ASCII.
137    let float = || std::str::from_utf8(bytes).ok().and_then(|t| t.parse::<f64>().ok());
138    if !is_float {
139        let negative = bytes[0] == b'-';
140        let parsed = bytes[int_start..].iter().try_fold(0i64, |v, d| {
141            let v = v.checked_mul(10)?;
142            let d = i64::from(d - b'0');
143            if negative { v.checked_sub(d) } else { v.checked_add(d) }
144        });
145        if let Some(v) = parsed {
146            // The engine's overflow check `strcmp`s the 19 digits up to the
147            // end of the string, trailing whitespace included: "-9223372036854775808 "
148            // compares greater than "9223372036854775808" and becomes a float.
149            let trailing_ws = trail != s.len();
150            if v == i64::MIN && trailing_ws {
151                return Some((Number::Float(v as f64), -1));
152            }
153            return Some((Number::Int(v), 0));
154        }
155        let oflow = if negative { -1 } else { 1 };
156        return float().map(|f| (Number::Float(f), oflow));
157    }
158    float().map(|f| (Number::Float(f), 0))
159}
160
161/// PHP truthiness (`(bool) $value`).
162pub fn truthy(value: &Value) -> bool {
163    match value {
164        Value::Null => false,
165        Value::Bool(b) => *b,
166        Value::Number(n) => json_number(n).as_f64() != 0.0,
167        Value::String(s) => !(s.is_empty() || s == "0"),
168        Value::Array(a) => !a.is_empty(),
169        // An empty object is a stdClass instance, which is truthy in PHP.
170        Value::Object(_) => true,
171    }
172}
173
174/// PHP `(string) $value` for scalars; `None` for arrays and objects.
175pub fn to_string(value: &Value) -> Option<String> {
176    match value {
177        Value::Null | Value::Bool(false) => Some(String::new()),
178        Value::Bool(true) => Some("1".to_owned()),
179        Value::Number(n) => Some(match json_number(n) {
180            Number::Int(i) => i.to_string(),
181            Number::Float(f) => number::to_string(f),
182        }),
183        Value::String(s) => Some(s.clone()),
184        _ => None,
185    }
186}
187
188/// PHP `empty($value)`.
189pub fn empty(value: &Value) -> bool {
190    !truthy(value)
191}
192
193/// PHP 8 loose equality (`$a == $b`).
194pub fn loose_eq(a: &Value, b: &Value) -> bool {
195    use Value::*;
196    match (a, b) {
197        (Bool(_), _) | (_, Bool(_)) => truthy(a) == truthy(b),
198        (Null, Null) => true,
199        (Null, String(s)) | (String(s), Null) => s.is_empty(),
200        (Null, other) | (other, Null) => !truthy(other),
201        (Number(x), Number(y)) => num_eq(json_number(x), json_number(y)),
202        (Number(n), String(s)) | (String(s), Number(n)) => number_eq_string(json_number(n), s),
203        (String(x), String(y)) => smart_str_eq(x, y),
204        (Object(x), Object(y)) if x.is_empty() || y.is_empty() => {
205            // stdClass == stdClass compares properties; stdClass vs array is uncomparable.
206            x.is_empty() && y.is_empty()
207        }
208        (Object(o), Array(_)) | (Array(_), Object(o)) if o.is_empty() => false,
209        (Array(_) | Object(_), Array(_) | Object(_)) => arrays_eq(a, b),
210        // A stdClass compared with a number is cast to 1 (with a notice).
211        (Object(o), Number(n)) | (Number(n), Object(o)) if o.is_empty() => {
212            num_eq(crate::value::Number::Int(1), json_number(n))
213        }
214        // Arrays are greater than any scalar; objects are uncomparable with strings.
215        _ => false,
216    }
217}
218
219fn num_eq(x: Number, y: Number) -> bool {
220    match (x, y) {
221        (Number::Int(p), Number::Int(q)) => p == q,
222        _ => x.as_f64() == y.as_f64(),
223    }
224}
225
226/// `compare_longs_to_string` / `compare_doubles_to_string`.
227fn number_eq_string(n: Number, s: &str) -> bool {
228    match numeric_str(s) {
229        Some(m) => num_eq(n, m),
230        None => {
231            let as_string = match n {
232                Number::Int(i) => i.to_string(),
233                Number::Float(f) => number::to_string(f),
234            };
235            as_string == s
236        }
237    }
238}
239
240/// `zendi_smart_str_equals`.
241fn smart_str_eq(a: &str, b: &str) -> bool {
242    let (Some((x, ox)), Some((y, oy))) = (numeric_str_ex(a), numeric_str_ex(b)) else {
243        return a == b;
244    };
245    if ox != 0 && ox == oy && x.as_f64() - y.as_f64() == 0.0 {
246        // Both integers overflowed to the same side: a float comparison would be lossy.
247        return a == b;
248    }
249    match (x, y) {
250        (Number::Int(p), Number::Int(q)) => p == q,
251        (Number::Int(_), Number::Float(_)) if oy != 0 => false,
252        (Number::Float(_), Number::Int(_)) if ox != 0 => false,
253        (Number::Float(p), Number::Float(q)) if p == q && !p.is_finite() => a == b,
254        _ => x.as_f64() == y.as_f64(),
255    }
256}
257
258/// The PHP array key a JSON object key or list index becomes.
259fn entries(v: &Value) -> Vec<(String, &Value)> {
260    match v {
261        Value::Array(a) => a.iter().enumerate().map(|(i, v)| (i.to_string(), v)).collect(),
262        Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), v)).collect(),
263        _ => Vec::new(),
264    }
265}
266
267/// `zend_compare_arrays`: same size, and every key of `a` is in `b` with a loosely equal value.
268fn arrays_eq(a: &Value, b: &Value) -> bool {
269    let (ea, eb) = (entries(a), entries(b));
270    if ea.len() != eb.len() {
271        return false;
272    }
273    let mb: Map<String, Value> = eb.iter().map(|(k, v)| (k.clone(), (*v).clone())).collect();
274    ea.iter().all(|(k, v)| mb.get(k).is_some_and(|w| loose_eq(v, w)))
275}
276
277/// PHP 8 `<=>` for two numbers.
278pub fn compare_numbers(x: Number, y: Number) -> Ordering {
279    match (x, y) {
280        (Number::Int(p), Number::Int(q)) => p.cmp(&q),
281        _ => x.as_f64().partial_cmp(&y.as_f64()).unwrap_or(Ordering::Equal),
282    }
283}
284
285/// PHP `$a == $b` for two strings (`zendi_smart_str_equals`): two numeric
286/// strings compare as numbers, anything else byte for byte. Numeric strings
287/// are ASCII, so a string that is not UTF-8 only equals itself.
288pub fn loose_str_eq(a: &[u8], b: &[u8]) -> bool {
289    match (std::str::from_utf8(a), std::str::from_utf8(b)) {
290        (Ok(x), Ok(y)) => smart_str_eq(x, y),
291        _ => a == b,
292    }
293}
294
295/// PHP 8 `$a <= $b` for two numbers (`zend_is_smaller_or_equal`): integers
296/// compare exactly; otherwise both are floats, `ZEND_THREEWAY_COMPARE` is
297/// not below zero for `NAN`, so any comparison with `NAN` is false.
298pub fn le_numbers(a: Number, b: Number) -> bool {
299    match (a, b) {
300        (Number::Int(p), Number::Int(q)) => p <= q,
301        // `ZEND_THREEWAY_COMPARE(x, y) <= 0` is `x <= y`, false for NAN.
302        _ => a.as_f64() <= b.as_f64(),
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use serde_json::json;
310
311    #[test]
312    fn numeric_strings() {
313        assert_eq!(numeric_str("8"), Some(Number::Int(8)));
314        assert_eq!(numeric_str(" 8"), Some(Number::Int(8)));
315        assert_eq!(numeric_str("8 "), Some(Number::Int(8)));
316        assert_eq!(numeric_str("-1.5"), Some(Number::Float(-1.5)));
317        assert_eq!(numeric_str(".5"), Some(Number::Float(0.5)));
318        assert_eq!(numeric_str("1e3"), Some(Number::Float(1000.0)));
319        assert_eq!(numeric_str("abc"), None);
320        assert_eq!(numeric_str("0x1A"), None);
321        assert_eq!(numeric_str(""), None);
322        assert_eq!(numeric_str("."), None);
323    }
324
325    #[test]
326    fn truthiness() {
327        assert!(truthy(&json!("false")));
328        assert!(!truthy(&json!("0")));
329        assert!(!truthy(&json!("")));
330        assert!(truthy(&json!({})));
331        assert!(!truthy(&json!([])));
332    }
333
334    #[test]
335    fn loose_equality_matches_php() {
336        assert!(!loose_eq(&json!(1.5), &json!("1.5abc")));
337        assert!(!loose_eq(&json!(0.30000000000000004), &json!("0.3")));
338        assert!(!loose_eq(&json!("abc"), &json!(0)));
339        assert!(!loose_eq(&json!(null), &json!("0")));
340        assert!(loose_eq(&json!("1e3"), &json!("1000")));
341        assert!(!loose_eq(&json!("9223372036854775808"), &json!("9223372036854775809")));
342        assert!(loose_eq(&json!([]), &json!(false)));
343        assert!(!loose_eq(&json!({}), &json!([])));
344        assert!(loose_eq(&json!({}), &json!(1)));
345        assert!(loose_eq(&json!({"0": 1}), &json!([1])));
346    }
347
348    #[test]
349    fn strings_of_floats() {
350        assert_eq!(to_string(&json!(1.0)).unwrap(), "1");
351        assert_eq!(to_string(&json!(1e25)).unwrap(), "1.0E+25");
352    }
353}