laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! What a template type's variables look like: the tree the editor shows and the checks use.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::sync::Arc;

use serde::Serialize;

use crate::Recipient;
use crate::defaults::DefaultTemplate;

/// The shape of a value a template can read.
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
    /// Text.
    Text,
    /// A whole or decimal number.
    Number,
    /// `true` or `false`.
    Bool,
    /// A date or a date and time, given to templates as ISO 8601 text.
    Date,
    /// Someone a message can go to: `email`, `name` and `locale`.
    Recipient,
    /// A value that may be missing.
    Optional(Box<Node>),
    /// A list of values of one shape, for `{% for %}`.
    List(Box<Node>),
    /// Named fields.
    Object(Vec<Field>),
    /// Anything: the checks don't look inside.
    Any,
}

/// A named field of an object.
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
    /// The name templates use.
    pub name: &'static str,
    /// What the field holds, in words for the person editing the template.
    pub description: &'static str,
    /// The field's shape.
    pub node: Node,
}

impl Field {
    /// A field. The derive macro writes these.
    #[must_use]
    pub fn new(name: &'static str, description: &'static str, node: Node) -> Self {
        Self {
            name,
            description,
            node,
        }
    }
}

impl Node {
    /// The node without any [`Node::Optional`] around it.
    #[must_use]
    pub fn required(&self) -> &Node {
        match self {
            Node::Optional(inner) => inner.required(),
            other => other,
        }
    }

    /// The fields of an object, or of a recipient (`email`, `name`, `locale`).
    #[must_use]
    pub fn fields(&self) -> Option<Vec<Field>> {
        match self.required() {
            Node::Object(fields) => Some(fields.clone()),
            Node::Recipient => Some(recipient_fields()),
            _ => None,
        }
    }

    /// A short name of the shape, as the editor's JSON writes it.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        match self.required() {
            Node::Text => "text",
            Node::Number => "number",
            Node::Bool => "bool",
            Node::Date => "date",
            Node::Recipient => "recipient",
            Node::List(_) => "list",
            Node::Object(_) => "object",
            Node::Any | Node::Optional(_) => "any",
        }
    }
}

fn recipient_fields() -> Vec<Field> {
    vec![
        Field::new("email", "Email address", Node::Text),
        Field::new("name", "Name", Node::Optional(Box::new(Node::Text))),
        Field::new(
            "locale",
            "Preferred language, such as `uk` or `en`",
            Node::Optional(Box::new(Node::Text)),
        ),
    ]
}

/// A type that can describe its shape to the template engine. Derive it with
/// [`TemplateData`](crate::TemplateData) for your own structs.
pub trait Describe {
    /// The shape of the type's values.
    fn describe() -> Node;
}

macro_rules! describe_as {
    ($node:expr => $($ty:ty),* $(,)?) => {
        $(impl Describe for $ty {
            fn describe() -> Node {
                $node
            }
        })*
    };
}

describe_as!(Node::Text => String, str, char, std::borrow::Cow<'_, str>);
describe_as!(Node::Number => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64);
describe_as!(Node::Bool => bool);
describe_as!(Node::Recipient => Recipient);
describe_as!(Node::Any => serde_json::Value);
describe_as!(Node::Date => laravel::time::Timestamp, laravel::time::ZonedDateTime, laravel::time::civil::Date,
    laravel::time::civil::DateTime, chrono::NaiveDate, chrono::NaiveDateTime);

impl<Tz: chrono::TimeZone> Describe for chrono::DateTime<Tz> {
    fn describe() -> Node {
        Node::Date
    }
}

impl<T: Describe + ?Sized> Describe for &T {
    fn describe() -> Node {
        T::describe()
    }
}

impl<T: Describe + ?Sized> Describe for Box<T> {
    fn describe() -> Node {
        T::describe()
    }
}

impl<T: Describe + ?Sized> Describe for Arc<T> {
    fn describe() -> Node {
        T::describe()
    }
}

impl<T: Describe> Describe for Option<T> {
    fn describe() -> Node {
        Node::Optional(Box::new(T::describe()))
    }
}

macro_rules! describe_list {
    ($($ty:ty),*) => {
        $(impl<T: Describe> Describe for $ty {
            fn describe() -> Node {
                Node::List(Box::new(T::describe()))
            }
        })*
    };
}

describe_list!(Vec<T>, [T], VecDeque<T>, BTreeSet<T>, HashSet<T>);

impl<T: Describe, const N: usize> Describe for [T; N] {
    fn describe() -> Node {
        Node::List(Box::new(T::describe()))
    }
}

impl<K, V: Describe> Describe for BTreeMap<K, V> {
    fn describe() -> Node {
        Node::Any
    }
}

impl<K, V: Describe, S> Describe for HashMap<K, V, S> {
    fn describe() -> Node {
        Node::Any
    }
}

/// A template type: what one kind of event, such as `order.placed`, gives its templates. Derive
/// it with [`TemplateData`](crate::TemplateData) and `#[template(key = "...", example = ...)]`;
/// the engine finds derived types on its own.
pub trait TemplateType: Describe + serde::Serialize + Send + Sync + 'static {
    /// The key templates of this type are stored under, such as `order.placed`.
    const KEY: &'static str;
    /// What the type is for, in words for the person editing its templates.
    const DESCRIPTION: &'static str;

    /// Data for previews and test sends.
    fn example() -> Self;

    /// Templates `template-engine:install-defaults` creates when the type has none of that name.
    fn defaults() -> Vec<DefaultTemplate>;
}

/// A template type as the engine sees it at run time.
#[derive(Debug, Clone)]
pub struct TypeInfo {
    /// The type's key.
    pub key: &'static str,
    /// What it's for.
    pub description: &'static str,
    /// Its variables.
    pub variables: Vec<Field>,
    pub(crate) example: fn() -> serde_json::Result<serde_json::Value>,
    pub(crate) defaults: fn() -> Vec<DefaultTemplate>,
}

impl TypeInfo {
    /// The example data, as templates see it.
    ///
    /// # Errors
    ///
    /// Fails when the example doesn't serialize.
    pub fn example(&self) -> laravel::Result<serde_json::Value> {
        (self.example)()
            .map_err(|e| laravel::Error::msg(format!("the example of `{}` doesn't serialize: {e}", self.key)))
    }

    /// The templates this type comes with.
    #[must_use]
    pub fn defaults(&self) -> Vec<DefaultTemplate> {
        (self.defaults)()
    }

    /// The paths of the variables a message can be sent to, such as `customer`: fields that hold a
    /// [`Recipient`], an optional one or a list of them, outside of other lists.
    #[must_use]
    pub fn recipients(&self) -> Vec<String> {
        let mut paths = Vec::new();
        collect_recipients(&self.variables, "", &mut paths);
        paths
    }

    /// The variable at `path`, such as `order.number`, if the type has it.
    #[must_use]
    pub fn variable(&self, path: &str) -> Option<Node> {
        let mut node = Node::Object(self.variables.clone());
        for part in path.split('.') {
            let fields = node.fields()?;
            node = fields.into_iter().find(|f| f.name == part)?.node;
        }
        Some(node)
    }

    /// The type as JSON for an editor: the variable tree with types, descriptions and paths, the
    /// recipient variables and the example data.
    ///
    /// # Errors
    ///
    /// Fails when the example doesn't serialize.
    pub fn to_json(&self) -> laravel::Result<serde_json::Value> {
        Ok(serde_json::json!({
            "key": self.key,
            "description": self.description,
            "variables": fields_json(&self.variables, ""),
            "recipients": self.recipients(),
            "example": self.example()?,
        }))
    }
}

fn collect_recipients(fields: &[Field], prefix: &str, paths: &mut Vec<String>) {
    for field in fields {
        let path = join(prefix, field.name);
        match field.node.required() {
            Node::Recipient => paths.push(path),
            Node::List(item) if *item.required() == Node::Recipient => paths.push(path),
            Node::Object(inner) => collect_recipients(inner, &path, paths),
            _ => {}
        }
    }
}

pub(crate) fn join(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_owned()
    } else {
        format!("{prefix}.{name}")
    }
}

#[derive(Serialize)]
struct FieldJson {
    name: &'static str,
    path: String,
    #[serde(rename = "type")]
    kind: &'static str,
    description: &'static str,
    optional: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    item: Option<Box<NodeJson>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fields: Option<Vec<FieldJson>>,
}

#[derive(Serialize)]
struct NodeJson {
    #[serde(rename = "type")]
    kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    item: Option<Box<NodeJson>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fields: Option<Vec<FieldJson>>,
}

fn fields_json(fields: &[Field], prefix: &str) -> Vec<FieldJson> {
    fields
        .iter()
        .map(|field| {
            let path = join(prefix, field.name);
            let (item, fields) = children(&field.node, &path);
            FieldJson {
                name: field.name,
                kind: field.node.type_name(),
                description: field.description,
                optional: matches!(field.node, Node::Optional(_)),
                path,
                item,
                fields,
            }
        })
        .collect()
}

/// A list's items are reached through a loop variable, so their paths start again from `item`.
fn children(node: &Node, path: &str) -> (Option<Box<NodeJson>>, Option<Vec<FieldJson>>) {
    match node.required() {
        Node::List(item) => {
            let (inner_item, inner_fields) = children(item, "item");
            let json = NodeJson {
                kind: item.type_name(),
                item: inner_item,
                fields: inner_fields,
            };
            (Some(Box::new(json)), None)
        }
        other => (None, other.fields().map(|fields| fields_json(&fields, path))),
    }
}

#[doc(hidden)]
pub struct Registration {
    key: &'static str,
    description: &'static str,
    describe: fn() -> Node,
    example: fn() -> serde_json::Result<serde_json::Value>,
    defaults: fn() -> Vec<DefaultTemplate>,
}

impl Registration {
    #[must_use]
    pub const fn of<T: TemplateType>() -> Self {
        Self {
            key: T::KEY,
            description: T::DESCRIPTION,
            describe: T::describe,
            example: example_of::<T>,
            defaults: T::defaults,
        }
    }

    pub(crate) fn info(&self) -> TypeInfo {
        let variables = match (self.describe)() {
            Node::Object(fields) => fields,
            _ => Vec::new(),
        };
        TypeInfo {
            key: self.key,
            description: self.description,
            variables,
            example: self.example,
            defaults: self.defaults,
        }
    }
}

fn example_of<T: TemplateType>() -> serde_json::Result<serde_json::Value> {
    serde_json::to_value(T::example())
}

inventory::collect!(Registration);

/// Every template type in the application, sorted by key.
#[must_use]
pub fn types() -> Vec<TypeInfo> {
    let mut types: Vec<TypeInfo> = inventory::iter::<Registration>().map(Registration::info).collect();
    types.sort_by_key(|t| t.key);
    types.dedup_by_key(|t| t.key);
    types
}

/// The template type with `key`.
#[must_use]
pub fn find_type(key: &str) -> Option<TypeInfo> {
    inventory::iter::<Registration>()
        .find(|r| r.key == key)
        .map(Registration::info)
}

/// The template type `T`.
#[must_use]
pub fn type_of<T: TemplateType>() -> TypeInfo {
    Registration::of::<T>().info()
}