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
use crate::config;
use crate::kind::{DateAndTime, DateOnly, Format, Kind, Storage, midnight};
use crate::pattern::{Pattern, format_with};
use crate::{CastError, ColumnCast};
use laravel::db::{AnyRow, Decode, Nullable, Value};
use laravel::time::Timestamp;
use laravel::time::civil::{Date, DateTime, date};
use laravel::time::tz::TimeZone;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

/// A date column that reads with its storage format, writes the same, and serializes with the
/// configured display pattern. Use [`DateCast`] and [`DateTimeCast`] as field types.
pub struct Cast<S, F = crate::Configured> {
    value: DateTime,
    /// `S::KIND`, kept here so that equality and hashing need no bound on `S`.
    kind: Kind,
    marker: PhantomData<fn() -> (S, F)>,
}

/// `Casts\DateCast`: a `DATE` column. `DateCast<Parsed>` is `DateCast::SETPARSED`,
/// `DateCast<MonthYear>` is `DateCast::SETONLYMONTHYEAR`.
pub type DateCast<F = crate::Configured> = Cast<DateOnly, F>;
/// `Casts\DateTimeCast`: a `DATETIME` column.
pub type DateTimeCast<F = crate::Configured> = Cast<DateAndTime, F>;

impl<S: Storage, F: Format> Cast<S, F> {
    /// Wrap a date-time. A [`DateCast`] holds the day: the time is not stored, printed or compared.
    #[must_use]
    pub const fn new(value: DateTime) -> Self {
        Self {
            value,
            kind: S::KIND,
            marker: PhantomData,
        }
    }

    /// The date and time given to [`Cast::new`]. A [`DateCast`] read from a column or a request is at midnight.
    #[must_use]
    pub const fn datetime(&self) -> DateTime {
        self.value
    }

    /// The stored date.
    #[must_use]
    pub fn date(&self) -> Date {
        self.value.date()
    }

    /// Format with any PHP pattern, as `$model->date->format('d/m')` does in Carbon.
    ///
    /// # Errors
    /// Returns [`crate::Error`] for a pattern that is not supported.
    pub fn format(&self, pattern: &str) -> crate::Result<String> {
        format_with(pattern, &self.moment())
    }

    /// Check that the patterns of this cast work, at boot or in a test, instead of on the first request: both
    /// compile and, with [`Format::PARSE_SET`], what the `set` pattern prints it can also read. Call it after
    /// [`crate::configure`].
    ///
    /// ```
    /// use laravel_casts::{DateCast, DateTimeCast, Parsed};
    ///
    /// DateCast::<Parsed>::check_format()?;
    /// laravel_casts::date_format!(Week, "Y-W");
    /// assert!(DateTimeCast::<Week>::check_format().is_err()); // `createFromFormat` does not read `W`.
    /// # Ok::<_, laravel_casts::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns [`crate::Error`] for a pattern that is not supported or that cannot be read back.
    pub fn check_format() -> crate::Result<()> {
        pattern_of(F::get(), S::KIND)?;
        if F::PARSE_SET {
            let set = pattern_of(F::set(), S::KIND)?;
            let sample = date(2026, 11, 28).at(23, 45, 56, 0);
            if set.parse(&set.format(&sample)).is_none() {
                return Err(crate::Error::InvalidFormat(format!(
                    "the date pattern \"{}\" cannot read back what it prints",
                    set.source()
                )));
            }
        }
        Ok(())
    }

    /// PHP `get`: the cast's own display pattern, or the configured one.
    fn display(&self) -> crate::Result<String> {
        let moment = self.moment();
        match F::get() {
            Some(own) => format_with(own, &moment),
            None => Ok(config::pattern(S::KIND).format(&moment)),
        }
    }

    /// A value that was read: a `DATE` is at midnight, whatever the text that gave it said of the time.
    fn read(value: DateTime) -> Self {
        Self::new(match S::KIND {
            Kind::Date => midnight(value.date()),
            Kind::DateTime => value,
        })
    }

    /// The storage format, `Y-m-d` or `Y-m-d H:i:s`, with `.ffffff` when there are microseconds.
    pub(crate) fn canonical(&self) -> String {
        let moment = self.moment();
        let stored = config::storage(S::KIND).format(&moment);
        match moment.subsec_nanosecond() / 1_000 {
            0 => stored,
            micros => format!("{stored}.{micros:06}"),
        }
    }

    /// The storage format, or what `Serialize` shows (the form 0.1.0 left in JSON that was persisted), read exactly.
    pub(crate) fn from_canonical(text: &str) -> Result<Self, CastError> {
        let stored = config::storage(S::KIND);
        let value = match stored
            .parse(text)
            .or_else(|| with_microseconds::<S>(text, stored))
        {
            Some(value) => Some(value),
            None => pattern_of(F::get(), S::KIND)?.parse(text),
        };
        value.map(Self::read).ok_or_else(|| {
            CastError::Rejected(format!(
                "\"{text}\" is not a valid date in the format {}",
                stored.source()
            ))
        })
    }

    /// PHP `set`: the value of the incoming request, or `None` when it does not parse. A custom
    /// [`Format`] is not vetted by [`crate::configure`], so a bad pattern is an error here.
    fn parse(text: &str) -> crate::Result<Option<Self>> {
        let storage = config::storage(S::KIND);
        let parsed = if F::PARSE_SET {
            let set = pattern_of(F::set(), S::KIND)?;
            set.parse(text)
                .or_else(|| storage.parse(text))
                .or_else(|| set.parse_typed(text))
        } else {
            storage.parse(text)
        };
        Ok(parsed.map(Self::read))
    }
}

// The column traits and serde of a date cast are written here, over any `Storage`, as 0.1.0 published them.

impl<S: Storage, F: Format> Decode for Cast<S, F> {
    fn decode(row: &AnyRow, index: usize) -> laravel::Result<Self> {
        Ok(match S::KIND {
            Kind::Date => Self::new(midnight(Date::decode(row, index)?)),
            Kind::DateTime => Self::new(DateTime::decode(row, index)?),
        })
    }
}

impl<S: Storage, F: Format> Nullable for Cast<S, F> {
    fn null() -> Value<'static> {
        match S::KIND {
            Kind::Date => Value::Date(None),
            Kind::DateTime => Value::DateTime(None),
        }
    }
}

impl<S: Storage, F: Format> From<Cast<S, F>> for Value<'_> {
    fn from(cast: Cast<S, F>) -> Self {
        match S::KIND {
            Kind::Date => Value::Date(Some(cast.value.date())),
            Kind::DateTime => Value::DateTime(Some(cast.value)),
        }
    }
}

impl<'a, S: Storage, F: Format> From<&'a Cast<S, F>> for Value<'a> {
    fn from(cast: &'a Cast<S, F>) -> Self {
        (*cast).into()
    }
}

impl<'a, S: Storage, F: Format> From<&&'a Cast<S, F>> for Value<'a> {
    fn from(cast: &&'a Cast<S, F>) -> Self {
        (**cast).into()
    }
}

impl<S: Storage, F: Format> Serialize for Cast<S, F> {
    fn serialize<T: Serializer>(&self, serializer: T) -> Result<T::Ok, T::Error> {
        serializer.serialize_str(&self.display().map_err(serde::ser::Error::custom)?)
    }
}

impl<'de, S: Storage, F: Format> Deserialize<'de> for Cast<S, F> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::parse(&text)
            .map_err(de::Error::custom)?
            .ok_or_else(|| {
                de::Error::custom(format!("\"{text}\" is not a valid {}", Self::expected()))
            })
    }
}

impl<F: Format> ColumnCast for Cast<DateOnly, F> {
    type Repr = Date;

    fn from_repr(date: Date) -> Result<Self, CastError> {
        Ok(date.into())
    }

    fn to_repr(&self) -> Date {
        self.value.date()
    }
}

impl<F: Format> ColumnCast for Cast<DateAndTime, F> {
    type Repr = DateTime;

    fn from_repr(value: DateTime) -> Result<Self, CastError> {
        Ok(value.into())
    }

    fn to_repr(&self) -> DateTime {
        self.value
    }
}

impl<S: Storage, F: Format> Cast<S, F> {
    fn expected() -> String {
        let pattern = match (F::PARSE_SET, F::set()) {
            (false, _) => S::KIND.storage().to_owned(),
            (true, Some(own)) => own.to_owned(),
            (true, None) => config::pattern(S::KIND).source().to_owned(),
        };
        format!("date in the format {pattern}")
    }
}

/// The storage format of a `DATETIME` followed by `.` and exactly six digits, as [`Cast::canonical`] writes it.
fn with_microseconds<S: Storage>(text: &str, stored: &Pattern) -> Option<DateTime> {
    let (seconds, fraction) = text.rsplit_once('.')?;
    if S::KIND != Kind::DateTime
        || fraction.len() != 6
        || !fraction.bytes().all(|byte| byte.is_ascii_digit())
    {
        return None;
    }
    let nanoseconds = fraction.parse::<i32>().ok()? * 1_000;

    stored
        .parse(seconds)?
        .with()
        .subsec_nanosecond(nanoseconds)
        .build()
        .ok()
}

/// A cast's own pattern, or the configured one.
fn pattern_of(own: Option<&str>, kind: Kind) -> crate::Result<Arc<Pattern>> {
    match own {
        Some(own) => Pattern::compile(own).map(Arc::new),
        None => Ok(config::pattern(kind)),
    }
}

impl<F: Format> From<Date> for Cast<DateOnly, F> {
    fn from(date: Date) -> Self {
        Self::new(midnight(date))
    }
}

impl<F: Format> From<DateTime> for Cast<DateAndTime, F> {
    fn from(value: DateTime) -> Self {
        Self::new(value)
    }
}

/// The wall time in UTC, which is how `laravel-rust` keeps a `DATETIME`. With it, a model's `created_at` or
/// `updated_at` can be a [`DateTimeCast`].
impl<F: Format> From<Timestamp> for Cast<DateAndTime, F> {
    fn from(moment: Timestamp) -> Self {
        Self::new(TimeZone::UTC.to_datetime(moment))
    }
}

impl<S, F> Cast<S, F> {
    /// What the column holds: a `DATE` is its day at midnight.
    fn moment(&self) -> DateTime {
        match self.kind {
            Kind::Date => midnight(self.value.date()),
            Kind::DateTime => self.value,
        }
    }
}

impl<S, F> Clone for Cast<S, F> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<S, F> Copy for Cast<S, F> {}
impl<S, F> PartialEq for Cast<S, F> {
    fn eq(&self, other: &Self) -> bool {
        self.moment() == other.moment()
    }
}
impl<S, F> Eq for Cast<S, F> {}
impl<S, F> PartialOrd for Cast<S, F> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl<S, F> Ord for Cast<S, F> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.moment().cmp(&other.moment())
    }
}
impl<S, F> std::hash::Hash for Cast<S, F> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.moment().hash(state);
    }
}
impl<S, F> fmt::Debug for Cast<S, F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Cast").field(&self.moment()).finish()
    }
}