Skip to main content

php_dates/
formats.rs

1//! The date format contract: PHP patterns on the server; [`frontend_config`] exports the equivalent Day.js patterns.
2
3use crate::{DateConfig, DatePatterns, Error, Result};
4use serde_json::{Value, json};
5
6/// Which pattern: a date, a date-time or a month/year.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Kind {
9    /// `dates.date`
10    Date,
11    /// `dates.dateTime`
12    DateTime,
13    /// `dates.month`
14    Month,
15}
16
17/// What the pattern is for.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Purpose {
20    /// Frontend display (top-level setting).
21    Display,
22    /// Cast form values (`dates.value.*`).
23    Value,
24    /// Filter payloads (`dates.filter.*`).
25    Filter,
26}
27
28impl Kind {
29    const fn default_pattern(self) -> &'static str {
30        match self {
31            Self::Date => "d/m/Y",
32            Self::DateTime => "d/m/Y h:i a",
33            Self::Month => "m/Y",
34        }
35    }
36
37    /// The pattern a cast of this kind used before the shared settings existed.
38    const fn cast_fallback(self) -> &'static str {
39        match self {
40            Self::Date => "d/m/y",
41            Self::DateTime => "d/m/y h:i A",
42            Self::Month => "m/Y",
43        }
44    }
45}
46
47fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
48    match kind {
49        Kind::Date => patterns.date.as_ref(),
50        Kind::DateTime => patterns.date_time.as_ref(),
51        Kind::Month => patterns.month.as_ref(),
52    }
53}
54
55/// The pattern for a kind and purpose: `dates.<purpose>.<kind>`, then `dates.<kind>`, then the
56/// legacy `app.date_format_solo` / `app.date_format`, then `fallback` or the built-in default.
57///
58/// # Errors
59/// Returns [`Error::InvalidArgument`] for an empty pattern.
60pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
61    let specific = match purpose {
62        Purpose::Display => None,
63        Purpose::Value => pick(&config.value, kind),
64        Purpose::Filter => pick(&config.filter, kind),
65    };
66    let general = match kind {
67        Kind::Date => config.date.as_ref(),
68        Kind::DateTime => config.date_time.as_ref(),
69        Kind::Month => config.month.as_ref(),
70    };
71    if let Some(pattern) = specific.or(general) {
72        return require(pattern);
73    }
74    let legacy = match kind {
75        Kind::Date => config.date_format_solo.as_deref(),
76        Kind::DateTime => config.date_format.as_deref(),
77        Kind::Month => None,
78    };
79    require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
80}
81
82/// The shared contract for the frontend: pass the JSON to `configureUtilsDates()`.
83///
84/// # Errors
85/// Returns [`Error::InvalidArgument`] for a pattern Day.js cannot express.
86pub fn frontend_config(config: &DateConfig) -> Result<Value> {
87    let mut result = json!({ "value": {}, "filter": {} });
88    for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
89        result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
90        result["value"][key] =
91            to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
92        result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
93    }
94    Ok(result)
95}
96
97/// Translate a PHP pattern to Day.js tokens.
98///
99/// # Errors
100/// Rejects tokens Day.js cannot express instead of generating an incompatible format.
101pub fn to_dayjs(pattern: &str) -> Result<String> {
102    require(pattern)?;
103    let mut result = String::new();
104    let mut chars = pattern.chars();
105    while let Some(character) = chars.next() {
106        match character {
107            '\\' => match chars.next() {
108                Some(escaped) if escaped != '[' && escaped != ']' => {
109                    result.push('[');
110                    result.push(escaped);
111                    result.push(']');
112                }
113                _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
114            },
115            'Y' => result.push_str("YYYY"),
116            'y' => result.push_str("YY"),
117            'm' => result.push_str("MM"),
118            'n' => result.push('M'),
119            'd' => result.push_str("DD"),
120            'j' => result.push('D'),
121            'H' => result.push_str("HH"),
122            'G' => result.push('H'),
123            'h' => result.push_str("hh"),
124            'g' => result.push('h'),
125            'i' => result.push_str("mm"),
126            's' => result.push_str("ss"),
127            'a' => result.push('a'),
128            'A' => result.push('A'),
129            other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
130                return Err(Error::argument(format!(
131                    "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
132                )));
133            }
134            other => result.push(other),
135        }
136    }
137    Ok(result)
138}
139
140fn require(pattern: &str) -> Result<String> {
141    if pattern.trim().is_empty() {
142        return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
143    }
144    Ok(pattern.to_owned())
145}