laravel-data 0.2.0

Powerful data objects for Laravel Rust: a port of spatie/laravel-data.
Documentation
//! `Data`: the PHP package's base class.

use laravel::http::Request;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};

use crate::partials::Partials;
use crate::transform::{Context, Transformation};

/// A data object: the PHP package's `Data` class. Derive `Serialize` (and `Deserialize` to
/// create it from input), then implement `Data`:
///
/// ```ignore
/// #[derive(Serialize, Deserialize)]
/// pub struct SongData {
///     pub title: String,
///     pub artist: String,
/// }
///
/// impl Data for SongData {}
///
/// let song = SongData::from_value(json!({"title": "Never Gonna Give You Up", "artist": "Rick Astley"}))?;
/// song.to_array();
/// ```
///
/// Property names follow serde's attributes: `#[serde(rename = "..")]` and
/// `#[serde(rename_all = "camelCase")]` are PHP's `MapName` attributes.
pub trait Data: Serialize + Sized {
    /// Lazy properties always included: `includeProperties()`.
    fn include_properties(&self) -> Vec<&'static str> {
        Vec::new()
    }

    /// Lazy properties always excluded: `excludeProperties()`.
    fn exclude_properties(&self) -> Vec<&'static str> {
        Vec::new()
    }

    /// The only properties output: `onlyProperties()`.
    fn only_properties(&self) -> Vec<&'static str> {
        Vec::new()
    }

    /// Properties never output: `exceptProperties()`.
    fn except_properties(&self) -> Vec<&'static str> {
        Vec::new()
    }

    /// Properties added to the output: `with()`.
    fn with(&self) -> Map<String, Value> {
        Map::new()
    }

    /// The key to wrap responses in: the class's `wrap`. `None` uses the configured key.
    fn default_wrap(&self) -> Option<&'static str> {
        None
    }

    /// The includes a request may ask for with `?include=`: `allowedRequestIncludes()`. Empty
    /// allows none, `None` allows all.
    fn allowed_request_includes() -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }

    /// The excludes a request may ask for with `?exclude=`: `allowedRequestExcludes()`.
    fn allowed_request_excludes() -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }

    /// The only-properties a request may ask for with `?only=`: `allowedRequestOnly()`.
    fn allowed_request_only() -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }

    /// The except-properties a request may ask for with `?except=`: `allowedRequestExcept()`.
    fn allowed_request_except() -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }

    /// Creates the data object from a JSON value: `from()` with an array.
    ///
    /// # Errors
    ///
    /// Fails with a `422` naming the field when the value doesn't fit.
    fn from_value(value: Value) -> laravel::Result<Self>
    where
        Self: DeserializeOwned,
    {
        serde_json::from_value(value).map_err(|error| laravel::Error::new(422, error))
    }

    /// Creates the data object from anything serializable, such as a model: `from()`.
    ///
    /// # Errors
    ///
    /// As [`from_value`](Self::from_value).
    fn from_source(source: &impl Serialize) -> laravel::Result<Self>
    where
        Self: DeserializeOwned,
    {
        Self::from_value(serde_json::to_value(source).map_err(|error| laravel::Error::msg(error.to_string()))?)
    }

    /// Creates a list of data objects: `collect()`.
    ///
    /// # Errors
    ///
    /// As [`from_value`](Self::from_value).
    fn collect<S: Serialize>(sources: impl IntoIterator<Item = S>) -> laravel::Result<Vec<Self>>
    where
        Self: DeserializeOwned,
    {
        sources.into_iter().map(|source| Self::from_source(&source)).collect()
    }

    /// The transformation of this object, with its own partials, additional data and wrap.
    fn transformation(self) -> Transformation<Self> {
        let context = Context {
            include: Partials::parse(self.include_properties()),
            exclude: Partials::parse(self.exclude_properties()),
            only: Partials::parse(self.only_properties()),
            except: Partials::parse(self.except_properties()),
        };
        let additional = self.with();
        let wrap = self.default_wrap().map(|key| Some(key.to_owned()));
        let mut transformation = Transformation::new(self, context).additional(additional);
        if let Some(wrap) = wrap {
            transformation.wrap = Some(wrap);
        }
        transformation
    }

    /// Includes lazy properties: `include()`.
    fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
        self.transformation().include(paths)
    }

    /// Excludes lazy properties: `exclude()`.
    fn exclude<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
        self.transformation().exclude(paths)
    }

    /// Keeps only these properties: `only()`.
    fn only<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
        self.transformation().only(paths)
    }

    /// Leaves these properties out: `except()`.
    fn except<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
        self.transformation().except(paths)
    }

    /// Adds properties: `additional()`.
    fn additional(self, additional: impl Serialize) -> Transformation<Self> {
        self.transformation().additional(additional)
    }

    /// Wraps responses in a key: `wrap()`.
    fn wrap(self, key: impl Into<String>) -> Transformation<Self> {
        self.transformation().wrap(key)
    }

    /// The transformed object: `toArray()`.
    fn to_array(&self) -> Map<String, Value> {
        let context = Context {
            include: Partials::parse(self.include_properties()),
            exclude: Partials::parse(self.exclude_properties()),
            only: Partials::parse(self.only_properties()),
            except: Partials::parse(self.except_properties()),
        };
        let mut value = crate::transform::transform(self, &context);
        if let Value::Object(object) = &mut value {
            object.extend(self.with());
            return std::mem::take(object);
        }
        Map::new()
    }

    /// The JSON text: `toJson()`.
    fn to_json(&self) -> String {
        Value::Object(self.to_array()).to_string()
    }

    /// The response for `request`, with the partials its query string asks for and the
    /// statuses PHP gives: `201` for a `POST`, else `200`. `toResponse()`.
    fn to_response(self, request: &Request) -> laravel::http::Response {
        let transformation = with_request_partials::<Self, Self>(self.transformation(), request);
        response(&transformation, request)
    }
}

/// Lists of data objects: PHP's `DataCollection` and `collect()`.
pub trait DataCollection<T: Data> {
    /// The list's transformation.
    fn transformation(self) -> Transformation<Vec<T>>;

    /// Includes lazy properties of each item: `include()`.
    fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Vec<T>>
    where
        Self: Sized,
    {
        self.transformation().include(paths)
    }

    /// The response for `request`: `toResponse()`.
    fn to_response(self, request: &Request) -> laravel::http::Response
    where
        Self: Sized,
    {
        let transformation = with_request_partials::<T, Vec<T>>(self.transformation(), request);
        response(&transformation, request)
    }
}

impl<T: Data> DataCollection<T> for Vec<T> {
    fn transformation(self) -> Transformation<Vec<T>> {
        Transformation::new(self, Context::default())
    }
}

fn response<V: Serialize>(transformation: &Transformation<V>, request: &Request) -> laravel::http::Response {
    let status = if request.method() == laravel::http::Method::POST {
        201
    } else {
        200
    };
    laravel::http::IntoResponse::into_response(laravel::http::Json(transformation.to_response_value()))
        .with_status(status)
}

/// Adds the partials of `?include=`, `?exclude=`, `?only=` and `?except=` that `D` allows.
fn with_request_partials<D: Data, V: Serialize>(
    mut transformation: Transformation<V>,
    request: &Request,
) -> Transformation<V> {
    let query: Vec<(String, String)> = request
        .uri()
        .query()
        .map(|query| form_urlencoded::parse(query.as_bytes()).into_owned().collect())
        .unwrap_or_default();
    let requested = |name: &str, allowed: Option<Vec<&'static str>>| -> Vec<String> {
        let values: Vec<String> = query
            .iter()
            .filter(|(key, _)| key == name)
            .flat_map(|(_, value)| value.split(',').map(|part| part.trim().to_owned()).collect::<Vec<_>>())
            .filter(|part| !part.is_empty())
            .collect();
        match allowed {
            None => values,
            Some(allowed) => values
                .into_iter()
                .filter(|value| allowed.iter().any(|allowed| *allowed == "*" || value == allowed))
                .collect(),
        }
    };
    transformation = transformation.include(requested("include", D::allowed_request_includes()));
    transformation = transformation.exclude(requested("exclude", D::allowed_request_excludes()));
    transformation = transformation.only(requested("only", D::allowed_request_only()));
    transformation.except(requested("except", D::allowed_request_except()))
}