use super::arguments::{Args, formatted};
use super::{dispatch, render_error, upstream};
use crate::error::Result;
use crate::value::{Object, Value};
use jiff::civil::{Date, DateTime, Weekday};
use jiff::fmt::temporal::DateTimeParser;
use jiff::tz::TimeZone;
use jiff::{Timestamp, ZonedDateTime};
use laravel_rust_format_core::carbon::{
self, CalendarUnit, CarbonInput, DifferenceOptions, Locale, Relative,
};
use std::any::Any;
#[derive(Debug)]
pub(super) struct DateValue {
date: ZonedDateTime,
now: Option<ZonedDateTime>,
locale: Locale,
}
impl Object<'_> for DateValue {
fn type_name(&self) -> &'static str {
"date"
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
pub(super) fn as_date<'s>(value: &'s Value<'_>) -> Option<&'s DateValue> {
match value {
Value::Object(object) => object.as_any()?.downcast_ref(),
_ => None,
}
}
pub(super) fn function<'a>(
name: &str,
args: Args<'_, 'a, '_>,
clock: Option<&dyn Fn() -> ZonedDateTime>,
) -> Option<Result<Value<'a>>> {
dispatch!(name, args, {
"date" => 1..=1, {
if as_date(args.value(0)?).is_some() {
return Ok(args.value(0)?.clone());
}
let date = parse(args.str(0)?)?;
Ok(Value::object(DateValue { date, now: clock.map(|now| now()), locale: Locale::default() }))
};
"now" => 0..=0, {
let now = clock.ok_or_else(no_clock)?();
Ok(Value::object(DateValue { date: now.clone(), now: Some(now), locale: Locale::default() }))
};
})
}
fn parse(input: &str) -> Result<ZonedDateTime> {
if let Ok(date) = input.parse::<ZonedDateTime>() {
return Ok(date);
}
if !input.contains('[')
&& let Ok(timestamp) = input.parse::<Timestamp>()
{
let zone = if input.ends_with(['Z', 'z']) {
TimeZone::UTC
} else {
let offset = input.get(10..).and_then(|time| {
time.rfind(['+', '-'])
.and_then(|index| DateTimeParser::new().parse_time_zone(&time[index..]).ok())
});
offset.unwrap_or(TimeZone::UTC)
};
return Ok(timestamp.to_zoned_datetime(zone));
}
if !input.contains('[') {
if let Ok(date) = input.parse::<DateTime>() {
return upstream(CarbonInput::to_zoned_datetime(&date));
}
if let Ok(date) = input.parse::<Date>() {
return upstream(CarbonInput::to_zoned_datetime(&date));
}
}
Err(render_error(format!(
"date expects an ISO date or date-time, got {input:?}"
)))
}
pub(super) fn method<'a>(
name: &str,
receiver: &DateValue,
args: Args<'_, 'a, '_>,
) -> Option<Result<Value<'a>>> {
let date = &receiver.date;
let other = |index| date_arg(args, index);
let date_result = |result| receiver.wrap_result(result);
let optional_date_result = |result: laravel_rust_format_core::Result<Option<ZonedDateTime>>| {
Ok(upstream(result)?.map_or(Value::Bool(false), |date| receiver.wrap(date)))
};
let now = || receiver.now.as_ref().ok_or_else(no_clock);
let result = dispatch!(name, args, {
"format" => 1..=1, formatted(upstream(carbon::format(date, args.str(0)?))?);
"to_iso_string" => 0..=0, Ok(upstream(carbon::to_iso_string(date))?.map_or(Value::Null, Value::string));
"to_iso8601_string" => 0..=0, formatted(upstream(carbon::to_iso8601_string(date))?);
"to_date_string" => 0..=0, formatted(upstream(carbon::to_date_string(date))?);
"to_time_string" => 0..=0, formatted(upstream(carbon::to_time_string(date))?);
"to_date_time_string" | "to_datetime_string" => 0..=0, formatted(upstream(carbon::to_date_time_string(date))?);
"to_formatted_date_string" => 0..=0, formatted(upstream(carbon::to_formatted_date_string(date))?);
"to_day_date_time_string" => 0..=0, formatted(upstream(carbon::to_day_date_time_string(date))?);
"to_atom_string" => 0..=0, formatted(upstream(carbon::to_atom_string(date))?);
"to_cookie_string" => 0..=0, formatted(upstream(carbon::to_cookie_string(date))?);
"to_rfc2822_string" => 0..=0, formatted(upstream(carbon::to_rfc2822_string(date))?);
"to_rss_string" => 0..=0, formatted(upstream(carbon::to_rss_string(date))?);
"to_w3c_string" => 0..=0, formatted(upstream(carbon::to_w3c_string(date))?);
"locale" => 0..=1, {
if args.len() == 0 {
return Ok(Value::string(receiver.locale.code()));
}
Ok(Value::object(DateValue {
date: date.clone(),
now: receiver.now.clone(),
locale: Locale::new(args.str(0)?),
}))
};
"iso_format" | "iso_format_in" => 1..=2, formatted(upstream(carbon::iso_format_in(
args.opt_str(1)?.map_or(receiver.locale, Locale::new), date, args.str(0)?
))?);
"translated_format" | "translated_format_in" => 1..=2, formatted(upstream(carbon::translated_format_in(
args.opt_str(1)?.map_or(receiver.locale, Locale::new), date, args.str(0)?
))?);
"calendar" | "calendar_in" => 0..=2, formatted(upstream(carbon::calendar_in(
args.opt_str(1)?.map_or(receiver.locale, Locale::new), date, other_or_now(receiver, args)?
))?);
"diff_for_humans" | "diff_for_humans_in" => 0..=2, {
let relative = if args.is_null(0) {
Relative::Now(receiver.now.as_ref().ok_or_else(no_clock)?.clone())
} else {
Relative::To(&as_date(args.value(0)?).ok_or_else(|| args.invalid(0, "a date"))?.date)
};
let locale = args.opt_str(1)?.map_or(receiver.locale, Locale::new);
formatted(upstream(carbon::diff_for_humans_in(locale, date, relative))?)
};
"is_past" => 0..=0, Ok(Value::Bool(upstream(carbon::is_past(date, now()?))?));
"is_future" => 0..=0, Ok(Value::Bool(upstream(carbon::is_future(date, now()?))?));
"is_now_or_past" => 0..=0, Ok(Value::Bool(upstream(carbon::is_now_or_past(date, now()?))?));
"is_now_or_future" => 0..=0, Ok(Value::Bool(upstream(carbon::is_now_or_future(date, now()?))?));
"is_today" => 0..=0, Ok(Value::Bool(upstream(carbon::is_today(date, now()?))?));
"is_tomorrow" => 0..=0, Ok(Value::Bool(upstream(carbon::is_tomorrow(date, now()?))?));
"is_yesterday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_yesterday(date, now()?))?));
"is_weekday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_weekday(date))?));
"is_weekend" => 0..=0, Ok(Value::Bool(upstream(carbon::is_weekend(date))?));
"is_monday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_monday(date))?));
"is_tuesday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_tuesday(date))?));
"is_wednesday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_wednesday(date))?));
"is_thursday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_thursday(date))?));
"is_friday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_friday(date))?));
"is_saturday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_saturday(date))?));
"is_sunday" => 0..=0, Ok(Value::Bool(upstream(carbon::is_sunday(date))?));
"is_leap_year" => 0..=0, Ok(Value::Bool(upstream(carbon::is_leap_year(date))?));
"is_long_year" => 0..=0, Ok(Value::Bool(upstream(carbon::is_long_year(date))?));
"is_long_iso_year" => 0..=0, Ok(Value::Bool(upstream(carbon::is_long_iso_year(date))?));
"is_last_of_month" => 0..=0, Ok(Value::Bool(upstream(carbon::is_last_of_month(date))?));
"is_start_of_day" | "is_start_of_day_with_precision" => 0..=1,
Ok(Value::Bool(upstream(carbon::is_start_of_day_with_precision(date, args.bool_or(0, false)?))?));
"is_end_of_day" | "is_end_of_day_with_precision" => 0..=1,
Ok(Value::Bool(upstream(carbon::is_end_of_day_with_precision(date, args.bool_or(0, false)?))?));
"is_start_of_day_with_interval" => 1..=1,
Ok(Value::Bool(upstream(carbon::is_start_of_day_with_interval(date, span_arg(args)?))?));
"is_end_of_day_with_interval" => 1..=1,
Ok(Value::Bool(upstream(carbon::is_end_of_day_with_interval(date, span_arg(args)?))?));
"eq" => 1..=1, Ok(Value::Bool(upstream(carbon::eq(date, other(0)?))?));
"ne" => 1..=1, Ok(Value::Bool(upstream(carbon::ne(date, other(0)?))?));
"lt" => 1..=1, Ok(Value::Bool(upstream(carbon::lt(date, other(0)?))?));
"lte" => 1..=1, Ok(Value::Bool(upstream(carbon::lte(date, other(0)?))?));
"gt" => 1..=1, Ok(Value::Bool(upstream(carbon::gt(date, other(0)?))?));
"gte" => 1..=1, Ok(Value::Bool(upstream(carbon::gte(date, other(0)?))?));
"min" => 0..=1, Ok(receiver.wrap(upstream(carbon::min(date, other_or_now(receiver, args)?))?));
"max" => 0..=1, Ok(receiver.wrap(upstream(carbon::max(date, other_or_now(receiver, args)?))?));
"average" => 0..=1, date_result(carbon::average(date, other_or_now(receiver, args)?));
"is_birthday" => 0..=1, Ok(Value::Bool(upstream(carbon::is_birthday(date, other_or_now(receiver, args)?))?));
"between" => 2..=3, Ok(Value::Bool(upstream(carbon::between(date, other(0)?, other(1)?, args.bool_or(2, true)?))?));
"between_included" => 2..=2, Ok(Value::Bool(upstream(carbon::between_included(date, other(0)?, other(1)?))?));
"between_excluded" => 2..=2, Ok(Value::Bool(upstream(carbon::between_excluded(date, other(0)?, other(1)?))?));
"closest" => 2..=2, Ok(receiver.wrap(upstream(carbon::closest(date, other(0)?, other(1)?))?));
"farthest" => 2..=2, Ok(receiver.wrap(upstream(carbon::farthest(date, other(0)?, other(1)?))?));
"next" => 1..=1, date_result(carbon::next(date, weekday(args, 0)?));
"previous" => 1..=1, date_result(carbon::previous(date, weekday(args, 0)?));
"first_of_month" => 0..=1, date_result(carbon::first_of_month(date, optional_weekday(args)?));
"first_of_quarter" => 0..=1, date_result(carbon::first_of_quarter(date, optional_weekday(args)?));
"first_of_year" => 0..=1, date_result(carbon::first_of_year(date, optional_weekday(args)?));
"last_of_month" => 0..=1, date_result(carbon::last_of_month(date, optional_weekday(args)?));
"last_of_quarter" => 0..=1, date_result(carbon::last_of_quarter(date, optional_weekday(args)?));
"last_of_year" => 0..=1, date_result(carbon::last_of_year(date, optional_weekday(args)?));
"nth_of_month" => 2..=2, optional_date_result(carbon::nth_of_month(date, args.int(0)?, weekday(args, 1)?));
"nth_of_quarter" => 2..=2, optional_date_result(carbon::nth_of_quarter(date, args.int(0)?, weekday(args, 1)?));
"nth_of_year" => 2..=2, optional_date_result(carbon::nth_of_year(date, args.int(0)?, weekday(args, 1)?));
"start_of_week" | "start_of_week_on" => 0..=1,
date_result(carbon::start_of_week_on(date, optional_weekday(args)?.unwrap_or(Weekday::Monday)));
"end_of_week" | "end_of_week_on" => 0..=1,
date_result(carbon::end_of_week_on(date, optional_weekday(args)?.unwrap_or(Weekday::Sunday)));
"set_date" => 3..=3, date_result(carbon::set_date(date, args.int(0)?, args.int(1)?, args.int(2)?));
"set_time" => 2..=4, date_result(carbon::set_time(date, args.int(0)?, args.int(1)?, args.int_or(2, 0)?, args.int_or(3, 0)?));
"set_iso_date" => 2..=3, date_result(carbon::set_iso_date(date, args.int(0)?, args.int(1)?, args.int_or(2, 1)?));
"set_timezone" => 1..=1, {
let zone = DateTimeParser::new().parse_time_zone(args.str(0)?).map_err(|error| render_error(error.to_string()))?;
Ok(receiver.wrap(upstream(carbon::set_timezone(date, zone))?))
};
"copy" => 0..=0, Ok(receiver.wrap(upstream(carbon::copy(date))?));
"add_span" => 1..=1, date_result(carbon::add_span(date, span_arg(args)?));
"sub_span" => 1..=1, date_result(carbon::sub_span(date, span_arg(args)?));
"is_same_month_with_year" => 1..=2,
Ok(Value::Bool(upstream(carbon::is_same_month_with_year(date, other(0)?, args.bool_or(1, true)?))?));
"is_same_quarter_with_year" => 1..=2,
Ok(Value::Bool(upstream(carbon::is_same_quarter_with_year(date, other(0)?, args.bool_or(1, true)?))?));
"timestamp_ms" => 0..=0, Ok(Value::Int(upstream(carbon::timestamp_ms(date))?));
"timestamp_float" => 0..=0, Ok(Value::Float(upstream(carbon::timestamp_float(date))?));
"tz_abbreviation" => 0..=0, formatted(upstream(carbon::tz_abbreviation(date))?);
});
result.or_else(|| unit_method(name, receiver, args))
}
impl DateValue {
pub(super) fn timestamp(&self) -> Timestamp {
self.date.timestamp()
}
fn wrap<'a>(&self, date: ZonedDateTime) -> Value<'a> {
Value::object(Self {
date,
now: self.now.clone(),
locale: self.locale,
})
}
fn wrap_result<'a>(
&self,
value: laravel_rust_format_core::Result<ZonedDateTime>,
) -> Result<Value<'a>> {
upstream(value).map(|date| self.wrap(date))
}
}
fn date_arg<'s>(args: Args<'s, '_, '_>, index: usize) -> Result<&'s ZonedDateTime> {
as_date(args.value(index)?)
.map(|date| &date.date)
.ok_or_else(|| args.invalid(index, "a date"))
}
fn other_or_now<'s>(receiver: &'s DateValue, args: Args<'s, '_, '_>) -> Result<&'s ZonedDateTime> {
if args.is_null(0) {
receiver.now.as_ref().ok_or_else(no_clock)
} else {
date_arg(args, 0)
}
}
fn span_arg(args: Args<'_, '_, '_>) -> Result<jiff::Span> {
args.str(0)?
.parse::<jiff::Span>()
.map_err(|error| render_error(error.to_string()))
}
fn weekday(args: Args<'_, '_, '_>, index: usize) -> Result<Weekday> {
Ok(match args.int(index)? {
0 => Weekday::Sunday,
1 => Weekday::Monday,
2 => Weekday::Tuesday,
3 => Weekday::Wednesday,
4 => Weekday::Thursday,
5 => Weekday::Friday,
6 => Weekday::Saturday,
_ => return Err(args.invalid(index, "a Sunday-based weekday from 0 to 6")),
})
}
fn optional_weekday(args: Args<'_, '_, '_>) -> Result<Option<Weekday>> {
if args.is_null(0) {
Ok(None)
} else {
weekday(args, 0).map(Some)
}
}
fn unit_method<'a>(
name: &str,
receiver: &DateValue,
args: Args<'_, 'a, '_>,
) -> Option<Result<Value<'a>>> {
let (operation, suffix) = [
"add_",
"sub_",
"start_of_",
"end_of_",
"diff_in_",
"is_same_",
"is_current_",
"is_next_",
"is_last_",
]
.into_iter()
.find_map(|prefix| name.strip_prefix(prefix).map(|suffix| (prefix, suffix)))?;
let (suffix, overflow) = suffix
.strip_suffix("_no_overflow")
.map(|unit| (unit, Some(false)))
.or_else(|| {
suffix
.strip_suffix("_with_overflow")
.map(|unit| (unit, Some(true)))
})
.unwrap_or((suffix, None));
let suffix = suffix.strip_suffix("_with").unwrap_or(suffix);
let explicit = suffix == "unit";
let unit = if explicit {
None
} else {
Some(calendar_unit(suffix)?)
};
let slot = usize::from(explicit);
let resolve_unit = || match unit {
Some(unit) => Ok(unit),
None => {
calendar_unit(args.str(0)?).ok_or_else(|| args.invalid(0, "a Carbon calendar unit"))
}
};
let date = &receiver.date;
Some((|| match operation {
"add_" | "sub_" => {
let variable_overflow = explicit && overflow.is_some();
args.check(slot, slot + 1 + usize::from(variable_overflow))?;
let amount = args.number_or(slot, 1)?;
let overflow = if variable_overflow {
args.bool_or(slot + 1, true)?
} else {
overflow.unwrap_or(true)
};
let calendar = resolve_unit()?;
receiver.wrap_result(if operation == "add_" {
carbon::add_unit_with_overflow(date, calendar, amount, overflow)
} else {
carbon::sub_unit_with_overflow(date, calendar, amount, overflow)
})
}
"start_of_" | "end_of_" => {
args.check(slot, slot)?;
let calendar = resolve_unit()?;
receiver.wrap_result(if operation == "start_of_" {
carbon::start_of_unit(date, calendar)
} else {
carbon::end_of_unit(date, calendar)
})
}
"diff_in_" => {
args.check(slot, slot + 3)?;
let calendar = resolve_unit()?;
let other = other_or_now(receiver, args.skip(slot))?;
let options = DifferenceOptions::default()
.absolute(args.bool_or(slot + 1, false)?)
.utc(args.bool_or(slot + 2, false)?);
Ok(Value::Float(upstream(carbon::diff_in_unit(
date, other, calendar, options,
))?))
}
"is_same_" => {
args.check(slot + 1, slot + 1)?;
Ok(Value::Bool(upstream(carbon::is_same_unit(
date,
date_arg(args, slot)?,
resolve_unit()?,
))?))
}
_ => {
args.check(slot, slot)?;
let calendar = resolve_unit()?;
let now = receiver.now.as_ref().ok_or_else(no_clock)?;
Ok(Value::Bool(upstream(match operation {
"is_current_" => carbon::is_current_unit(date, now, calendar),
"is_next_" => carbon::is_next_unit(date, now, calendar),
_ => carbon::is_last_unit(date, now, calendar),
})?))
}
})())
}
fn calendar_unit(name: &str) -> Option<CalendarUnit> {
use CalendarUnit::*;
Some(match name.trim_end_matches('s') {
"microsecond" => Microsecond,
"millisecond" => Millisecond,
"second" => Second,
"minute" => Minute,
"hour" => Hour,
"day" => Day,
"weekday" => Weekday,
"weekend_day" | "weekendDay" => WeekendDay,
"week" => Week,
"month" => Month,
"quarter" => Quarter,
"year" => Year,
"decade" => Decade,
"century" | "centurie" => Century,
"millennium" | "millennia" => Millennium,
_ => return None,
})
}
pub(super) fn property<'a>(name: &str, receiver: &DateValue) -> Option<Result<Value<'a>>> {
let date = &receiver.date;
macro_rules! properties {
($($prop:ident => $constructor:ident),+ $(,)?) => {
match name {
$(stringify!($prop) => upstream(carbon::$prop(date)).map(|value| Value::$constructor(value.into())),)+
"timezone_name" => upstream(carbon::timezone_name(date)).and_then(formatted),
"age" => receiver.now.as_ref().ok_or_else(no_clock).and_then(|now| upstream(carbon::age(date, now))).map(Value::Int),
"local" => upstream(carbon::local(date, receiver.now.as_ref().map_or(&TimeZone::UTC, |now| now.time_zone()))).map(Value::Bool),
_ => return None,
}
};
}
Some(properties!(
year => Int, month => Int, day => Int, hour => Int, minute => Int, second => Int,
micro => Int, milli => Int, day_of_week => Int, day_of_week_iso => Int, day_of_year => Int,
week_of_year => Int, iso_week => Int, iso_week_year => Int, week_of_month => Int, week_number_in_month => Int,
quarter => Int, days_in_month => Int, days_in_year => Int, days_in_quarter => Int,
timestamp => Int, offset => Int, offset_hours => Float, dst => Bool, utc => Bool,
decade => Int, century => Int, millennium => Int,
))
}
fn no_clock() -> crate::error::Error {
render_error("this date operation requires the render clock")
}