laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::error::ActionError;

/// What `run` and `dispatch` receive, in the shapes PHP accepts them.
///
/// | PHP | Rust |
/// |---|---|
/// | `run('a', 'b')` | `run(("a", "b"))` |
/// | `run('a')` | `run("a")` |
/// | `run($order)` | `run((order,))`, a tuple is always positional |
/// | `run(email: 'a', subject: 'b')` | `run(args! { email: "a", subject: "b" })` |
/// | `run(['email' => 'a'])` | `run(json!({ "email": "a" }))` |
/// | `run()` | `run(())` |
///
/// A struct serializes to an object, which PHP cannot tell from an array, so a struct is
/// passed inside a tuple, where it is one positional argument and never spread.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum Arguments {
    /// Arguments given by position.
    Positional(Vec<Value>),
    /// One array: a JSON object or list, `Vec`, or `Map`. A single `array`-like parameter takes
    /// it whole, and otherwise its keys name the parameters, or its items fill them in order.
    Array(Value),
    /// Arguments given by name, as PHP's named arguments.
    Named(Map<String, Value>),
}

/// Build named arguments, the closest Rust has to `run(email: 'a', subject: 'b')`.
///
/// ```
/// # use laractions::args;
/// let arguments = args! { email: "user@example.com", subject: "Welcome!" };
/// ```
///
/// # Panics
///
/// Panics when a value cannot be serialized, as `serde_json::json!` does.
#[macro_export]
macro_rules! args {
    () => {
        $crate::Arguments::Named($crate::__private::Map::new())
    };
    ($($name:ident : $value:expr),+ $(,)?) => {{
        let mut map = $crate::__private::Map::new();

        $(
            map.insert(
                ::std::stringify!($name).trim_start_matches("r#").to_owned(),
                $crate::__private::to_value(&$value).expect("an argument of args! must serialize"),
            );
        )+

        $crate::Arguments::Named(map)
    }};
}

/// Anything `run` and `dispatch` accept as the action's arguments.
pub trait IntoArguments {
    /// The arguments.
    ///
    /// # Errors
    ///
    /// Fails when a value cannot be serialized.
    fn into_arguments(self) -> laravel::Result<Arguments>;
}

impl IntoArguments for Arguments {
    fn into_arguments(self) -> laravel::Result<Arguments> {
        Ok(self)
    }
}

impl IntoArguments for () {
    fn into_arguments(self) -> laravel::Result<Arguments> {
        Ok(Arguments::Positional(Vec::new()))
    }
}

impl IntoArguments for Value {
    fn into_arguments(self) -> laravel::Result<Arguments> {
        Ok(if is_array(&self) {
            Arguments::Array(self)
        } else {
            Arguments::Positional(vec![self])
        })
    }
}

impl IntoArguments for Map<String, Value> {
    fn into_arguments(self) -> laravel::Result<Arguments> {
        Ok(Arguments::Array(Value::Object(self)))
    }
}

impl<T: Serialize> IntoArguments for Vec<T> {
    fn into_arguments(self) -> laravel::Result<Arguments> {
        Ok(Arguments::Array(serde_json::to_value(self)?))
    }
}

macro_rules! scalar_arguments {
    ($($scalar:ty),*) => {
        $(
            impl IntoArguments for $scalar {
                fn into_arguments(self) -> laravel::Result<Arguments> {
                    Ok(Arguments::Positional(vec![serde_json::to_value(self)?]))
                }
            }
        )*
    };
}

scalar_arguments!(
    &str, String, &String, bool, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64
);

macro_rules! tuple_arguments {
    ($($name:ident),+) => {
        impl<$($name: Serialize),+> IntoArguments for ($($name,)+) {
            fn into_arguments(self) -> laravel::Result<Arguments> {
                #[allow(non_snake_case)]
                let ($($name,)+) = self;

                Ok(Arguments::Positional(vec![$(serde_json::to_value($name)?),+]))
            }
        }
    };
}

tuple_arguments!(A);
tuple_arguments!(A, B);
tuple_arguments!(A, B, C);
tuple_arguments!(A, B, C, D);
tuple_arguments!(A, B, C, D, E);
tuple_arguments!(A, B, C, D, E, F);
tuple_arguments!(A, B, C, D, E, F, G);
tuple_arguments!(A, B, C, D, E, F, G, H);
tuple_arguments!(A, B, C, D, E, F, G, H, I);
tuple_arguments!(A, B, C, D, E, F, G, H, I, J);

/// A parameter of `handle`, as `#[action]` read it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Parameter {
    /// The parameter's name.
    pub name: &'static str,
    /// Whether the parameter is an `Option`, so an argument left out arrives as `None`.
    pub optional: bool,
    /// Whether the parameter accepts a whole array: a `Value`, a map, a `Vec` or a set.
    pub bag: bool,
}

/// The arguments of a call, matched to the parameters of `handle` by name.
#[derive(Debug, Clone, Default)]
pub struct Resolved {
    values: Map<String, Value>,
}

impl Resolved {
    pub(crate) fn new(values: Map<String, Value>) -> Self {
        Self { values }
    }

    /// Take the value of a parameter, as the type `handle` declares.
    ///
    /// # Errors
    ///
    /// Fails with an [`ActionError::Argument`] when the value does not fit the type.
    pub fn take<T: serde::de::DeserializeOwned>(&mut self, action: &str, parameter: &str) -> laravel::Result<T> {
        let value = self.values.remove(parameter).unwrap_or(Value::Null);

        serde_json::from_value(value).map_err(|error| {
            ActionError::Argument {
                action: action.to_owned(),
                parameter: parameter.to_owned(),
                reason: error.to_string(),
            }
            .into()
        })
    }
}

/// How the arguments were matched.
pub(crate) struct Bound {
    /// The value of every parameter, by name.
    pub resolved: Map<String, Value>,
    /// The array that was spread across the parameters, when a single associative array was given.
    pub spread: Option<Map<String, Value>>,
}

fn is_array(value: &Value) -> bool {
    matches!(value, Value::Object(_) | Value::Array(_))
}

/// Match arguments to parameters the way `Action::run()` does in PHP.
///
/// A single array given to a single `array`-like parameter is that parameter, whole. Any other
/// single array is spread: its keys name parameters, or its items fill them in order. Missing
/// arguments become `null`, which `Option` parameters read as `None`.
pub(crate) fn bind(parameters: &[Parameter], arguments: Arguments) -> Bound {
    let mut named = Map::new();
    let mut positional = Vec::new();
    let mut spread = None;

    match arguments {
        Arguments::Named(map) => named = map,
        Arguments::Positional(list) => positional = list,
        Arguments::Array(array) if parameters.len() == 1 && parameters[0].bag => positional = vec![array],
        Arguments::Array(Value::Object(map)) => {
            spread = Some(map.clone());
            named = map;
        }
        Arguments::Array(Value::Array(items)) => positional = items,
        Arguments::Array(scalar) => positional = vec![scalar],
    }

    let mut positional = positional.into_iter();
    let mut resolved = Map::new();

    for parameter in parameters {
        let value = match named.remove(parameter.name) {
            Some(value) => value,
            None => positional.next().unwrap_or(Value::Null),
        };

        resolved.insert(parameter.name.to_owned(), value);
    }

    Bound { resolved, spread }
}

/// The error for a single array that matches none of `handle`'s parameters, when that leaves a
/// required one empty.
pub(crate) fn explain_unbound_array(
    action: &str,
    parameters: &[Parameter],
    array: &Map<String, Value>,
    resolved: &Map<String, Value>,
) -> Option<ActionError> {
    if parameters.iter().any(|parameter| array.contains_key(parameter.name)) {
        return None;
    }

    let empty = parameters
        .iter()
        .find(|parameter| !parameter.optional && resolved.get(parameter.name).is_none_or(Value::is_null))?;
    let mut keys = array.keys().take(5).cloned().collect::<Vec<_>>().join(", ");

    if array.len() > 5 {
        keys.push_str(", ...");
    }

    Some(ActionError::UnboundArray {
        action: action.to_owned(),
        keys,
        parameters: parameters
            .iter()
            .map(|parameter| parameter.name)
            .collect::<Vec<_>>()
            .join(", "),
        parameter: empty.name.to_owned(),
    })
}

impl fmt::Display for Arguments {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Positional(list) => write!(f, "{}", Value::Array(list.clone())),
            Self::Array(value) => write!(f, "{value}"),
            Self::Named(map) => write!(f, "{}", Value::Object(map.clone())),
        }
    }
}