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    /// Values read and written by forms and APIs (`value.*`).
23    Value,
24    /// Filter payloads (`dates.filter.*`).
25    Filter,
26}
27
28impl Kind {
29    /// The pattern of this kind when none is configured: `d/m/Y`, `d/m/Y h:i a` or `m/Y`.
30    #[must_use]
31    pub const fn default_pattern(self) -> &'static str {
32        match self {
33            Self::Date => "d/m/Y",
34            Self::DateTime => "d/m/Y h:i a",
35            Self::Month => "m/Y",
36        }
37    }
38
39    /// The pattern of this kind for values when none is configured: two-digit years, as older code wrote them. Pass it
40    /// as the `fallback` of [`format()`] for [`Purpose::Value`], as [`frontend_config`] does.
41    #[must_use]
42    pub const fn cast_fallback(self) -> &'static str {
43        match self {
44            Self::Date => "d/m/y",
45            Self::DateTime => "d/m/y h:i A",
46            Self::Month => "m/Y",
47        }
48    }
49}
50
51fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
52    match kind {
53        Kind::Date => patterns.date.as_ref(),
54        Kind::DateTime => patterns.date_time.as_ref(),
55        Kind::Month => patterns.month.as_ref(),
56    }
57}
58
59/// The pattern for a kind and purpose: `dates.<purpose>.<kind>`, then `dates.<kind>`, then the
60/// legacy `app.date_format_solo` / `app.date_format`, then `fallback` or the built-in default.
61///
62/// # Errors
63/// Returns [`Error::InvalidFormat`] for an empty pattern.
64pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
65    let specific = match purpose {
66        Purpose::Display => None,
67        Purpose::Value => pick(&config.value, kind),
68        Purpose::Filter => pick(&config.filter, kind),
69    };
70    let general = match kind {
71        Kind::Date => config.date.as_ref(),
72        Kind::DateTime => config.date_time.as_ref(),
73        Kind::Month => config.month.as_ref(),
74    };
75    if let Some(pattern) = specific.or(general) {
76        return require(pattern);
77    }
78    let legacy = match kind {
79        Kind::Date => config.date_format_solo.as_deref(),
80        Kind::DateTime => config.date_format.as_deref(),
81        Kind::Month => None,
82    };
83    require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
84}
85
86/// The patterns of every kind and purpose in Day.js tokens, as JSON for a frontend.
87///
88/// # Errors
89/// Returns [`Error::InvalidFormat`] for a pattern Day.js cannot express.
90pub fn frontend_config(config: &DateConfig) -> Result<Value> {
91    let mut result = json!({ "value": {}, "filter": {} });
92    for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
93        result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
94        result["value"][key] = to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
95        result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
96    }
97    Ok(result)
98}
99
100/// Translate a PHP pattern to Day.js tokens: `Y y m n d j H G h g i s a A D l M F w v O P U`, escaped literals and
101/// any non-letter. `U` needs Day.js's `advancedFormat` plugin.
102///
103/// Day.js has no way to separate two tokens other than a character that prints, so two tokens that would run into a
104/// different one are rejected: `nm` would be `MMM`, the short month name. Put a character between them.
105///
106/// ```
107/// use php_dates::formats::to_dayjs;
108///
109/// assert_eq!(to_dayjs("d/m/Y H:i")?, "DD/MM/YYYY HH:mm");
110/// assert_eq!(to_dayjs("Ymd")?, "YYYYMMDD");
111/// assert!(to_dayjs("nm").is_err());
112/// # Ok::<(), php_dates::Error>(())
113/// ```
114///
115/// # Errors
116/// [`Error::InvalidFormat`] for an empty pattern, a token Day.js cannot express, or two tokens that would be read as
117/// another one.
118pub fn to_dayjs(pattern: &str) -> Result<String> {
119    require(pattern)?;
120    let mut result = String::with_capacity(pattern.len() * 2);
121    let mut chars = pattern.chars();
122    // The Day.js token written last, while nothing has been written after it.
123    let mut previous: Option<&str> = None;
124    while let Some(character) = chars.next() {
125        let token = match character {
126            '\\' => match chars.next() {
127                Some(escaped) if escaped != '[' && escaped != ']' => {
128                    result.push('[');
129                    result.push(escaped);
130                    result.push(']');
131                    previous = None;
132                    continue;
133                }
134                _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
135            },
136            'Y' => "YYYY",
137            'y' => "YY",
138            'm' => "MM",
139            'n' => "M",
140            'd' => "DD",
141            'j' => "D",
142            'H' => "HH",
143            'G' => "H",
144            'h' => "hh",
145            'g' => "h",
146            'i' => "mm",
147            's' => "ss",
148            'a' => "a",
149            'A' => "A",
150            'D' => "ddd",
151            'l' => "dddd",
152            'M' => "MMM",
153            'F' => "MMMM",
154            'w' => "d",
155            'v' => "SSS",
156            'O' => "ZZ",
157            'P' => "Z",
158            'U' => "X",
159            other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
160                return Err(Error::argument(format!(
161                    "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
162                )));
163            }
164            other => {
165                result.push(other);
166                previous = None;
167                continue;
168            }
169        };
170        if let Some(before) = previous.filter(|before| runs_into(before, token)) {
171            return Err(Error::argument(format!(
172                "Day.js would read \"{before}{token}\" as other tokens. Put a character between them."
173            )));
174        }
175        result.push_str(token);
176        previous = Some(token);
177    }
178    Ok(result)
179}
180
181/// Whether Day.js, which takes the longest token it can from a run of one letter, would take part of `next` as part of
182/// `before`. A run is read as written only when every token but the last is as long as that letter's longest.
183fn runs_into(before: &str, next: &str) -> bool {
184    let Some(letter) = before.bytes().next() else { return false };
185    let longest = match letter {
186        b'Y' | b'M' | b'd' => 4,
187        b'S' => 3,
188        b'D' | b'H' | b'h' | b'm' | b's' | b'Z' => 2,
189        _ => 1,
190    };
191    next.bytes().next() == Some(letter) && before.len() < longest
192}
193
194fn require(pattern: &str) -> Result<String> {
195    if pattern.trim().is_empty() {
196        return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
197    }
198    Ok(pattern.to_owned())
199}