laravel-data 0.1.0

Powerful data objects for Laravel Rust: a port of spatie/laravel-data.
Documentation
//! Transforming data objects to arrays and responses, with partials, additional data and wrapping.

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

use crate::config;
use crate::lazy::{LAZY_MARKER, MISSING_MARKER, Pending, with_registry};
use crate::partials::Partials;

/// The partials of one transformation.
#[derive(Debug, Clone, Default)]
pub(crate) struct Context {
    pub include: Partials,
    pub exclude: Partials,
    pub only: Partials,
    pub except: Partials,
}

impl Context {
    fn child(&self, key: &str) -> Self {
        Self {
            include: self.include.child(key),
            exclude: self.exclude.child(key),
            only: self.only.child(key),
            except: self.except.child(key),
        }
    }
}

/// Serializes `value` and applies the partials: PHP's `transform()`.
pub(crate) fn transform<T: Serialize + ?Sized>(value: &T, context: &Context) -> Value {
    let (json, registry) = with_registry(|| serde_json::to_value(value).unwrap_or(Value::Null));
    process(json, context, &registry)
}

fn lazy_index(value: &Value) -> Option<usize> {
    let object = value.as_object()?;
    if object.len() != 1 {
        return None;
    }
    object
        .get(LAZY_MARKER)?
        .as_u64()
        .and_then(|index| usize::try_from(index).ok())
}

fn is_missing(value: &Value) -> bool {
    value
        .as_object()
        .is_some_and(|object| object.len() == 1 && object.contains_key(MISSING_MARKER))
}

fn included(pending: &Pending, key: &str, context: &Context) -> bool {
    if let Some(condition) = &pending.condition {
        return condition();
    }
    if context.exclude.contains_leaf(key) {
        return false;
    }
    context.include.contains(key) || pending.default_included
}

fn process(value: Value, context: &Context, registry: &[Pending]) -> Value {
    match value {
        Value::Array(items) => Value::Array(items.into_iter().map(|item| process(item, context, registry)).collect()),
        Value::Object(object) => {
            let mut output = Map::new();
            for (key, value) in object {
                if !context.only.is_empty() && !context.only.contains(&key) {
                    continue;
                }
                if context.except.contains_leaf(&key) {
                    continue;
                }
                if is_missing(&value) {
                    continue;
                }
                let child = context.child(&key);
                let value = match lazy_index(&value) {
                    Some(index) => {
                        let Some(pending) = registry.get(index) else { continue };
                        if !included(pending, &key, context) {
                            continue;
                        }
                        let (resolved, nested) = with_registry(|| (pending.resolve)());
                        process(resolved, &child, &nested)
                    }
                    None => process(value, &child, registry),
                };
                output.insert(key, value);
            }
            Value::Object(output)
        }
        other => other,
    }
}

/// A data object or collection with the partials, additional data and wrap of one
/// transformation: what PHP's `include()`, `additional()` and `wrap()` return.
#[derive(Debug, Clone)]
pub struct Transformation<T> {
    pub(crate) value: T,
    pub(crate) context: Context,
    pub(crate) additional: Map<String, Value>,
    pub(crate) wrap: Option<Option<String>>,
}

impl<T: Serialize> Transformation<T> {
    pub(crate) fn new(value: T, context: Context) -> Self {
        Self {
            value,
            context,
            additional: Map::new(),
            wrap: None,
        }
    }

    /// Includes lazy properties: `include('songs', 'songs.{name, artist}')`.
    #[must_use]
    pub fn include<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
        self.context.include.merge(&Partials::parse(paths));
        self
    }

    /// Excludes lazy properties included by default: `exclude()`.
    #[must_use]
    pub fn exclude<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
        self.context.exclude.merge(&Partials::parse(paths));
        self
    }

    /// Keeps only these properties: `only()`.
    #[must_use]
    pub fn only<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
        self.context.only.merge(&Partials::parse(paths));
        self
    }

    /// Leaves these properties out: `except()`.
    #[must_use]
    pub fn except<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
        self.context.except.merge(&Partials::parse(paths));
        self
    }

    /// Adds properties to the output: `additional()`.
    #[must_use]
    pub fn additional(mut self, additional: impl Serialize) -> Self {
        if let Ok(Value::Object(map)) = serde_json::to_value(additional) {
            self.additional.extend(map);
        }
        self
    }

    /// Wraps the response in a key, such as `data`: `wrap()`.
    #[must_use]
    pub fn wrap(mut self, key: impl Into<String>) -> Self {
        self.wrap = Some(Some(key.into()));
        self
    }

    /// Doesn't wrap the response: `withoutWrapping()`.
    #[must_use]
    pub fn without_wrapping(mut self) -> Self {
        self.wrap = Some(None);
        self
    }

    /// The transformed value: `toArray()`.
    #[must_use]
    pub fn to_value(&self) -> Value {
        let mut value = transform(&self.value, &self.context);
        if let Value::Object(object) = &mut value {
            object.extend(self.additional.clone());
        }
        value
    }

    /// The transformed object, as a map: `toArray()`.
    #[must_use]
    pub fn to_array(&self) -> Map<String, Value> {
        match self.to_value() {
            Value::Object(map) => map,
            _ => Map::new(),
        }
    }

    /// The JSON text: `toJson()`.
    #[must_use]
    pub fn to_json(&self) -> String {
        self.to_value().to_string()
    }

    /// The value a response sends: the transformed value, wrapped in the data's or the
    /// configured key.
    #[must_use]
    pub fn to_response_value(&self) -> Value {
        let value = self.to_value();
        let key = match &self.wrap {
            Some(key) => key.clone(),
            None => config::current().wrap,
        };
        match key {
            Some(key) => {
                let mut wrapped = Map::new();
                wrapped.insert(key, value);
                Value::Object(wrapped)
            }
            None => value,
        }
    }
}

impl<T: Serialize> laravel::http::IntoResponse for Transformation<T> {
    fn into_response(self) -> laravel::http::Response {
        laravel::http::IntoResponse::into_response(laravel::http::Json(self.to_response_value()))
    }
}