Skip to main content

laravel_template_engine/
schema.rs

1//! What a template type's variables look like: the tree the editor shows and the checks use.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
4use std::sync::Arc;
5
6use serde::Serialize;
7
8use crate::Recipient;
9use crate::defaults::DefaultTemplate;
10
11/// The shape of a value a template can read.
12#[derive(Debug, Clone, PartialEq)]
13pub enum Node {
14    /// Text.
15    Text,
16    /// A whole or decimal number.
17    Number,
18    /// `true` or `false`.
19    Bool,
20    /// A date or a date and time, given to templates as ISO 8601 text.
21    Date,
22    /// Someone a message can go to: `email`, `name` and `locale`.
23    Recipient,
24    /// A value that may be missing.
25    Optional(Box<Node>),
26    /// A list of values of one shape, for `{% for %}`.
27    List(Box<Node>),
28    /// Named fields.
29    Object(Vec<Field>),
30    /// Anything: the checks don't look inside.
31    Any,
32}
33
34/// A named field of an object.
35#[derive(Debug, Clone, PartialEq)]
36pub struct Field {
37    /// The name templates use.
38    pub name: &'static str,
39    /// What the field holds, in words for the person editing the template.
40    pub description: &'static str,
41    /// The field's shape.
42    pub node: Node,
43}
44
45impl Field {
46    /// A field. The derive macro writes these.
47    #[must_use]
48    pub fn new(name: &'static str, description: &'static str, node: Node) -> Self {
49        Self {
50            name,
51            description,
52            node,
53        }
54    }
55}
56
57impl Node {
58    /// The node without any [`Node::Optional`] around it.
59    #[must_use]
60    pub fn required(&self) -> &Node {
61        match self {
62            Node::Optional(inner) => inner.required(),
63            other => other,
64        }
65    }
66
67    /// The fields of an object, or of a recipient (`email`, `name`, `locale`).
68    #[must_use]
69    pub fn fields(&self) -> Option<Vec<Field>> {
70        match self.required() {
71            Node::Object(fields) => Some(fields.clone()),
72            Node::Recipient => Some(recipient_fields()),
73            _ => None,
74        }
75    }
76
77    /// A short name of the shape, as the editor's JSON writes it.
78    #[must_use]
79    pub fn type_name(&self) -> &'static str {
80        match self.required() {
81            Node::Text => "text",
82            Node::Number => "number",
83            Node::Bool => "bool",
84            Node::Date => "date",
85            Node::Recipient => "recipient",
86            Node::List(_) => "list",
87            Node::Object(_) => "object",
88            Node::Any | Node::Optional(_) => "any",
89        }
90    }
91}
92
93fn recipient_fields() -> Vec<Field> {
94    vec![
95        Field::new("email", "Email address", Node::Text),
96        Field::new("name", "Name", Node::Optional(Box::new(Node::Text))),
97        Field::new(
98            "locale",
99            "Preferred language, such as `uk` or `en`",
100            Node::Optional(Box::new(Node::Text)),
101        ),
102    ]
103}
104
105/// A type that can describe its shape to the template engine. Derive it with
106/// [`TemplateData`](crate::TemplateData) for your own structs.
107pub trait Describe {
108    /// The shape of the type's values.
109    fn describe() -> Node;
110}
111
112macro_rules! describe_as {
113    ($node:expr => $($ty:ty),* $(,)?) => {
114        $(impl Describe for $ty {
115            fn describe() -> Node {
116                $node
117            }
118        })*
119    };
120}
121
122describe_as!(Node::Text => String, str, char, std::borrow::Cow<'_, str>);
123describe_as!(Node::Number => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);
124describe_as!(Node::Bool => bool);
125describe_as!(Node::Recipient => Recipient);
126describe_as!(Node::Any => serde_json::Value);
127describe_as!(Node::Date => laravel::time::Timestamp, laravel::time::ZonedDateTime, laravel::time::civil::Date,
128    laravel::time::civil::DateTime, chrono::NaiveDate, chrono::NaiveDateTime);
129
130impl<Tz: chrono::TimeZone> Describe for chrono::DateTime<Tz> {
131    fn describe() -> Node {
132        Node::Date
133    }
134}
135
136impl<T: Describe + ?Sized> Describe for &T {
137    fn describe() -> Node {
138        T::describe()
139    }
140}
141
142impl<T: Describe + ?Sized> Describe for Box<T> {
143    fn describe() -> Node {
144        T::describe()
145    }
146}
147
148impl<T: Describe + ?Sized> Describe for Arc<T> {
149    fn describe() -> Node {
150        T::describe()
151    }
152}
153
154impl<T: Describe> Describe for Option<T> {
155    fn describe() -> Node {
156        Node::Optional(Box::new(T::describe()))
157    }
158}
159
160macro_rules! describe_list {
161    ($($ty:ty),*) => {
162        $(impl<T: Describe> Describe for $ty {
163            fn describe() -> Node {
164                Node::List(Box::new(T::describe()))
165            }
166        })*
167    };
168}
169
170describe_list!(Vec<T>, [T], VecDeque<T>, BTreeSet<T>, HashSet<T>);
171
172impl<T: Describe, const N: usize> Describe for [T; N] {
173    fn describe() -> Node {
174        Node::List(Box::new(T::describe()))
175    }
176}
177
178impl<K, V: Describe> Describe for BTreeMap<K, V> {
179    fn describe() -> Node {
180        Node::Any
181    }
182}
183
184impl<K, V: Describe, S> Describe for HashMap<K, V, S> {
185    fn describe() -> Node {
186        Node::Any
187    }
188}
189
190/// A template type: what one kind of event, such as `order.placed`, gives its templates. Derive
191/// it with [`TemplateData`](crate::TemplateData) and `#[template(key = "...", example = ...)]`;
192/// the engine finds derived types on its own.
193pub trait TemplateType: Describe + serde::Serialize + Send + Sync + 'static {
194    /// The key templates of this type are stored under, such as `order.placed`.
195    const KEY: &'static str;
196    /// What the type is for, in words for the person editing its templates.
197    const DESCRIPTION: &'static str;
198
199    /// Data for previews and test sends.
200    fn example() -> Self;
201
202    /// Templates `template-engine:install-defaults` creates when the type has none of that name.
203    fn defaults() -> Vec<DefaultTemplate>;
204}
205
206/// A template type as the engine sees it at run time.
207#[derive(Debug, Clone)]
208pub struct TypeInfo {
209    /// The type's key.
210    pub key: &'static str,
211    /// What it's for.
212    pub description: &'static str,
213    /// Its variables.
214    pub variables: Vec<Field>,
215    pub(crate) example: fn() -> serde_json::Result<serde_json::Value>,
216    pub(crate) defaults: fn() -> Vec<DefaultTemplate>,
217}
218
219impl TypeInfo {
220    /// The example data, as templates see it.
221    ///
222    /// # Errors
223    ///
224    /// Fails when the example doesn't serialize.
225    pub fn example(&self) -> laravel::Result<serde_json::Value> {
226        (self.example)()
227            .map_err(|e| laravel::Error::msg(format!("the example of `{}` doesn't serialize: {e}", self.key)))
228    }
229
230    /// The templates this type comes with.
231    #[must_use]
232    pub fn defaults(&self) -> Vec<DefaultTemplate> {
233        (self.defaults)()
234    }
235
236    /// The paths of the variables a message can be sent to, such as `customer`: fields that hold a
237    /// [`Recipient`], an optional one or a list of them, outside of other lists.
238    #[must_use]
239    pub fn recipients(&self) -> Vec<String> {
240        let mut paths = Vec::new();
241        collect_recipients(&self.variables, "", &mut paths);
242        paths
243    }
244
245    /// The variable at `path`, such as `order.number`, if the type has it.
246    #[must_use]
247    pub fn variable(&self, path: &str) -> Option<Node> {
248        let mut node = Node::Object(self.variables.clone());
249        for part in path.split('.') {
250            let fields = node.fields()?;
251            node = fields.into_iter().find(|f| f.name == part)?.node;
252        }
253        Some(node)
254    }
255
256    /// The type as JSON for an editor: the variable tree with types, descriptions and paths, the
257    /// recipient variables and the example data.
258    ///
259    /// # Errors
260    ///
261    /// Fails when the example doesn't serialize.
262    pub fn to_json(&self) -> laravel::Result<serde_json::Value> {
263        Ok(serde_json::json!({
264            "key": self.key,
265            "description": self.description,
266            "variables": fields_json(&self.variables, ""),
267            "recipients": self.recipients(),
268            "example": self.example()?,
269        }))
270    }
271}
272
273fn collect_recipients(fields: &[Field], prefix: &str, paths: &mut Vec<String>) {
274    for field in fields {
275        let path = join(prefix, field.name);
276        match field.node.required() {
277            Node::Recipient => paths.push(path),
278            Node::List(item) if *item.required() == Node::Recipient => paths.push(path),
279            Node::Object(inner) => collect_recipients(inner, &path, paths),
280            _ => {}
281        }
282    }
283}
284
285pub(crate) fn join(prefix: &str, name: &str) -> String {
286    if prefix.is_empty() {
287        name.to_owned()
288    } else {
289        format!("{prefix}.{name}")
290    }
291}
292
293#[derive(Serialize)]
294struct FieldJson {
295    name: &'static str,
296    path: String,
297    #[serde(rename = "type")]
298    kind: &'static str,
299    description: &'static str,
300    optional: bool,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    item: Option<Box<NodeJson>>,
303    #[serde(skip_serializing_if = "Option::is_none")]
304    fields: Option<Vec<FieldJson>>,
305}
306
307#[derive(Serialize)]
308struct NodeJson {
309    #[serde(rename = "type")]
310    kind: &'static str,
311    #[serde(skip_serializing_if = "Option::is_none")]
312    item: Option<Box<NodeJson>>,
313    #[serde(skip_serializing_if = "Option::is_none")]
314    fields: Option<Vec<FieldJson>>,
315}
316
317fn fields_json(fields: &[Field], prefix: &str) -> Vec<FieldJson> {
318    fields
319        .iter()
320        .map(|field| {
321            let path = join(prefix, field.name);
322            let (item, fields) = children(&field.node, &path);
323            FieldJson {
324                name: field.name,
325                kind: field.node.type_name(),
326                description: field.description,
327                optional: matches!(field.node, Node::Optional(_)),
328                path,
329                item,
330                fields,
331            }
332        })
333        .collect()
334}
335
336/// A list's items are reached through a loop variable, so their paths start again from `item`.
337fn children(node: &Node, path: &str) -> (Option<Box<NodeJson>>, Option<Vec<FieldJson>>) {
338    match node.required() {
339        Node::List(item) => {
340            let (inner_item, inner_fields) = children(item, "item");
341            let json = NodeJson {
342                kind: item.type_name(),
343                item: inner_item,
344                fields: inner_fields,
345            };
346            (Some(Box::new(json)), None)
347        }
348        other => (None, other.fields().map(|fields| fields_json(&fields, path))),
349    }
350}
351
352#[doc(hidden)]
353pub struct Registration {
354    key: &'static str,
355    description: &'static str,
356    describe: fn() -> Node,
357    example: fn() -> serde_json::Result<serde_json::Value>,
358    defaults: fn() -> Vec<DefaultTemplate>,
359}
360
361impl Registration {
362    #[must_use]
363    pub const fn of<T: TemplateType>() -> Self {
364        Self {
365            key: T::KEY,
366            description: T::DESCRIPTION,
367            describe: T::describe,
368            example: example_of::<T>,
369            defaults: T::defaults,
370        }
371    }
372
373    pub(crate) fn info(&self) -> TypeInfo {
374        let variables = match (self.describe)() {
375            Node::Object(fields) => fields,
376            _ => Vec::new(),
377        };
378        TypeInfo {
379            key: self.key,
380            description: self.description,
381            variables,
382            example: self.example,
383            defaults: self.defaults,
384        }
385    }
386}
387
388fn example_of<T: TemplateType>() -> serde_json::Result<serde_json::Value> {
389    serde_json::to_value(T::example())
390}
391
392inventory::collect!(Registration);
393
394/// Every template type in the application, sorted by key.
395#[must_use]
396pub fn types() -> Vec<TypeInfo> {
397    let mut types: Vec<TypeInfo> = inventory::iter::<Registration>().map(Registration::info).collect();
398    types.sort_by_key(|t| t.key);
399    types.dedup_by_key(|t| t.key);
400    types
401}
402
403/// The template type with `key`.
404#[must_use]
405pub fn find_type(key: &str) -> Option<TypeInfo> {
406    inventory::iter::<Registration>()
407        .find(|r| r.key == key)
408        .map(Registration::info)
409}
410
411/// The template type `T`.
412#[must_use]
413pub fn type_of<T: TemplateType>() -> TypeInfo {
414    Registration::of::<T>().info()
415}