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
//! What a cast stores (the column type) and how it is read and written (the format).

use laravel::time::civil::{Date, DateTime};

/// Which column type a cast stores.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A `DATE` column, stored as `Y-m-d`.
    Date,
    /// A `DATETIME` column, stored as `Y-m-d H:i:s`.
    DateTime,
}

impl Kind {
    pub(crate) const fn storage(self) -> &'static str {
        match self {
            Self::Date => "Y-m-d",
            Self::DateTime => "Y-m-d H:i:s",
        }
    }
}

/// Marker for the stored column type. Equivalent to the PHP subclass (`DateCast`, `DateTimeCast`).
pub trait Storage: 'static {
    /// The column type.
    const KIND: Kind;
}

/// `DATE` column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateOnly;
/// `DATETIME` column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DateAndTime;

impl Storage for DateOnly {
    const KIND: Kind = Kind::Date;
}
impl Storage for DateAndTime {
    const KIND: Kind = Kind::DateTime;
}

/// Marker for the cast's constructor arguments. Equivalent to the PHP `Cast::class . ':true,m/Y,m/Y'`
/// string, as a type.
pub trait Format: 'static {
    /// PHP's `setParsing`: read the incoming value with [`Format::set`] instead of the storage format.
    const PARSE_SET: bool;
    /// Pattern of `get` (serialization). `None` uses the configured one.
    fn get() -> Option<&'static str> {
        None
    }
    /// Pattern of `set` (deserialization), used when [`Format::PARSE_SET`] is true. `None` uses the configured one.
    fn set() -> Option<&'static str> {
        None
    }
}

/// `DateCast::class`: serialize with the configured pattern, accept the storage format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Configured;
/// `DateCast::SETPARSED`: also accept the configured pattern.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Parsed;
/// `DateCast::SETONLYMONTHYEAR`: read and write `m/Y`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MonthYear;

impl Format for Configured {
    const PARSE_SET: bool = false;
}
impl Format for Parsed {
    const PARSE_SET: bool = true;
}
impl Format for MonthYear {
    const PARSE_SET: bool = true;
    fn get() -> Option<&'static str> {
        Some("m/Y")
    }
    fn set() -> Option<&'static str> {
        Some("m/Y")
    }
}

pub(crate) fn midnight(date: Date) -> DateTime {
    date.at(0, 0, 0, 0)
}

/// Declare a [`Format`] with its own pattern, then use it as the cast's type parameter.
///
/// ```
/// laravel_casts::date_format!(pub MonthDash, "m - Y");
/// laravel_casts::date_format!(pub Mixed, get = "d/m/Y", set = "Y-m-d");
/// // issued_at: DateCast<MonthDash>
/// ```
///
/// With one pattern, the cast serializes and reads it. With `get` and `set`, they differ. Both
/// parse the incoming request (`PARSE_SET`, like `SETPARSED`) and fall back to the storage format.
#[macro_export]
macro_rules! date_format {
    ($(#[$meta:meta])* $vis:vis $name:ident, $pattern:literal) => {
        $crate::date_format!($(#[$meta])* $vis $name, get = $pattern, set = $pattern);
    };
    ($(#[$meta:meta])* $vis:vis $name:ident, get = $get:literal, set = $set:literal) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        $vis struct $name;

        impl $crate::Format for $name {
            const PARSE_SET: bool = true;
            fn get() -> Option<&'static str> {
                Some($get)
            }
            fn set() -> Option<&'static str> {
                Some($set)
            }
        }
    };
}