Skip to main content

laravel_data/
transform.rs

1//! Transforming data objects to arrays and responses, with partials, additional data and wrapping.
2
3use serde::Serialize;
4use serde_json::{Map, Value};
5
6use crate::config;
7use crate::lazy::{LAZY_MARKER, MISSING_MARKER, Pending, with_registry};
8use crate::partials::Partials;
9
10/// The partials of one transformation.
11#[derive(Debug, Clone, Default)]
12pub(crate) struct Context {
13    pub include: Partials,
14    pub exclude: Partials,
15    pub only: Partials,
16    pub except: Partials,
17}
18
19impl Context {
20    fn child(&self, key: &str) -> Self {
21        Self {
22            include: self.include.child(key),
23            exclude: self.exclude.child(key),
24            only: self.only.child(key),
25            except: self.except.child(key),
26        }
27    }
28}
29
30/// Serializes `value` and applies the partials: PHP's `transform()`.
31pub(crate) fn transform<T: Serialize + ?Sized>(value: &T, context: &Context) -> Value {
32    let (json, registry) = with_registry(|| serde_json::to_value(value).unwrap_or(Value::Null));
33    process(json, context, &registry)
34}
35
36fn lazy_index(value: &Value) -> Option<usize> {
37    let object = value.as_object()?;
38    if object.len() != 1 {
39        return None;
40    }
41    object
42        .get(LAZY_MARKER)?
43        .as_u64()
44        .and_then(|index| usize::try_from(index).ok())
45}
46
47fn is_missing(value: &Value) -> bool {
48    value
49        .as_object()
50        .is_some_and(|object| object.len() == 1 && object.contains_key(MISSING_MARKER))
51}
52
53fn included(pending: &Pending, key: &str, context: &Context) -> bool {
54    if let Some(condition) = &pending.condition {
55        return condition();
56    }
57    if context.exclude.contains_leaf(key) {
58        return false;
59    }
60    context.include.contains(key) || pending.default_included
61}
62
63fn process(value: Value, context: &Context, registry: &[Pending]) -> Value {
64    match value {
65        Value::Array(items) => Value::Array(items.into_iter().map(|item| process(item, context, registry)).collect()),
66        Value::Object(object) => {
67            let mut output = Map::new();
68            for (key, value) in object {
69                if !context.only.is_empty() && !context.only.contains(&key) {
70                    continue;
71                }
72                if context.except.contains_leaf(&key) {
73                    continue;
74                }
75                if is_missing(&value) {
76                    continue;
77                }
78                let child = context.child(&key);
79                let value = match lazy_index(&value) {
80                    Some(index) => {
81                        let Some(pending) = registry.get(index) else { continue };
82                        if !included(pending, &key, context) {
83                            continue;
84                        }
85                        let (resolved, nested) = with_registry(|| (pending.resolve)());
86                        process(resolved, &child, &nested)
87                    }
88                    None => process(value, &child, registry),
89                };
90                output.insert(key, value);
91            }
92            Value::Object(output)
93        }
94        other => other,
95    }
96}
97
98/// A data object or collection with the partials, additional data and wrap of one
99/// transformation: what PHP's `include()`, `additional()` and `wrap()` return.
100#[derive(Debug, Clone)]
101pub struct Transformation<T> {
102    pub(crate) value: T,
103    pub(crate) context: Context,
104    pub(crate) additional: Map<String, Value>,
105    pub(crate) wrap: Option<Option<String>>,
106}
107
108impl<T: Serialize> Transformation<T> {
109    pub(crate) fn new(value: T, context: Context) -> Self {
110        Self {
111            value,
112            context,
113            additional: Map::new(),
114            wrap: None,
115        }
116    }
117
118    /// Includes lazy properties: `include('songs', 'songs.{name, artist}')`.
119    #[must_use]
120    pub fn include<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
121        self.context.include.merge(&Partials::parse(paths));
122        self
123    }
124
125    /// Excludes lazy properties included by default: `exclude()`.
126    #[must_use]
127    pub fn exclude<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
128        self.context.exclude.merge(&Partials::parse(paths));
129        self
130    }
131
132    /// Keeps only these properties: `only()`.
133    #[must_use]
134    pub fn only<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
135        self.context.only.merge(&Partials::parse(paths));
136        self
137    }
138
139    /// Leaves these properties out: `except()`.
140    #[must_use]
141    pub fn except<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
142        self.context.except.merge(&Partials::parse(paths));
143        self
144    }
145
146    /// Adds properties to the output: `additional()`.
147    #[must_use]
148    pub fn additional(mut self, additional: impl Serialize) -> Self {
149        if let Ok(Value::Object(map)) = serde_json::to_value(additional) {
150            self.additional.extend(map);
151        }
152        self
153    }
154
155    /// Wraps the response in a key, such as `data`: `wrap()`.
156    #[must_use]
157    pub fn wrap(mut self, key: impl Into<String>) -> Self {
158        self.wrap = Some(Some(key.into()));
159        self
160    }
161
162    /// Doesn't wrap the response: `withoutWrapping()`.
163    #[must_use]
164    pub fn without_wrapping(mut self) -> Self {
165        self.wrap = Some(None);
166        self
167    }
168
169    /// The transformed value: `toArray()`.
170    #[must_use]
171    pub fn to_value(&self) -> Value {
172        let mut value = transform(&self.value, &self.context);
173        if let Value::Object(object) = &mut value {
174            object.extend(self.additional.clone());
175        }
176        value
177    }
178
179    /// The transformed object, as a map: `toArray()`.
180    #[must_use]
181    pub fn to_array(&self) -> Map<String, Value> {
182        match self.to_value() {
183            Value::Object(map) => map,
184            _ => Map::new(),
185        }
186    }
187
188    /// The JSON text: `toJson()`.
189    #[must_use]
190    pub fn to_json(&self) -> String {
191        self.to_value().to_string()
192    }
193
194    /// The value a response sends: the transformed value, wrapped in the data's or the
195    /// configured key.
196    #[must_use]
197    pub fn to_response_value(&self) -> Value {
198        let value = self.to_value();
199        let key = match &self.wrap {
200            Some(key) => key.clone(),
201            None => config::current().wrap,
202        };
203        match key {
204            Some(key) => {
205                let mut wrapped = Map::new();
206                wrapped.insert(key, value);
207                Value::Object(wrapped)
208            }
209            None => value,
210        }
211    }
212}
213
214impl<T: Serialize> laravel::http::IntoResponse for Transformation<T> {
215    fn into_response(self) -> laravel::http::Response {
216        laravel::http::IntoResponse::into_response(laravel::http::Json(self.to_response_value()))
217    }
218}