laravel-casts 0.2.0

Eloquent-style attribute casts for laravel-rust models: DateCast and DateTimeCast read, write and serialize a date column in a PHP format
Documentation
//! Process-wide cast settings. `Decode`, `Serialize` and `Deserialize` receive no application
//! context, so the patterns live here; call [`configure`] once while the application boots.

use crate::Result;
use crate::kind::Kind;
use crate::pattern::Pattern;
use php_dates::{DateConfig, Purpose, formats};
use std::sync::{Arc, LazyLock, RwLock};

/// The patterns of a configuration, compiled once.
struct Patterns {
    date: Arc<Pattern>,
    date_time: Arc<Pattern>,
}

impl Patterns {
    fn compile(config: &DateConfig) -> Result<Self> {
        let compile = |kind| Pattern::compile(&resolve(config, kind)?).map(Arc::new);

        Ok(Self {
            date: compile(Kind::Date)?,
            date_time: compile(Kind::DateTime)?,
        })
    }

    fn get(&self, kind: Kind) -> Arc<Pattern> {
        Arc::clone(match kind {
            Kind::Date => &self.date,
            Kind::DateTime => &self.date_time,
        })
    }
}

static CONFIG: RwLock<Option<Patterns>> = RwLock::new(None);

static DEFAULTS: LazyLock<Patterns> = LazyLock::new(|| {
    Patterns::compile(&DateConfig::default())
        .unwrap_or_else(|error| panic!("laravel-casts: {error}"))
});

/// Replace the settings. Patterns are validated first, so a bad one fails at boot, not on a row.
///
/// The setting is one for the whole process: the last call wins, for every application in it. It is safe to call
/// while other threads read, but the setting is read once for each value, not once for each document: a response
/// being written during a call can carry values of both. Call it before serving.
///
/// A pattern that prints but cannot be read back (`Y-W`) is accepted, because a cast without
/// [`Parsed`](crate::Parsed) only prints with it. Check the ones that read with
/// [`Cast::check_format`](crate::Cast::check_format).
///
/// Without a call, dates are `d/m/y` and `d/m/y h:i A`. Those lose information: a two-digit year reads as 1970 to
/// 2069 (`1965` comes back as `2065`) and there are no seconds. Prefer `Y` in forms that send the value back.
///
/// # Errors
/// Returns [`php_dates::Error`] for a pattern that is empty or uses an unsupported token.
pub fn configure(config: DateConfig) -> Result<()> {
    let patterns = Patterns::compile(&config)?;
    *CONFIG
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(patterns);
    Ok(())
}

/// `dates.value.<kind>`, then `dates.<kind>`, then the legacy `app.date_format*`, then the cast's
/// own historical pattern.
fn resolve(config: &DateConfig, kind: Kind) -> Result<String> {
    let (kind, fallback) = match kind {
        Kind::Date => (php_dates::Kind::Date, "d/m/y"),
        Kind::DateTime => (php_dates::Kind::DateTime, "d/m/y h:i A"),
    };
    formats::format(config, kind, Purpose::Value, Some(fallback))
}

/// The pattern in effect for a kind. A bad pattern cannot be here: [`configure`] rejects it.
pub(crate) fn pattern(kind: Kind) -> Arc<Pattern> {
    CONFIG
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .as_ref()
        .unwrap_or(&DEFAULTS)
        .get(kind)
}

/// The pattern a column of this kind is stored with.
pub(crate) fn storage(kind: Kind) -> &'static Pattern {
    static DATE: LazyLock<Pattern> = LazyLock::new(|| builtin(Kind::Date));
    static DATE_TIME: LazyLock<Pattern> = LazyLock::new(|| builtin(Kind::DateTime));

    match kind {
        Kind::Date => &DATE,
        Kind::DateTime => &DATE_TIME,
    }
}

fn builtin(kind: Kind) -> Pattern {
    Pattern::compile(kind.storage()).unwrap_or_else(|error| panic!("laravel-casts: {error}"))
}