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
//! `php_dates::PhpDatePattern` over jiff's civil types, which laravel-rust columns decode into.

use crate::Result;
use laravel::time::civil::{DateTime, date};
use php_dates::{PhpDatePattern, PhpDateTime};

/// Tokens that print a number.
const NUMERIC: &str = "djmnyYgGhHisuvz";

/// Print with a pattern that is not kept, so there is no [`Pattern`] to build around it.
pub(crate) fn format_with(pattern: &str, date: &DateTime) -> Result<String> {
    Ok(PhpDatePattern::compile_strict(pattern)?.format(*date))
}

/// A compiled pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Pattern {
    source: Box<str>,
    exact: PhpDatePattern,
}

impl Pattern {
    /// A letter that is not a PHP token is an error, not a literal: it is almost always a typo.
    pub(crate) fn compile(pattern: &str) -> Result<Self> {
        Ok(Self {
            source: pattern.into(),
            exact: PhpDatePattern::compile_strict(pattern)?,
        })
    }

    /// The pattern as written.
    pub(crate) fn source(&self) -> &str {
        &self.source
    }

    pub(crate) fn format(&self, date: &DateTime) -> String {
        self.exact.format(*date)
    }

    pub(crate) fn parse(&self, text: &str) -> Option<DateTime> {
        self.exact.parse(text)
    }

    /// Like `createFromFormat('!' . $pattern, $text)`, which reads `1/2/2026` as `d/m/Y`. Unlike PHP, a date that does
    /// not exist is refused rather than rolled over, so is a `Y` year below 1000 (`5/2/26` is year 26 in PHP), and so
    /// is anything but spaces that PHP would drop to get to `AM`/`PM` (the seconds of `9:05:59 pm` for `h:i A`).
    /// Patterns with a day name (PHP moves the date to that day), a 12-hour clock without a meridiem, or two numbers
    /// with nothing between them are not read this way at all.
    ///
    /// It is the second attempt, after [`Pattern::parse`], so it is compiled only when needed.
    pub(crate) fn parse_typed(&self, text: &str) -> Option<DateTime> {
        if is_ambiguous(&self.source) {
            return None;
        }
        let typed = PhpDatePattern::compile_strict(&format!("!{}", self.source)).ok()?;
        let epoch = PhpDateTime::from(date(1970, 1, 1).at(0, 0, 0, 0));
        let parsed = *typed.parse_at(text, &epoch).ok()?.datetime();
        let short_year = letters(&self.source).any(|letter| letter == 'Y') && parsed.year() < 1000;

        (!short_year && !drops_before_meridiem(&self.source, text, &epoch)).then_some(parsed)
    }
}

/// Whether reading `text` gets to an `a` or `A` of the pattern by dropping part of it: PHP skips whatever stands before
/// the first `a` or `p`. It is the one place where `createFromFormat` throws input away without being told to.
fn drops_before_meridiem(pattern: &str, text: &str, epoch: &PhpDateTime) -> bool {
    let mut escaped = false;

    pattern.char_indices().any(|(at, letter)| {
        if escaped || letter == '\\' {
            escaped = !escaped;
            return false;
        }
        if !matches!(letter, 'a' | 'A') {
            return false;
        }
        // Reading only what comes before the meridiem stops, with data left over, where the meridiem has to start.
        let Ok(before) = PhpDatePattern::compile_strict(&format!("!{}", &pattern[..at])) else {
            return true;
        };
        before.parse_at(text, epoch).err().is_none_or(|stopped| {
            !text
                .get(stopped.position..)
                .unwrap_or_default()
                .trim_start_matches([' ', '\t', '\u{a0}', '\u{202f}'])
                .starts_with(['a', 'A', 'p', 'P'])
        })
    })
}

/// The characters of a pattern that are not escaped.
fn tokens(pattern: &str) -> impl Iterator<Item = Option<char>> {
    let mut characters = pattern.chars();

    std::iter::from_fn(move || {
        characters.next().map(|character| {
            if character == '\\' {
                characters.next();
                None
            } else {
                Some(character)
            }
        })
    })
}

fn letters(pattern: &str) -> impl Iterator<Item = char> {
    tokens(pattern).flatten()
}

fn is_ambiguous(pattern: &str) -> bool {
    let has = |wanted: &str| letters(pattern).any(|letter| wanted.contains(letter));
    let numeric = |token: Option<char>| token.is_some_and(|letter| NUMERIC.contains(letter));
    let adjacent = tokens(pattern)
        .zip(tokens(pattern).skip(1))
        .any(|(first, second)| numeric(first) && numeric(second));

    adjacent || has("Dl") || (has("gh") && !has("aA"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_and_prints_names_and_numbers() {
        let pattern = Pattern::compile("M - Y").unwrap();
        let date = pattern.parse("Feb - 2026").unwrap();
        assert_eq!(date.to_string(), "2026-02-01T00:00:00");
        assert_eq!(pattern.format(&date), "Feb - 2026");
        assert!(pattern.parse("31/02/2026").is_none());
        assert!(Pattern::compile("Y-m-d q").is_err());
    }

    #[test]
    fn typed_reading_only_forgives_what_is_not_ambiguous() {
        let read = |pattern: &str, text: &str| {
            Pattern::compile(pattern)
                .unwrap()
                .parse_typed(text)
                .map(|date| date.to_string())
        };
        assert_eq!(
            read("d/m/Y", "1/2/2026").as_deref(),
            Some("2026-02-01T00:00:00")
        );
        assert_eq!(
            read("\\D d/m/Y", "D 1/2/2026").as_deref(),
            Some("2026-02-01T00:00:00")
        );
        assert_eq!(read("Ymd", "2026111"), None);
        assert_eq!(read("D d/m/Y", "Sun 1/2/2026"), None);
        assert_eq!(read("d/m/Y h:i", "1/2/2026 9:05"), None);
        assert_eq!(read("d/m/Y", "1/2/999"), None);
    }
}