1use 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
17pub(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
28pub(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
36pub 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 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 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 #[must_use]
95 pub fn default_included(mut self) -> Self {
96 self.default_included = true;
97 self
98 }
99
100 #[must_use]
102 pub fn is_default_included(&self) -> bool {
103 self.default_included
104 }
105
106 #[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 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
144pub enum Optional<T> {
145 #[default]
147 Missing,
148 Present(T),
150}
151
152impl<T> Optional<T> {
153 #[must_use]
155 pub const fn is_missing(&self) -> bool {
156 matches!(self, Self::Missing)
157 }
158
159 #[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}