Skip to main content

php_dates/
pattern.rs

1//! Compiled PHP date patterns: `date()` / `DateTime::format()` and `DateTime::createFromFormat()`.
2
3use crate::{Error, Result};
4use std::{fmt, str::FromStr};
5
6/// One piece of a pattern.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub(crate) enum Token {
9    /// A character that is not a token. `createFromFormat` gives ` # ? * ! | +` a meaning; `format` prints them.
10    Literal(char),
11    /// A character after a backslash: always itself.
12    Escaped(char),
13    /// `d`
14    Day2,
15    /// `D`
16    DayShort,
17    /// `j`
18    Day,
19    /// `l`
20    DayName,
21    /// `N`
22    IsoWeekday,
23    /// `S`
24    OrdinalSuffix,
25    /// `w`
26    Weekday,
27    /// `z`
28    DayOfYear,
29    /// `W`
30    IsoWeek,
31    /// `F`
32    MonthName,
33    /// `m`
34    Month2,
35    /// `M`
36    MonthShort,
37    /// `n`
38    Month,
39    /// `t`
40    DaysInMonth,
41    /// `L`
42    LeapYear,
43    /// `o`
44    IsoYear,
45    /// `X`
46    ExpandedYear,
47    /// `x`
48    ExpandedYearSigned,
49    /// `Y`
50    Year4,
51    /// `y`
52    Year2,
53    /// `a`
54    MeridiemLower,
55    /// `A`
56    MeridiemUpper,
57    /// `B`
58    Swatch,
59    /// `g`
60    Hour12,
61    /// `G`
62    Hour24,
63    /// `h`
64    Hour12Padded,
65    /// `H`
66    Hour24Padded,
67    /// `i`
68    Minute,
69    /// `s`
70    Second,
71    /// `u`
72    Micro,
73    /// `v`
74    Milli,
75    /// `e`
76    ZoneName,
77    /// `I`
78    Dst,
79    /// `O`
80    OffsetCompact,
81    /// `P`
82    OffsetColon,
83    /// `p`
84    OffsetColonZ,
85    /// `T`
86    ZoneAbbreviation,
87    /// `Z`
88    OffsetSeconds,
89    /// `c`
90    Iso8601,
91    /// `r`
92    Rfc2822,
93    /// `U`
94    Timestamp,
95}
96
97impl Token {
98    /// A token `createFromFormat()` does not read.
99    pub(crate) const fn only_formats(self) -> bool {
100        matches!(
101            self,
102            Self::IsoWeekday
103                | Self::Weekday
104                | Self::IsoWeek
105                | Self::DaysInMonth
106                | Self::LeapYear
107                | Self::IsoYear
108                | Self::Swatch
109                | Self::Dst
110                | Self::OffsetSeconds
111                | Self::Iso8601
112                | Self::Rfc2822
113        )
114    }
115}
116
117/// A compiled PHP date pattern.
118///
119/// The same pattern formats ([`format`](Self::format)) and parses ([`parse_at`](Self::parse_at)). The tokens are
120/// those of PHP 8.5's `DateTime::format()`:
121///
122/// | | Tokens |
123/// |---|---|
124/// | Day | `d D j l N S w z` |
125/// | Week | `W` |
126/// | Month | `F m M n t` |
127/// | Year | `L o X x Y y` |
128/// | Time | `a A B g G h H i s u v` |
129/// | Time zone | `e I O P p T Z` |
130/// | Full | `c r U` |
131/// | Escape | `\` |
132///
133/// 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
134/// the pattern characters ` # ? * ! | +`; the others only format.
135///
136/// A compiled pattern is `Send + Sync` and does not change, so compile once and share it. [`as_str`](Self::as_str) and
137/// `Display` give back the text it was compiled from, and [`FromStr`] is [`compile`](Self::compile).
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct PhpDatePattern {
140    pub(crate) tokens: Vec<Token>,
141    source: Box<str>,
142}
143
144impl fmt::Display for PhpDatePattern {
145    /// The pattern text, not a date.
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.pad(&self.source)
148    }
149}
150
151impl FromStr for PhpDatePattern {
152    type Err = Error;
153
154    fn from_str(pattern: &str) -> Result<Self> {
155        Self::compile(pattern)
156    }
157}
158
159impl PhpDatePattern {
160    /// Compile a pattern the way PHP reads it: a letter that is not a token is a literal, and `\` escapes the next
161    /// character.
162    ///
163    /// # Errors
164    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash.
165    pub fn compile(pattern: &str) -> Result<Self> {
166        Self::build(pattern, false)
167    }
168
169    /// Like [`compile`](Self::compile), but a letter that is not a PHP token is an error instead of a literal. Use
170    /// it to validate patterns a person typed: `compile("Y-m-d q")` prints a literal `q`, which is almost always a
171    /// typo.
172    ///
173    /// # Errors
174    /// Returns [`Error::InvalidFormat`] for a pattern that ends with a backslash or a letter that is not a token.
175    pub fn compile_strict(pattern: &str) -> Result<Self> {
176        Self::build(pattern, true)
177    }
178
179    /// The text the pattern was compiled from.
180    #[must_use]
181    pub const fn as_str(&self) -> &str {
182        &self.source
183    }
184
185    /// Whether `createFromFormat()` can read this pattern: `false` when it has a token that only formats
186    /// (`N w W o t L B I Z c r`), so that every parse would fail. Use it to reject a pattern for input when it is
187    /// configured rather than on the first value.
188    #[must_use]
189    pub fn is_parseable(&self) -> bool {
190        !self.tokens.iter().any(|token| token.only_formats())
191    }
192
193    fn build(pattern: &str, strict: bool) -> Result<Self> {
194        let mut tokens = Vec::with_capacity(pattern.len());
195        let mut chars = pattern.chars();
196        while let Some(character) = chars.next() {
197            tokens.push(match character {
198                '\\' => Token::Escaped(
199                    chars.next().ok_or_else(|| Error::argument("Date format ends with an incomplete escape."))?,
200                ),
201                'd' => Token::Day2,
202                'D' => Token::DayShort,
203                'j' => Token::Day,
204                'l' => Token::DayName,
205                'N' => Token::IsoWeekday,
206                'S' => Token::OrdinalSuffix,
207                'w' => Token::Weekday,
208                'z' => Token::DayOfYear,
209                'W' => Token::IsoWeek,
210                'F' => Token::MonthName,
211                'm' => Token::Month2,
212                'M' => Token::MonthShort,
213                'n' => Token::Month,
214                't' => Token::DaysInMonth,
215                'L' => Token::LeapYear,
216                'o' => Token::IsoYear,
217                'X' => Token::ExpandedYear,
218                'x' => Token::ExpandedYearSigned,
219                'Y' => Token::Year4,
220                'y' => Token::Year2,
221                'a' => Token::MeridiemLower,
222                'A' => Token::MeridiemUpper,
223                'B' => Token::Swatch,
224                'g' => Token::Hour12,
225                'G' => Token::Hour24,
226                'h' => Token::Hour12Padded,
227                'H' => Token::Hour24Padded,
228                'i' => Token::Minute,
229                's' => Token::Second,
230                'u' => Token::Micro,
231                'v' => Token::Milli,
232                'e' => Token::ZoneName,
233                'I' => Token::Dst,
234                'O' => Token::OffsetCompact,
235                'P' => Token::OffsetColon,
236                'p' => Token::OffsetColonZ,
237                'T' => Token::ZoneAbbreviation,
238                'Z' => Token::OffsetSeconds,
239                'c' => Token::Iso8601,
240                'r' => Token::Rfc2822,
241                'U' => Token::Timestamp,
242                other if strict && other.is_ascii_alphabetic() => {
243                    return Err(Error::argument(format!("PHP date token \"{other}\" is not supported.")));
244                }
245                other => Token::Literal(other),
246            });
247        }
248        Ok(Self { tokens, source: pattern.into() })
249    }
250}