Skip to main content

laravel_data/
lazy.rs

1//! `Lazy` and `Optional`: properties that are left out unless asked for, or missing.
2
3use std::cell::RefCell;
4use std::fmt;
5use std::sync::Arc;
6
7use serde::de::{Deserialize, Deserializer};
8use serde::ser::{Serialize, SerializeMap, Serializer};
9use serde_json::Value;
10
11pub(crate) const LAZY_MARKER: &str = "$laravel_data_lazy";
12pub(crate) const MISSING_MARKER: &str = "$laravel_data_optional_missing";
13
14type Resolve = Arc<dyn Fn() -> Value + Send + Sync>;
15type Condition = Arc<dyn Fn() -> bool + Send + Sync>;
16
17/// A lazy property waiting in the current transformation.
18pub(crate) struct Pending {
19    pub resolve: Resolve,
20    pub condition: Option<Condition>,
21    pub default_included: bool,
22}
23
24thread_local! {
25    static PENDING: RefCell<Option<Vec<Pending>>> = const { RefCell::new(None) };
26}
27
28/// Runs `work` with a registry of lazy properties, returning its result and the registry.
29pub(crate) fn with_registry<T>(work: impl FnOnce() -> T) -> (T, Vec<Pending>) {
30    let previous = PENDING.with(|pending| pending.replace(Some(Vec::new())));
31    let result = work();
32    let registry = PENDING.with(|pending| pending.replace(previous)).unwrap_or_default();
33    (result, registry)
34}
35
36/// A property that's only included when asked for: the PHP package's `Lazy`.
37///
38/// ```ignore
39/// AlbumData {
40///     title: album.title.clone(),
41///     songs: Lazy::create(move || SongData::collect(&songs)),
42/// }
43/// ```
44pub struct Lazy<T> {
45    value: Arc<dyn Fn() -> T + Send + Sync>,
46    condition: Option<Condition>,
47    default_included: bool,
48}
49
50impl<T> Clone for Lazy<T> {
51    fn clone(&self) -> Self {
52        Self {
53            value: self.value.clone(),
54            condition: self.condition.clone(),
55            default_included: self.default_included,
56        }
57    }
58}
59
60impl<T> fmt::Debug for Lazy<T> {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        formatter
63            .debug_struct("Lazy")
64            .field("default_included", &self.default_included)
65            .field("conditional", &self.condition.is_some())
66            .finish_non_exhaustive()
67    }
68}
69
70impl<T> Lazy<T> {
71    /// A lazy property, included with `include`: `Lazy::create`.
72    pub fn create(value: impl Fn() -> T + Send + Sync + 'static) -> Self {
73        Self {
74            value: Arc::new(value),
75            condition: None,
76            default_included: false,
77        }
78    }
79
80    /// A property included only when `condition` holds when transformed: `Lazy::when`. It can't
81    /// be included otherwise.
82    pub fn when(
83        condition: impl Fn() -> bool + Send + Sync + 'static,
84        value: impl Fn() -> T + Send + Sync + 'static,
85    ) -> Self {
86        Self {
87            value: Arc::new(value),
88            condition: Some(Arc::new(condition)),
89            default_included: false,
90        }
91    }
92
93    /// Includes the property unless it's excluded: `defaultIncluded()`.
94    #[must_use]
95    pub fn default_included(mut self) -> Self {
96        self.default_included = true;
97        self
98    }
99
100    /// Whether the property is included by default: `isDefaultIncluded()`.
101    #[must_use]
102    pub fn is_default_included(&self) -> bool {
103        self.default_included
104    }
105
106    /// The value: `resolve()`.
107    #[must_use]
108    pub fn resolve(&self) -> T {
109        (self.value)()
110    }
111}
112
113impl<T: Serialize + 'static> Serialize for Lazy<T> {
114    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
115        let registered = PENDING.with(|pending| {
116            let mut pending = pending.borrow_mut();
117            let registry = pending.as_mut()?;
118            let value = self.value.clone();
119            registry.push(Pending {
120                resolve: Arc::new(move || serde_json::to_value(value()).unwrap_or(Value::Null)),
121                condition: self.condition.clone(),
122                default_included: self.default_included,
123            });
124            Some(registry.len() - 1)
125        });
126        match registered {
127            Some(index) => {
128                let mut map = serializer.serialize_map(Some(1))?;
129                map.serialize_entry(LAZY_MARKER, &index)?;
130                map.end()
131            }
132            // Outside a transformation, as plain serde: the value when it's included by default.
133            None if self.default_included || self.condition.as_ref().is_some_and(|condition| condition()) => {
134                self.resolve().serialize(serializer)
135            }
136            None => serializer.serialize_none(),
137        }
138    }
139}
140
141/// A value that may be missing from the input, and is left out of the output when it is: the
142/// PHP package's `Optional`.
143#[derive(Debug, Clone, Default, PartialEq, Eq)]
144pub enum Optional<T> {
145    /// The property wasn't given.
146    #[default]
147    Missing,
148    /// The property's value.
149    Present(T),
150}
151
152impl<T> Optional<T> {
153    /// Whether the property is missing.
154    #[must_use]
155    pub const fn is_missing(&self) -> bool {
156        matches!(self, Self::Missing)
157    }
158
159    /// The value, if present.
160    #[must_use]
161    pub fn as_option(&self) -> Option<&T> {
162        match self {
163            Self::Missing => None,
164            Self::Present(value) => Some(value),
165        }
166    }
167}
168
169impl<T: Serialize> Serialize for Optional<T> {
170    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
171        match self {
172            Self::Present(value) => value.serialize(serializer),
173            Self::Missing => {
174                let mut map = serializer.serialize_map(Some(1))?;
175                map.serialize_entry(MISSING_MARKER, &true)?;
176                map.end()
177            }
178        }
179    }
180}
181
182impl<'de, T: Deserialize<'de>> Deserialize<'de> for Optional<T> {
183    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
184        T::deserialize(deserializer).map(Self::Present)
185    }
186}