Skip to main content

php_dates/
pattern.rs

1//! Compiled PHP date patterns: `date()` / `DateTime::format()` and `DateTime::createFromFormat()`.
2
3use crate::{Error, Result};
4
5/// One piece of a pattern.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub(crate) enum Token {
8    /// A character that is not a token. `createFromFormat` gives ` # ? * ! | +` a meaning; `format` prints them.
9    Literal(char),
10    /// A character after a backslash: always itself.
11    Escaped(char),
12    /// `d`
13    Day2,
14    /// `D`
15    DayShort,
16    /// `j`
17    Day,
18    /// `l`
19    DayName,
20    /// `N`
21    IsoWeekday,
22    /// `S`
23    OrdinalSuffix,
24    /// `w`
25    Weekday,
26    /// `z`
27    DayOfYear,
28    /// `W`
29    IsoWeek,
30    /// `F`
31    MonthName,
32    /// `m`
33    Month2,
34    /// `M`
35    MonthShort,
36    /// `n`
37    Month,
38    /// `t`
39    DaysInMonth,
40    /// `L`
41    LeapYear,
42    /// `o`
43    IsoYear,
44    /// `X`
45    ExpandedYear,
46    /// `x`
47    ExpandedYearSigned,
48    /// `Y`
49    Year4,
50    /// `y`
51    Year2,
52    /// `a`
53    MeridiemLower,
54    /// `A`
55    MeridiemUpper,
56    /// `B`
57    Swatch,
58    /// `g`
59    Hour12,
60    /// `G`
61    Hour24,
62    /// `h`
63    Hour12Padded,
64    /// `H`
65    Hour24Padded,
66    /// `i`
67    Minute,
68    /// `s`
69    Second,
70    /// `u`
71    Micro,
72    /// `v`
73    Milli,
74    /// `e`
75    ZoneName,
76    /// `I`
77    Dst,
78    /// `O`
79    OffsetCompact,
80    /// `P`
81    OffsetColon,
82    /// `p`
83    OffsetColonZ,
84    /// `T`
85    ZoneAbbreviation,
86    /// `Z`
87    OffsetSeconds,
88    /// `c`
89    Iso8601,
90    /// `r`
91    Rfc2822,
92    /// `U`
93    Timestamp,
94}
95
96/// A compiled PHP date pattern.
97///
98/// The same pattern formats ([`format`](Self::format)) and parses ([`parse_at`](Self::parse_at)). The tokens are
99/// those of PHP 8.5's `DateTime::format()`:
100///
101/// | | Tokens |
102/// |---|---|
103/// | Day | `d D j l N S w z` |
104/// | Week | `W` |
105/// | Month | `F m M n t` |
106/// | Year | `L o X x Y y` |
107/// | Time | `a A B g G h H i s u v` |
108/// | Time zone | `e I O P p T Z` |
109/// | Full | `c r U` |
110/// | Escape | `\` |
111///
112/// Names are English. `createFromFormat()` reads `d D j l S z F m M n Y y X x a A g h G H i s v u e T O P p U`, plus
113/// the pattern characters ` # ? * ! | +`; the others only format.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct PhpDatePattern {
116    pub(crate) tokens: Vec<Token>,
117}
118
119impl PhpDatePattern {
120    /// Compile a pattern the way PHP reads it: a letter that is not a token is a literal, and `\` escapes the next
121    /// character.
122    ///
123    /// # Errors
124    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash.
125    pub fn compile(pattern: &str) -> Result<Self> {
126        Self::build(pattern, false)
127    }
128
129    /// Like [`compile`](Self::compile), but a letter that is not a PHP token is an error instead of a literal. Use
130    /// it to validate patterns a person typed: `compile("Y-m-d q")` prints a literal `q`, which is almost always a
131    /// typo.
132    ///
133    /// # Errors
134    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash or a letter that is not a token.
135    pub fn compile_strict(pattern: &str) -> Result<Self> {
136        Self::build(pattern, true)
137    }
138
139    fn build(pattern: &str, strict: bool) -> Result<Self> {
140        let mut tokens = vec![];
141        let mut chars = pattern.chars();
142        while let Some(character) = chars.next() {
143            tokens.push(match character {
144                '\\' => Token::Escaped(
145                    chars.next().ok_or_else(|| Error::argument("Date format ends with an incomplete escape."))?,
146                ),
147                'd' => Token::Day2,
148                'D' => Token::DayShort,
149                'j' => Token::Day,
150                'l' => Token::DayName,
151                'N' => Token::IsoWeekday,
152                'S' => Token::OrdinalSuffix,
153                'w' => Token::Weekday,
154                'z' => Token::DayOfYear,
155                'W' => Token::IsoWeek,
156                'F' => Token::MonthName,
157                'm' => Token::Month2,
158                'M' => Token::MonthShort,
159                'n' => Token::Month,
160                't' => Token::DaysInMonth,
161                'L' => Token::LeapYear,
162                'o' => Token::IsoYear,
163                'X' => Token::ExpandedYear,
164                'x' => Token::ExpandedYearSigned,
165                'Y' => Token::Year4,
166                'y' => Token::Year2,
167                'a' => Token::MeridiemLower,
168                'A' => Token::MeridiemUpper,
169                'B' => Token::Swatch,
170                'g' => Token::Hour12,
171                'G' => Token::Hour24,
172                'h' => Token::Hour12Padded,
173                'H' => Token::Hour24Padded,
174                'i' => Token::Minute,
175                's' => Token::Second,
176                'u' => Token::Micro,
177                'v' => Token::Milli,
178                'e' => Token::ZoneName,
179                'I' => Token::Dst,
180                'O' => Token::OffsetCompact,
181                'P' => Token::OffsetColon,
182                'p' => Token::OffsetColonZ,
183                'T' => Token::ZoneAbbreviation,
184                'Z' => Token::OffsetSeconds,
185                'c' => Token::Iso8601,
186                'r' => Token::Rfc2822,
187                'U' => Token::Timestamp,
188                other if strict && other.is_ascii_alphabetic() => {
189                    return Err(Error::argument(format!("PHP date token \"{other}\" is not supported.")));
190                }
191                other => Token::Literal(other),
192            });
193        }
194        Ok(Self { tokens })
195    }
196}