use crate::FormError;
use crate::kind::ChoiceOptions;
pub trait DataTransformer: Send + Sync {
fn transform(&self, model: &str) -> Result<String, FormError>;
fn reverse_transform(&self, view: &str) -> Result<String, FormError>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct BoolToStringTransformer;
impl DataTransformer for BoolToStringTransformer {
fn transform(&self, model: &str) -> Result<String, FormError> {
Ok(if is_truthy(model) {
String::from("1")
} else {
String::new()
})
}
fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
Ok(if is_truthy(view) {
String::from("1")
} else {
String::from("0")
})
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct I64ToStringTransformer;
impl DataTransformer for I64ToStringTransformer {
fn transform(&self, model: &str) -> Result<String, FormError> {
if model.is_empty() {
return Ok(String::new());
}
model
.parse::<i64>()
.map(|n| n.to_string())
.map_err(|_| FormError::Transform(String::from("invalid i64 model value")))
}
fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
if view.is_empty() {
return Ok(String::new());
}
view.parse::<i64>()
.map(|n| n.to_string())
.map_err(|_| FormError::Transform(String::from("invalid i64 view value")))
}
}
#[derive(Debug, Clone)]
pub struct ChoiceToValueTransformer {
options: ChoiceOptions,
}
impl ChoiceToValueTransformer {
#[must_use]
pub const fn new(options: ChoiceOptions) -> Self {
Self { options }
}
}
impl DataTransformer for ChoiceToValueTransformer {
fn transform(&self, model: &str) -> Result<String, FormError> {
if model.is_empty() {
return Ok(String::new());
}
if self.options.multiple {
let mut out = Vec::new();
for part in split_multi(model) {
if !self.is_allowed(part) {
return Err(FormError::Transform(format!(
"choice value {part:?} is not allowed"
)));
}
out.push(part.to_owned());
}
return Ok(join_multi(&out));
}
if self.is_allowed(model) {
Ok(model.to_owned())
} else {
Err(FormError::Transform(format!(
"choice value {model:?} is not allowed"
)))
}
}
fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
self.transform(view)
}
}
impl ChoiceToValueTransformer {
fn is_allowed(&self, value: &str) -> bool {
self.options.choices.iter().any(|c| c.value == value)
}
}
fn is_truthy(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "on" | "yes"
)
}
#[must_use]
pub fn split_multi(value: &str) -> Vec<&str> {
value.split_whitespace().filter(|s| !s.is_empty()).collect()
}
#[must_use]
pub fn join_multi(values: &[String]) -> String {
values.join(" ")
}