laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! The built-in filters: a short list of standard ones, and `money`, `number`, `date` and `plural`
//! that follow the template's language with CLDR data.

use std::str::FromStr;

use fixed_decimal::Decimal;
use icu_decimal::DecimalFormatter;
use icu_experimental::dimension::currency::CurrencyType;
use icu_experimental::dimension::currency::formatter::CurrencyFormatter;
use icu_locale::LocaleExpander;
use icu_locale_core::Locale;
use icu_plurals::{PluralCategory, PluralRules};
use minijinja::value::Rest;
use minijinja::{Environment, Error, ErrorKind, Value};

use crate::sandbox::{Arg, ArgKind, FilterSpec, InputKind};

type Spec = (
    &'static str,
    &'static str,
    &'static str,
    &'static [(&'static str, ArgKind, bool)],
    InputKind,
);

const TEXT: ArgKind = ArgKind::Text;
const NUMBER: ArgKind = ArgKind::Number;
const ANY: ArgKind = ArgKind::Any;

#[rustfmt::skip]
const BUILTIN: &[Spec] = &[
    ("money", "An amount with its currency, as the language writes it", "{{ order.total | money(\"UAH\") }}", &[("currency", TEXT, false)], InputKind::Number),
    ("number", "A number with the language's separators", "{{ order.weight | number(2) }}", &[("decimals", NUMBER, false)], InputKind::Number),
    ("date", "A date in the given format", "{{ order.placed_at | date(\"%d.%m.%Y\") }}", &[("format", TEXT, false)], InputKind::Date),
    ("plural", "The word form that fits the number, by the language's plural rules", "{{ count }} {{ count | plural(\"item\", \"items\") }}", &[("forms", TEXT, true)], InputKind::Number),
    ("default", "A value to show when there is none or it's empty", "{{ customer.phone | default(\"—\") }}", &[("value", ANY, false)], InputKind::Any),
    ("upper", "UPPER CASE", "{{ customer.name | upper }}", &[], InputKind::Any),
    ("lower", "lower case", "{{ customer.email | lower }}", &[], InputKind::Any),
    ("title", "Each Word Capitalized", "{{ city | title }}", &[], InputKind::Any),
    ("capitalize", "First letter capitalized", "{{ note | capitalize }}", &[], InputKind::Any),
    ("trim", "Without spaces at the ends", "{{ note | trim }}", &[("characters", TEXT, false)], InputKind::Any),
    ("replace", "Replaces text", "{{ phone | replace(\" \", \"\") }}", &[("from", TEXT, true), ("to", TEXT, true), ("count", NUMBER, false)], InputKind::Any),
    ("round", "A rounded number", "{{ rating | round(1) }}", &[("precision", NUMBER, false)], InputKind::Number),
    ("abs", "A number without its sign", "{{ balance | abs }}", &[], InputKind::Number),
    ("int", "A whole number", "{{ quantity | int }}", &[], InputKind::Any),
    ("float", "A decimal number", "{{ weight | float }}", &[], InputKind::Any),
    ("length", "How many items a list has, or characters a text", "{{ order.items | length }}", &[], InputKind::Any),
    ("first", "A list's first item", "{{ order.items | first }}", &[], InputKind::Any),
    ("last", "A list's last item", "{{ order.items | last }}", &[], InputKind::Any),
    ("join", "A list's items in one text", "{{ tags | join(\", \") }}", &[("separator", TEXT, false)], InputKind::Any),
    ("sort", "A sorted list", "{{ names | sort }}", &[], InputKind::Any),
    ("reverse", "A list in reverse order", "{{ items | reverse }}", &[], InputKind::Any),
    ("sum", "The sum of a list's numbers", "{{ amounts | sum }}", &[], InputKind::Any),
    ("min", "A list's smallest item", "{{ prices | min }}", &[], InputKind::Any),
    ("max", "A list's largest item", "{{ prices | max }}", &[], InputKind::Any),
    ("unique", "A list without repeats", "{{ cities | unique }}", &[], InputKind::Any),
    ("string", "The value as text", "{{ code | string }}", &[], InputKind::Any),
];

/// The built-in filters, for the checks and the cheat sheet.
#[must_use]
pub fn builtin() -> Vec<FilterSpec> {
    BUILTIN
        .iter()
        .map(|&(name, description, example, args, input)| FilterSpec {
            name,
            description,
            example,
            args: args
                .iter()
                .map(|&(name, kind, required)| Arg { name, kind, required })
                .collect(),
            input,
        })
        .collect()
}

pub(crate) fn register(env: &mut Environment<'static>, locale: &str, currency: &str) {
    env.add_filter("upper", minijinja::filters::upper);
    env.add_filter("lower", minijinja::filters::lower);
    env.add_filter("title", minijinja::filters::title);
    env.add_filter("capitalize", minijinja::filters::capitalize);
    env.add_filter("trim", minijinja::filters::trim);
    env.add_filter("replace", minijinja::filters::replace);
    env.add_filter("default", |value: Value, fallback: Option<Value>| {
        let missing = value.is_undefined() || value.is_none() || value.as_str().is_some_and(|s| s.trim().is_empty());
        if missing {
            fallback.unwrap_or_else(|| Value::from(""))
        } else {
            value
        }
    });
    env.add_filter("round", minijinja::filters::round);
    env.add_filter("abs", minijinja::filters::abs);
    env.add_filter("int", minijinja::filters::int);
    env.add_filter("float", minijinja::filters::float);
    env.add_filter("length", minijinja::filters::length);
    env.add_filter("first", minijinja::filters::first);
    env.add_filter("last", minijinja::filters::last);
    env.add_filter("join", minijinja::filters::join);
    env.add_filter("sort", minijinja::filters::sort);
    env.add_filter("reverse", minijinja::filters::reverse);
    env.add_filter("sum", minijinja::filters::sum);
    env.add_filter("min", minijinja::filters::min);
    env.add_filter("max", minijinja::filters::max);
    env.add_filter("unique", minijinja::filters::unique);
    env.add_filter("string", minijinja::filters::string);

    let lang = locale.to_owned();
    let default_currency = currency.to_owned();
    env.add_filter("money", move |value: Value, currency: Option<String>| {
        money(&lang, &value, currency.as_deref().unwrap_or(&default_currency)).map_err(invalid)
    });
    let lang = locale.to_owned();
    env.add_filter("number", move |value: Value, decimals: Option<i16>| {
        number(&lang, &value, decimals).map_err(invalid)
    });
    let lang = locale.to_owned();
    env.add_filter("date", move |value: Value, format: Option<String>| {
        date(&lang, &value, format.as_deref().unwrap_or("%x")).map_err(invalid)
    });
    let lang = locale.to_owned();
    env.add_filter("plural", move |value: Value, forms: Rest<String>| {
        plural(&lang, &value, &forms).map_err(invalid)
    });
}

fn invalid(message: String) -> Error {
    Error::new(ErrorKind::InvalidOperation, message)
}

/// `uk`, `en-GB` or `pt_BR` as an ICU locale; the root locale when it doesn't parse.
pub(crate) fn icu_locale(locale: &str) -> Locale {
    Locale::try_from_str(&locale.replace('_', "-")).unwrap_or(icu_locale_core::locale!("und"))
}

fn decimal(value: &Value) -> Result<Decimal, String> {
    let text = value.to_string();
    if let Ok(number) = Decimal::from_str(&text) {
        return Ok(number);
    }
    // Floats such as `1e-7` and values that only look numeric.
    let float: f64 = text.parse().map_err(|_| format!("`{text}` isn't a number"))?;
    if !float.is_finite() {
        return Err(format!("`{text}` isn't a number"));
    }
    Decimal::from_str(&format!("{float}")).map_err(|_| format!("`{text}` isn't a number"))
}

pub(crate) fn money(locale: &str, value: &Value, currency: &str) -> Result<String, String> {
    let code = currency.trim().to_ascii_uppercase();
    let invalid = || format!("`{currency}` isn't a currency code such as UAH, EUR or USD");
    if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_uppercase()) {
        return Err(invalid());
    }
    let code = CurrencyType::try_from_str(&code).map_err(|_| invalid())?;
    let mut amount = decimal(value)?;
    amount.round(-2);
    amount.pad_end(-2);
    let formatter = CurrencyFormatter::try_new_symbol(
        (&icu_locale(locale)).into(),
        code,
        icu_experimental::dimension::currency::options::CurrencyFormatterOptions::default(),
    )
    .map_err(|e| e.to_string())?;
    Ok(formatter.format_fixed_decimal(&amount).to_string())
}

pub(crate) fn number(locale: &str, value: &Value, decimals: Option<i16>) -> Result<String, String> {
    let mut amount = decimal(value)?;
    if let Some(decimals) = decimals {
        amount.round(-decimals);
        amount.pad_end(-decimals);
    }
    let formatter = DecimalFormatter::try_new(
        icu_locale(locale).into(),
        icu_decimal::options::DecimalFormatterOptions::default(),
    )
    .map_err(|e| e.to_string())?;
    Ok(formatter.format(&amount).to_string())
}

pub(crate) fn date(locale: &str, value: &Value, format: &str) -> Result<String, String> {
    check_date_format(format)?;
    let text = value.to_string();
    let chrono_locale = chrono_locale(locale);
    if let Some(moment) = parse_date_time(&text) {
        return Ok(moment.format_localized(format, chrono_locale).to_string());
    }
    if let Ok(day) = chrono::NaiveDate::parse_from_str(&text, "%Y-%m-%d") {
        return Ok(day.format_localized(format, chrono_locale).to_string());
    }
    Err(format!("`{text}` isn't a date"))
}

/// Dates come as RFC 3339 (`Timestamp`, chrono's `DateTime`), with a time zone in brackets
/// (`ZonedDateTime`), or without an offset (`civil::DateTime`, `NaiveDateTime`).
fn parse_date_time(text: &str) -> Option<chrono::DateTime<chrono::FixedOffset>> {
    let text = text.split('[').next().unwrap_or(text);
    if let Ok(moment) = chrono::DateTime::parse_from_rfc3339(text) {
        return Some(moment);
    }
    for format in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M"] {
        if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(text, format) {
            return Some(naive.and_utc().fixed_offset());
        }
    }
    None
}

/// Fails on a format chrono can't read, such as `%Q`.
pub(crate) fn check_date_format(format: &str) -> Result<(), String> {
    use chrono::format::{Item, StrftimeItems};
    if StrftimeItems::new(format).any(|item| matches!(item, Item::Error)) {
        return Err(format!(
            "`{format}` isn't a date format; use codes such as %d, %m, %Y, %H:%M"
        ));
    }
    Ok(())
}

/// chrono's locale for a language: `uk` becomes `uk_UA` through CLDR's likely subtags.
fn chrono_locale(locale: &str) -> chrono::Locale {
    let mut icu = icu_locale(locale);
    LocaleExpander::new_common().maximize(&mut icu.id);
    let language = icu.id.language.as_str().to_owned();
    let candidates = [
        icu.id.region.map(|region| format!("{language}_{}", region.as_str())),
        Some(language),
    ];
    candidates
        .into_iter()
        .flatten()
        .find_map(|name| chrono::Locale::try_from(name.as_str()).ok())
        .unwrap_or(chrono::Locale::POSIX)
}

/// The plural categories whole numbers fall into, in CLDR's order: `one`, `few`, `many` for
/// Ukrainian, `one`, `other` for English. The template gives one form for each.
pub(crate) fn plural_categories(locale: &str) -> Result<Vec<PluralCategory>, String> {
    let rules = PluralRules::try_new_cardinal(icu_locale(locale).into()).map_err(|e| e.to_string())?;
    let mut used: Vec<PluralCategory> = Vec::new();
    for n in 0u32..=1000 {
        let category = rules.category_for(n);
        if !used.contains(&category) {
            used.push(category);
        }
    }
    Ok(rules.categories().filter(|c| used.contains(c)).collect())
}

pub(crate) fn plural(locale: &str, value: &Value, forms: &[String]) -> Result<String, String> {
    let Some(last) = forms.last() else {
        return Err("plural needs the word's forms, such as plural(\"item\", \"items\")".to_owned());
    };
    let rules = PluralRules::try_new_cardinal(icu_locale(locale).into()).map_err(|e| e.to_string())?;
    let amount = decimal(value)?;
    let category = rules.category_for(&amount);
    let index = plural_categories(locale)?.iter().position(|c| *c == category);
    Ok(index.and_then(|i| forms.get(i)).unwrap_or(last).clone())
}

/// The CLDR name of a plural category, for messages.
pub(crate) fn category_name(category: PluralCategory) -> &'static str {
    match category {
        PluralCategory::Zero => "zero",
        PluralCategory::One => "one",
        PluralCategory::Two => "two",
        PluralCategory::Few => "few",
        PluralCategory::Many => "many",
        PluralCategory::Other => "other",
    }
}