Skip to main content

laravel_casts/
kind.rs

1//! What a cast stores (the column type) and how it is read and written (the format).
2
3use laravel::time::civil::{Date, DateTime};
4
5/// Which column type a cast stores.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Kind {
8    /// A `DATE` column, stored as `Y-m-d`.
9    Date,
10    /// A `DATETIME` column, stored as `Y-m-d H:i:s`.
11    DateTime,
12}
13
14impl Kind {
15    pub(crate) const fn storage(self) -> &'static str {
16        match self {
17            Self::Date => "Y-m-d",
18            Self::DateTime => "Y-m-d H:i:s",
19        }
20    }
21}
22
23/// Marker for the stored column type. Equivalent to the PHP subclass (`DateCast`, `DateTimeCast`).
24pub trait Storage: 'static {
25    /// The column type.
26    const KIND: Kind;
27}
28
29/// `DATE` column.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct DateOnly;
32/// `DATETIME` column.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct DateAndTime;
35
36impl Storage for DateOnly {
37    const KIND: Kind = Kind::Date;
38}
39impl Storage for DateAndTime {
40    const KIND: Kind = Kind::DateTime;
41}
42
43/// Marker for the cast's constructor arguments. Equivalent to the PHP `Cast::class . ':true,m/Y,m/Y'`
44/// string, as a type.
45pub trait Format: 'static {
46    /// PHP's `setParsing`: read the incoming value with [`Format::set`] instead of the storage format.
47    const PARSE_SET: bool;
48    /// Pattern of `get` (serialization). `None` uses the configured one.
49    fn get() -> Option<&'static str> {
50        None
51    }
52    /// Pattern of `set` (deserialization), used when [`Format::PARSE_SET`] is true. `None` uses the configured one.
53    fn set() -> Option<&'static str> {
54        None
55    }
56}
57
58/// `DateCast::class`: serialize with the configured pattern, accept the storage format.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
60pub struct Configured;
61/// `DateCast::SETPARSED`: also accept the configured pattern.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub struct Parsed;
64/// `DateCast::SETONLYMONTHYEAR`: read and write `m/Y`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct MonthYear;
67
68impl Format for Configured {
69    const PARSE_SET: bool = false;
70}
71impl Format for Parsed {
72    const PARSE_SET: bool = true;
73}
74impl Format for MonthYear {
75    const PARSE_SET: bool = true;
76    fn get() -> Option<&'static str> {
77        Some("m/Y")
78    }
79    fn set() -> Option<&'static str> {
80        Some("m/Y")
81    }
82}
83
84pub(crate) fn midnight(date: Date) -> DateTime {
85    date.at(0, 0, 0, 0)
86}
87
88/// Declare a [`Format`] with its own pattern, then use it as the cast's type parameter.
89///
90/// ```
91/// laravel_casts::date_format!(pub MonthDash, "m - Y");
92/// laravel_casts::date_format!(pub Mixed, get = "d/m/Y", set = "Y-m-d");
93/// // issued_at: DateCast<MonthDash>
94/// ```
95///
96/// With one pattern, the cast serializes and reads it. With `get` and `set`, they differ. Both
97/// parse the incoming request (`PARSE_SET`, like `SETPARSED`) and fall back to the storage format.
98#[macro_export]
99macro_rules! date_format {
100    ($(#[$meta:meta])* $vis:vis $name:ident, $pattern:literal) => {
101        $crate::date_format!($(#[$meta])* $vis $name, get = $pattern, set = $pattern);
102    };
103    ($(#[$meta:meta])* $vis:vis $name:ident, get = $get:literal, set = $set:literal) => {
104        $(#[$meta])*
105        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
106        $vis struct $name;
107
108        impl $crate::Format for $name {
109            const PARSE_SET: bool = true;
110            fn get() -> Option<&'static str> {
111                Some($get)
112            }
113            fn set() -> Option<&'static str> {
114                Some($set)
115            }
116        }
117    };
118}