fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! Query strings read and written the way PHP does, so both packages agree on which parameters a
//! request has and build the same links: `fields[orders]=a,b` and `filter[total][gte]=1` nest,
//! as PHP's `parse_str` nests them, and links are encoded as Laravel's `Arr::query` encodes them.

use serde_json::{Map, Value};

/// The query string's parameters, nested on `[...]` as PHP nests them. Leaves are strings.
pub fn parse(query: &str) -> Map<String, Value> {
    let mut parameters = Map::new();
    for pair in query.split('&').filter(|pair| !pair.is_empty()) {
        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
        let key = decode(key);
        let value = decode(value);
        let (name, mut rest) = match key.find('[') {
            Some(index) if index > 0 => (&key[..index], &key[index..]),
            _ => (key.as_str(), ""),
        };
        // PHP turns dots and spaces in the top-level name into underscores.
        let name = name.replace(['.', ' '], "_");
        let mut path = vec![name];
        while let Some(stripped) = rest.strip_prefix('[') {
            let Some(end) = stripped.find(']') else { break };
            path.push(stripped[..end].to_owned());
            rest = &stripped[end + 1..];
        }
        insert(&mut parameters, &path, Value::String(value));
    }
    parameters
}

fn insert(map: &mut Map<String, Value>, path: &[String], value: Value) {
    let Some((first, rest)) = path.split_first() else {
        return;
    };
    let key = if first.is_empty() {
        // `a[]=1`: PHP appends with the next numeric key.
        let next = map
            .keys()
            .filter_map(|key| key.parse::<usize>().ok())
            .max()
            .map_or(0, |max| max + 1);
        next.to_string()
    } else {
        first.clone()
    };
    if rest.is_empty() {
        map.insert(key, value);
        return;
    }
    let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
    if !entry.is_object() {
        *entry = Value::Object(Map::new());
    }
    if let Value::Object(child) = entry {
        insert(child, rest, value);
    }
}

/// Builds a query string from nested parameters, as Laravel's `Arr::query` does: brackets for
/// nesting and RFC 3986 percent-encoding.
pub fn build(parameters: &Map<String, Value>) -> String {
    let mut pairs = Vec::new();
    for (key, value) in parameters {
        flatten(&encode(key), value, &mut pairs);
    }
    pairs.join("&")
}

fn flatten(prefix: &str, value: &Value, pairs: &mut Vec<String>) {
    match value {
        Value::Object(map) => {
            for (key, value) in map {
                flatten(&format!("{prefix}%5B{}%5D", encode(key)), value, pairs);
            }
        }
        Value::Array(items) => {
            for (index, value) in items.iter().enumerate() {
                flatten(&format!("{prefix}%5B{index}%5D"), value, pairs);
            }
        }
        Value::Null => {}
        Value::String(text) => pairs.push(format!("{prefix}={}", encode(text))),
        Value::Bool(flag) => pairs.push(format!("{prefix}={}", u8::from(*flag))),
        Value::Number(number) => pairs.push(format!("{prefix}={number}")),
    }
}

/// Percent-encodes everything but RFC 3986's unreserved characters.
pub fn encode(text: &str) -> String {
    let mut encoded = String::with_capacity(text.len());
    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
            encoded.push(char::from(byte));
        } else {
            encoded.push_str(&format!("%{byte:02X}"));
        }
    }
    encoded
}

/// Decodes `%XX` escapes and `+` as a space, as PHP's `urldecode` does.
pub fn decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'+' => decoded.push(b' '),
            b'%' if index + 2 < bytes.len()
                && bytes[index + 1].is_ascii_hexdigit()
                && bytes[index + 2].is_ascii_hexdigit() =>
            {
                let hex = |byte: u8| char::from(byte).to_digit(16).unwrap_or_default() as u8;
                decoded.push(hex(bytes[index + 1]) * 16 + hex(bytes[index + 2]));
                index += 2;
            }
            byte => decoded.push(byte),
        }
        index += 1;
    }
    String::from_utf8_lossy(&decoded).into_owned()
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn nests_brackets_as_php_does() {
        let parsed = parse(
            "include=customer&fields%5Borders%5D=a,b&filter[total][gte]=10&page[size]=2&a.b=1",
        );
        assert_eq!(
            Value::Object(parsed),
            json!({
                "include": "customer",
                "fields": { "orders": "a,b" },
                "filter": { "total": { "gte": "10" } },
                "page": { "size": "2" },
                "a_b": "1",
            })
        );
    }

    #[test]
    fn later_values_win_and_plus_is_a_space() {
        let parsed = parse("sort=a&sort=b+c&x=%E2%9C%93");
        assert_eq!(parsed["sort"], json!("b c"));
        assert_eq!(parsed["x"], json!("✓"));
    }

    #[test]
    fn builds_links_as_laravel_does() {
        let parameters = parse("sort=-created_at&fields[orders]=a,b");
        let mut parameters = parameters;
        parameters.insert("page".into(), json!({ "size": 2, "after": "eyJ" }));
        assert_eq!(
            build(&parameters),
            "sort=-created_at&fields%5Borders%5D=a%2Cb&page%5Bsize%5D=2&page%5Bafter%5D=eyJ"
        );
    }

    #[test]
    fn a_truncated_escape_is_kept() {
        assert_eq!(decode("50%"), "50%");
        assert_eq!(decode("%4"), "%4");
    }
}