laravel-data 0.2.0

Powerful data objects for Laravel Rust: a port of spatie/laravel-data.
Documentation
//! `Lazy` and `Optional`: properties that are left out unless asked for, or missing.

use std::cell::RefCell;
use std::fmt;
use std::sync::Arc;

use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, SerializeMap, Serializer};
use serde_json::Value;

pub(crate) const LAZY_MARKER: &str = "$laravel_data_lazy";
pub(crate) const MISSING_MARKER: &str = "$laravel_data_optional_missing";

type Resolve = Arc<dyn Fn() -> Value + Send + Sync>;
type Condition = Arc<dyn Fn() -> bool + Send + Sync>;

/// A lazy property waiting in the current transformation.
pub(crate) struct Pending {
    pub resolve: Resolve,
    pub condition: Option<Condition>,
    pub default_included: bool,
}

thread_local! {
    static PENDING: RefCell<Option<Vec<Pending>>> = const { RefCell::new(None) };
}

/// Runs `work` with a registry of lazy properties, returning its result and the registry.
pub(crate) fn with_registry<T>(work: impl FnOnce() -> T) -> (T, Vec<Pending>) {
    let previous = PENDING.with(|pending| pending.replace(Some(Vec::new())));
    let result = work();
    let registry = PENDING.with(|pending| pending.replace(previous)).unwrap_or_default();
    (result, registry)
}

/// A property that's only included when asked for: the PHP package's `Lazy`.
///
/// ```ignore
/// AlbumData {
///     title: album.title.clone(),
///     songs: Lazy::create(move || SongData::collect(&songs)),
/// }
/// ```
pub struct Lazy<T> {
    value: Arc<dyn Fn() -> T + Send + Sync>,
    condition: Option<Condition>,
    default_included: bool,
}

impl<T> Clone for Lazy<T> {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            condition: self.condition.clone(),
            default_included: self.default_included,
        }
    }
}

impl<T> fmt::Debug for Lazy<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Lazy")
            .field("default_included", &self.default_included)
            .field("conditional", &self.condition.is_some())
            .finish_non_exhaustive()
    }
}

impl<T> Lazy<T> {
    /// A lazy property, included with `include`: `Lazy::create`.
    pub fn create(value: impl Fn() -> T + Send + Sync + 'static) -> Self {
        Self {
            value: Arc::new(value),
            condition: None,
            default_included: false,
        }
    }

    /// A property included only when `condition` holds when transformed: `Lazy::when`. It can't
    /// be included otherwise.
    pub fn when(
        condition: impl Fn() -> bool + Send + Sync + 'static,
        value: impl Fn() -> T + Send + Sync + 'static,
    ) -> Self {
        Self {
            value: Arc::new(value),
            condition: Some(Arc::new(condition)),
            default_included: false,
        }
    }

    /// Includes the property unless it's excluded: `defaultIncluded()`.
    #[must_use]
    pub fn default_included(mut self) -> Self {
        self.default_included = true;
        self
    }

    /// Whether the property is included by default: `isDefaultIncluded()`.
    #[must_use]
    pub fn is_default_included(&self) -> bool {
        self.default_included
    }

    /// The value: `resolve()`.
    #[must_use]
    pub fn resolve(&self) -> T {
        (self.value)()
    }
}

impl<T: Serialize + 'static> Serialize for Lazy<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let registered = PENDING.with(|pending| {
            let mut pending = pending.borrow_mut();
            let registry = pending.as_mut()?;
            let value = self.value.clone();
            registry.push(Pending {
                resolve: Arc::new(move || serde_json::to_value(value()).unwrap_or(Value::Null)),
                condition: self.condition.clone(),
                default_included: self.default_included,
            });
            Some(registry.len() - 1)
        });
        match registered {
            Some(index) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry(LAZY_MARKER, &index)?;
                map.end()
            }
            // Outside a transformation, as plain serde: the value when it's included by default.
            None if self.default_included || self.condition.as_ref().is_some_and(|condition| condition()) => {
                self.resolve().serialize(serializer)
            }
            None => serializer.serialize_none(),
        }
    }
}

/// A value that may be missing from the input, and is left out of the output when it is: the
/// PHP package's `Optional`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Optional<T> {
    /// The property wasn't given.
    #[default]
    Missing,
    /// The property's value.
    Present(T),
}

impl<T> Optional<T> {
    /// Whether the property is missing.
    #[must_use]
    pub const fn is_missing(&self) -> bool {
        matches!(self, Self::Missing)
    }

    /// The value, if present.
    #[must_use]
    pub fn as_option(&self) -> Option<&T> {
        match self {
            Self::Missing => None,
            Self::Present(value) => Some(value),
        }
    }
}

impl<T: Serialize> Serialize for Optional<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Present(value) => value.serialize(serializer),
            Self::Missing => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry(MISSING_MARKER, &true)?;
                map.end()
            }
        }
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Optional<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        T::deserialize(deserializer).map(Self::Present)
    }
}