laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
use laravel::validation::{Field, Rule, RuleError, Rules, ValidationError, ValidationRule};
use serde_json::{Map, Value};

use crate::error::ActionError;

/// The checks Laravel's `numeric`, `integer`, `boolean` and `array` rules make, which Laravel Rust
/// derives from the Rust type instead.
#[derive(Debug, Clone, Copy)]
enum Kind {
    Numeric,
    Integer,
    Boolean,
    Array,
}

struct TypeRule(Kind);

impl ValidationRule for TypeRule {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        let Some(value) = field.value else {
            return Ok(());
        };

        let text = value.as_str();
        let valid = match self.0 {
            Kind::Numeric => value.is_number() || text.is_some_and(|text| text.trim().parse::<f64>().is_ok()),
            Kind::Integer => {
                value.is_number() && text.is_none() && !is_fraction(value)
                    || text.is_some_and(|text| text.trim().parse::<i64>().is_ok())
            }
            Kind::Boolean => value.is_bool() || text.is_some_and(|text| matches!(text, "0" | "1" | "true" | "false")),
            Kind::Array => value.is_array() || value.is_object(),
        };

        if valid {
            return Ok(());
        }

        Err(field.reject(match self.0 {
            Kind::Numeric => "The :attribute field must be a number.",
            Kind::Integer => "The :attribute field must be an integer.",
            Kind::Boolean => "The :attribute field must be true or false.",
            Kind::Array => "The :attribute field must be an array.",
        }))
    }
}

fn is_fraction(value: &laravel::validation::InputValue) -> bool {
    match value {
        laravel::validation::InputValue::Number(number) => {
            number.is_f64() && number.as_f64().is_some_and(|n| n.fract() != 0.0)
        }
        _ => false,
    }
}

fn number(text: &str) -> Option<f64> {
    text.trim().parse().ok()
}

/// Turn one rule of a pipe-separated string, such as `max:255`, into rules.
fn rule(action: &str, field: &str, part: &str, parts: &[&str], rules: &mut Rules) -> Result<Vec<Rule>, ActionError> {
    let (name, argument) = part
        .split_once(':')
        .map_or((part, ""), |(name, argument)| (name, argument));
    let numeric = parts.iter().any(|part| matches!(*part, "numeric" | "integer"));
    let array = parts.contains(&"array");
    let unsupported = || ActionError::Rule {
        action: action.to_owned(),
        rule: part.to_owned(),
    };
    let size = |argument: &str| number(argument).ok_or_else(unsupported);

    Ok(match name {
        "required" => vec![Rule::required()],
        "filled" => vec![Rule::filled()],
        "present" => vec![Rule::present()],
        "accepted" => vec![Rule::accepted()],
        "declined" => vec![Rule::declined()],
        "string" => vec![Rule::string()],
        "email" => vec![Rule::email()],
        "url" => vec![Rule::url(["http", "https"])],
        "uuid" => vec![Rule::uuid(None::<u8>)],
        "ulid" => vec![Rule::ulid()],
        "ip" => vec![Rule::ip()],
        "ipv4" => vec![Rule::ipv4()],
        "ipv6" => vec![Rule::ipv6()],
        "json" => vec![Rule::json()],
        "alpha" => vec![Rule::alpha()],
        "alpha_num" => vec![Rule::alpha_num()],
        "alpha_dash" => vec![Rule::alpha_dash()],
        "lowercase" => vec![Rule::lowercase()],
        "uppercase" => vec![Rule::uppercase()],
        "confirmed" => vec![Rule::confirmed()],
        "same" => vec![Rule::same(argument)],
        "different" => vec![Rule::different(argument)],
        "in" => vec![Rule::one_of(argument.split(',').map(str::to_owned))],
        "not_in" => vec![Rule::not_one_of(argument.split(',').map(str::to_owned))],
        "numeric" => vec![Rule::custom(TypeRule(Kind::Numeric))],
        "integer" => vec![Rule::custom(TypeRule(Kind::Integer))],
        "boolean" => vec![Rule::custom(TypeRule(Kind::Boolean))],
        "array" => vec![Rule::custom(TypeRule(Kind::Array))],
        "nullable" => {
            *rules = std::mem::take(rules).nullable(field);
            Vec::new()
        }
        "sometimes" => {
            *rules = std::mem::take(rules).sometimes(field);
            Vec::new()
        }
        "bail" => vec![Rule::bail()],
        "min" if array => vec![Rule::min_items(size(argument)? as usize)],
        "max" if array => vec![Rule::max_items(size(argument)? as usize)],
        "min" if numeric => vec![Rule::min_value(size(argument)?)],
        "max" if numeric => vec![Rule::max_value(size(argument)?)],
        "min" => vec![Rule::min_length(size(argument)? as usize)],
        "max" => vec![Rule::max_length(size(argument)? as usize)],
        "between" if numeric => {
            let (min, max) = argument.split_once(',').ok_or_else(unsupported)?;

            vec![Rule::between(size(min)?, size(max)?)]
        }
        "between" => {
            let (min, max) = argument.split_once(',').ok_or_else(unsupported)?;

            vec![
                Rule::min_length(size(min)? as usize),
                Rule::max_length(size(max)? as usize),
            ]
        }
        "gt" => vec![Rule::gt(argument)],
        "gte" => vec![Rule::gte(argument)],
        "lt" => vec![Rule::lt(argument)],
        "lte" => vec![Rule::lte(argument)],
        "date" => vec![Rule::date()],
        "regex" => vec![Rule::regex(argument).map_err(|_| unsupported())?],
        "starts_with" => vec![Rule::starts_with(argument.split(',').map(str::to_owned))],
        "ends_with" => vec![Rule::ends_with(argument.split(',').map(str::to_owned))],
        _ => return Err(unsupported()),
    })
}

/// Check the resolved arguments against the action's `rules`, as `Validator::make` does in PHP.
///
/// # Errors
///
/// Fails with the validation errors, which Laravel renders as a `422` or a redirect back.
pub(crate) async fn validate(
    action: &str,
    definitions: &[(&str, &str)],
    values: &Map<String, Value>,
) -> laravel::Result<()> {
    if definitions.is_empty() {
        return Ok(());
    }

    let mut rules = Rules::new();

    for (field, definition) in definitions {
        let parts: Vec<&str> = definition
            .split('|')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .collect();
        let mut list = Vec::new();

        for part in &parts {
            list.extend(rule(action, field, part, &parts, &mut rules)?);
        }

        rules = rules.field(*field, list);
    }

    match rules.validate(values).await {
        Ok(()) => Ok(()),
        Err(ValidationError::Invalid(errors)) => Err(errors.into()),
        Err(ValidationError::Failed(error)) => Err(error),
    }
}