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>;
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) };
}
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)
}
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> {
pub fn create(value: impl Fn() -> T + Send + Sync + 'static) -> Self {
Self {
value: Arc::new(value),
condition: None,
default_included: false,
}
}
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,
}
}
#[must_use]
pub fn default_included(mut self) -> Self {
self.default_included = true;
self
}
#[must_use]
pub fn is_default_included(&self) -> bool {
self.default_included
}
#[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()
}
None if self.default_included || self.condition.as_ref().is_some_and(|condition| condition()) => {
self.resolve().serialize(serializer)
}
None => serializer.serialize_none(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Optional<T> {
#[default]
Missing,
Present(T),
}
impl<T> Optional<T> {
#[must_use]
pub const fn is_missing(&self) -> bool {
matches!(self, Self::Missing)
}
#[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)
}
}