use crate::functions::metadata::{ArgumentMetadata, FunctionMetadata, SyntaxVariants};
use crate::is_functions::IsFunction;
use minijinja::value::Kwargs;
use minijinja::{Environment, Error, Value};
pub struct LeapYear;
impl LeapYear {
pub fn is_leap(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
}
impl IsFunction for LeapYear {
const FUNCTION_NAME: &'static str = "is_leap_year";
const IS_NAME: &'static str = "leap_year";
const METADATA: FunctionMetadata = FunctionMetadata {
name: "is_leap_year",
category: "datetime",
description: "Check if a year is a leap year",
arguments: &[ArgumentMetadata {
name: "year",
arg_type: "integer",
required: true,
default: None,
description: "The year to check",
}],
return_type: "boolean",
examples: &[
"{{ is_leap_year(year=2024) }}",
"{% if 2024 is leap_year %}leap year{% endif %}",
],
syntax: SyntaxVariants::FUNCTION_AND_TEST,
};
fn call_as_function(kwargs: Kwargs) -> Result<Value, Error> {
let year: i32 = kwargs.get("year")?;
Ok(Value::from(Self::is_leap(year)))
}
fn call_as_is(value: &Value) -> bool {
if let Some(n) = value.as_i64() {
Self::is_leap(n as i32)
} else if let Some(s) = value.as_str() {
s.parse::<i32>().map(Self::is_leap).unwrap_or(false)
} else {
false
}
}
}
pub fn register_all(env: &mut Environment) {
LeapYear::register(env);
}