use std::collections::HashMap;
use std::path::{Path, PathBuf};
pub struct Template {
path: PathBuf,
}
impl Template {
pub fn new(path: impl AsRef<Path>) -> laravel::Result<Self> {
let path = path.as_ref();
if !path.is_file() {
return Err(laravel::Error::msg(format!(
"Laracards: template not found at {}.",
path.display()
)));
}
Ok(Self {
path: path.to_path_buf(),
})
}
pub fn render<K: AsRef<str>, V: AsRef<str>>(
&self,
data: impl IntoIterator<Item = (K, V)>,
) -> laravel::Result<String> {
let data: Vec<(String, String)> = data
.into_iter()
.map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned()))
.collect();
let svg = std::fs::read_to_string(&self.path)?;
Ok(Self::fill(&svg, &data))
}
pub fn fill(svg: &str, data: &[(String, String)]) -> String {
let values: HashMap<&str, &str> = data.iter().map(|(key, value)| (key.as_str(), value.as_str())).collect();
let mut svg = Self::sections(svg, &values);
for (key, value) in data {
svg = svg
.replace(&format!("{{{{{key}}}}}"), value)
.replace(&format!("__{}__", key.to_ascii_uppercase()), value);
}
Self::strip_unfilled(&svg)
}
fn sections(svg: &str, values: &HashMap<&str, &str>) -> String {
let mut out = String::with_capacity(svg.len());
let mut at = 0;
while let Some(found) = svg[at..].find("{{#") {
let start = at + found;
let key_start = start + 3;
let key_end = key_start
+ Self::run(&svg.as_bytes()[key_start..], |byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
});
if key_end == key_start || !svg[key_end..].starts_with("}}") {
out.push_str(&svg[at..key_start]);
at = key_start;
continue;
}
let key = &svg[key_start..key_end];
let body_start = key_end + 2;
let closing = format!("{{{{/{key}}}}}");
let Some(length) = svg[body_start..].find(&closing) else {
out.push_str(&svg[at..body_start]);
at = body_start;
continue;
};
out.push_str(&svg[at..start]);
if !values.get(key).copied().unwrap_or("").trim().is_empty() {
out.push_str(&svg[body_start..body_start + length]);
}
at = body_start + length + closing.len();
}
out.push_str(&svg[at..]);
out
}
fn strip_unfilled(svg: &str) -> String {
let bytes = svg.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
if let Some(end) = Self::braced(bytes, at).or_else(|| Self::dunder(bytes, at)) {
at = end;
continue;
}
out.push(bytes[at]);
at += 1;
}
String::from_utf8(out).unwrap_or_default()
}
fn braced(bytes: &[u8], at: usize) -> Option<usize> {
if !bytes[at..].starts_with(b"{{") {
return None;
}
let mut cursor = at + 2;
if matches!(bytes.get(cursor), Some(b'#' | b'/')) {
cursor += 1;
}
let length = Self::run(&bytes[cursor..], |byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
});
(length > 0 && bytes[cursor + length..].starts_with(b"}}")).then_some(cursor + length + 2)
}
fn dunder(bytes: &[u8], at: usize) -> Option<usize> {
if !bytes[at..].starts_with(b"__") {
return None;
}
let run = Self::run(&bytes[at + 2..], |byte| {
byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_'
});
let limit = at + 2 + run;
(at + 5..=limit).rev().find(|&end| &bytes[end - 2..end] == b"__")
}
fn run(bytes: &[u8], accept: impl Fn(u8) -> bool) -> usize {
bytes.iter().take_while(|byte| accept(**byte)).count()
}
}