php-dates 0.2.0

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 {
    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.
    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::InvalidArgument`] 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::InvalidArgument`] 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.
///
/// # Errors
/// Rejects tokens Day.js cannot express instead of generating an incompatible format.
pub fn to_dayjs(pattern: &str) -> Result<String> {
    require(pattern)?;
    let mut result = String::new();
    let mut chars = pattern.chars();
    while let Some(character) = chars.next() {
        match character {
            '\\' => match chars.next() {
                Some(escaped) if escaped != '[' && escaped != ']' => {
                    result.push('[');
                    result.push(escaped);
                    result.push(']');
                }
                _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
            },
            'Y' => result.push_str("YYYY"),
            'y' => result.push_str("YY"),
            'm' => result.push_str("MM"),
            'n' => result.push('M'),
            'd' => result.push_str("DD"),
            'j' => result.push('D'),
            'H' => result.push_str("HH"),
            'G' => result.push('H'),
            'h' => result.push_str("hh"),
            'g' => result.push('h'),
            'i' => result.push_str("mm"),
            's' => result.push_str("ss"),
            'a' => result.push('a'),
            'A' => result.push('A'),
            'D' => result.push_str("ddd"),
            'l' => result.push_str("dddd"),
            'M' => result.push_str("MMM"),
            'F' => result.push_str("MMMM"),
            'w' => result.push('d'),
            'v' => result.push_str("SSS"),
            'O' => result.push_str("ZZ"),
            'P' => result.push('Z'),
            'U' => result.push('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),
        }
    }
    Ok(result)
}

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())
}