use serde::Serialize;
use serde_json::{Map, Value};
use crate::config;
use crate::lazy::{LAZY_MARKER, MISSING_MARKER, Pending, with_registry};
use crate::partials::Partials;
#[derive(Debug, Clone, Default)]
pub(crate) struct Context {
pub include: Partials,
pub exclude: Partials,
pub only: Partials,
pub except: Partials,
}
impl Context {
fn child(&self, key: &str) -> Self {
Self {
include: self.include.child(key),
exclude: self.exclude.child(key),
only: self.only.child(key),
except: self.except.child(key),
}
}
}
pub(crate) fn transform<T: Serialize + ?Sized>(value: &T, context: &Context) -> Value {
let (json, registry) = with_registry(|| serde_json::to_value(value).unwrap_or(Value::Null));
process(json, context, ®istry)
}
fn lazy_index(value: &Value) -> Option<usize> {
let object = value.as_object()?;
if object.len() != 1 {
return None;
}
object
.get(LAZY_MARKER)?
.as_u64()
.and_then(|index| usize::try_from(index).ok())
}
fn is_missing(value: &Value) -> bool {
value
.as_object()
.is_some_and(|object| object.len() == 1 && object.contains_key(MISSING_MARKER))
}
fn included(pending: &Pending, key: &str, context: &Context) -> bool {
if let Some(condition) = &pending.condition {
return condition();
}
if context.exclude.contains_leaf(key) {
return false;
}
context.include.contains(key) || pending.default_included
}
fn process(value: Value, context: &Context, registry: &[Pending]) -> Value {
match value {
Value::Array(items) => Value::Array(items.into_iter().map(|item| process(item, context, registry)).collect()),
Value::Object(object) => {
let mut output = Map::new();
for (key, value) in object {
if !context.only.is_empty() && !context.only.contains(&key) {
continue;
}
if context.except.contains_leaf(&key) {
continue;
}
if is_missing(&value) {
continue;
}
let child = context.child(&key);
let value = match lazy_index(&value) {
Some(index) => {
let Some(pending) = registry.get(index) else { continue };
if !included(pending, &key, context) {
continue;
}
let (resolved, nested) = with_registry(|| (pending.resolve)());
process(resolved, &child, &nested)
}
None => process(value, &child, registry),
};
output.insert(key, value);
}
Value::Object(output)
}
other => other,
}
}
#[derive(Debug, Clone)]
pub struct Transformation<T> {
pub(crate) value: T,
pub(crate) context: Context,
pub(crate) additional: Map<String, Value>,
pub(crate) wrap: Option<Option<String>>,
}
impl<T: Serialize> Transformation<T> {
pub(crate) fn new(value: T, context: Context) -> Self {
Self {
value,
context,
additional: Map::new(),
wrap: None,
}
}
#[must_use]
pub fn include<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.context.include.merge(&Partials::parse(paths));
self
}
#[must_use]
pub fn exclude<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.context.exclude.merge(&Partials::parse(paths));
self
}
#[must_use]
pub fn only<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.context.only.merge(&Partials::parse(paths));
self
}
#[must_use]
pub fn except<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.context.except.merge(&Partials::parse(paths));
self
}
#[must_use]
pub fn additional(mut self, additional: impl Serialize) -> Self {
if let Ok(Value::Object(map)) = serde_json::to_value(additional) {
self.additional.extend(map);
}
self
}
#[must_use]
pub fn wrap(mut self, key: impl Into<String>) -> Self {
self.wrap = Some(Some(key.into()));
self
}
#[must_use]
pub fn without_wrapping(mut self) -> Self {
self.wrap = Some(None);
self
}
#[must_use]
pub fn to_value(&self) -> Value {
let mut value = transform(&self.value, &self.context);
if let Value::Object(object) = &mut value {
object.extend(self.additional.clone());
}
value
}
#[must_use]
pub fn to_array(&self) -> Map<String, Value> {
match self.to_value() {
Value::Object(map) => map,
_ => Map::new(),
}
}
#[must_use]
pub fn to_json(&self) -> String {
self.to_value().to_string()
}
#[must_use]
pub fn to_response_value(&self) -> Value {
let value = self.to_value();
let key = match &self.wrap {
Some(key) => key.clone(),
None => config::current().wrap,
};
match key {
Some(key) => {
let mut wrapped = Map::new();
wrapped.insert(key, value);
Value::Object(wrapped)
}
None => value,
}
}
}
impl<T: Serialize> laravel::http::IntoResponse for Transformation<T> {
fn into_response(self) -> laravel::http::Response {
laravel::http::IntoResponse::into_response(laravel::http::Json(self.to_response_value()))
}
}