php-dates 0.2.1

PHP date() patterns for Rust: strict createFromFormat-style parsing, a pattern resolution contract and a Day.js export, with no framework dependency
Documentation
//! The date format contract: PHP patterns on the server; [`frontend_config`] exports the equivalent Day.js patterns.

use crate::{DateConfig, DatePatterns, Error, Result};
use serde_json::{Value, json};

/// Which pattern: a date, a date-time or a month/year.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// `dates.date`
    Date,
    /// `dates.dateTime`
    DateTime,
    /// `dates.month`
    Month,
}

/// What the pattern is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Purpose {
    /// Frontend display (top-level setting).
    Display,
    /// Values read and written by forms and APIs (`value.*`).
    Value,
    /// Filter payloads (`dates.filter.*`).
    Filter,
}

impl Kind {
    /// The pattern of this kind when none is configured: `d/m/Y`, `d/m/Y h:i a` or `m/Y`.
    #[must_use]
    pub const fn default_pattern(self) -> &'static str {
        match self {
            Self::Date => "d/m/Y",
            Self::DateTime => "d/m/Y h:i a",
            Self::Month => "m/Y",
        }
    }

    /// The pattern of this kind for values when none is configured: two-digit years, as older code wrote them. Pass it
    /// as the `fallback` of [`format()`] for [`Purpose::Value`], as [`frontend_config`] does.
    #[must_use]
    pub const fn cast_fallback(self) -> &'static str {
        match self {
            Self::Date => "d/m/y",
            Self::DateTime => "d/m/y h:i A",
            Self::Month => "m/Y",
        }
    }
}

fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
    match kind {
        Kind::Date => patterns.date.as_ref(),
        Kind::DateTime => patterns.date_time.as_ref(),
        Kind::Month => patterns.month.as_ref(),
    }
}

/// The pattern for a kind and purpose: `dates.<purpose>.<kind>`, then `dates.<kind>`, then the
/// legacy `app.date_format_solo` / `app.date_format`, then `fallback` or the built-in default.
///
/// # Errors
/// Returns [`Error::InvalidFormat`] for an empty pattern.
pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
    let specific = match purpose {
        Purpose::Display => None,
        Purpose::Value => pick(&config.value, kind),
        Purpose::Filter => pick(&config.filter, kind),
    };
    let general = match kind {
        Kind::Date => config.date.as_ref(),
        Kind::DateTime => config.date_time.as_ref(),
        Kind::Month => config.month.as_ref(),
    };
    if let Some(pattern) = specific.or(general) {
        return require(pattern);
    }
    let legacy = match kind {
        Kind::Date => config.date_format_solo.as_deref(),
        Kind::DateTime => config.date_format.as_deref(),
        Kind::Month => None,
    };
    require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
}

/// The patterns of every kind and purpose in Day.js tokens, as JSON for a frontend.
///
/// # Errors
/// Returns [`Error::InvalidFormat`] for a pattern Day.js cannot express.
pub fn frontend_config(config: &DateConfig) -> Result<Value> {
    let mut result = json!({ "value": {}, "filter": {} });
    for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
        result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
        result["value"][key] = to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
        result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
    }
    Ok(result)
}

/// 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
/// any non-letter. `U` needs Day.js's `advancedFormat` plugin.
///
/// Day.js has no way to separate two tokens other than a character that prints, so two tokens that would run into a
/// different one are rejected: `nm` would be `MMM`, the short month name. Put a character between them.
///
/// ```
/// use php_dates::formats::to_dayjs;
///
/// assert_eq!(to_dayjs("d/m/Y H:i")?, "DD/MM/YYYY HH:mm");
/// assert_eq!(to_dayjs("Ymd")?, "YYYYMMDD");
/// assert!(to_dayjs("nm").is_err());
/// # Ok::<(), php_dates::Error>(())
/// ```
///
/// # Errors
/// [`Error::InvalidFormat`] for an empty pattern, a token Day.js cannot express, or two tokens that would be read as
/// another one.
pub fn to_dayjs(pattern: &str) -> Result<String> {
    require(pattern)?;
    let mut result = String::with_capacity(pattern.len() * 2);
    let mut chars = pattern.chars();
    // The Day.js token written last, while nothing has been written after it.
    let mut previous: Option<&str> = None;
    while let Some(character) = chars.next() {
        let token = match character {
            '\\' => match chars.next() {
                Some(escaped) if escaped != '[' && escaped != ']' => {
                    result.push('[');
                    result.push(escaped);
                    result.push(']');
                    previous = None;
                    continue;
                }
                _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
            },
            'Y' => "YYYY",
            'y' => "YY",
            'm' => "MM",
            'n' => "M",
            'd' => "DD",
            'j' => "D",
            'H' => "HH",
            'G' => "H",
            'h' => "hh",
            'g' => "h",
            'i' => "mm",
            's' => "ss",
            'a' => "a",
            'A' => "A",
            'D' => "ddd",
            'l' => "dddd",
            'M' => "MMM",
            'F' => "MMMM",
            'w' => "d",
            'v' => "SSS",
            'O' => "ZZ",
            'P' => "Z",
            'U' => "X",
            other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
                return Err(Error::argument(format!(
                    "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
                )));
            }
            other => {
                result.push(other);
                previous = None;
                continue;
            }
        };
        if let Some(before) = previous.filter(|before| runs_into(before, token)) {
            return Err(Error::argument(format!(
                "Day.js would read \"{before}{token}\" as other tokens. Put a character between them."
            )));
        }
        result.push_str(token);
        previous = Some(token);
    }
    Ok(result)
}

/// Whether Day.js, which takes the longest token it can from a run of one letter, would take part of `next` as part of
/// `before`. A run is read as written only when every token but the last is as long as that letter's longest.
fn runs_into(before: &str, next: &str) -> bool {
    let Some(letter) = before.bytes().next() else { return false };
    let longest = match letter {
        b'Y' | b'M' | b'd' => 4,
        b'S' => 3,
        b'D' | b'H' | b'h' | b'm' | b's' | b'Z' => 2,
        _ => 1,
    };
    next.bytes().next() == Some(letter) && before.len() < longest
}

fn require(pattern: &str) -> Result<String> {
    if pattern.trim().is_empty() {
        return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
    }
    Ok(pattern.to_owned())
}