larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
//! Small helpers shared by the rest of the crate: slugs, localized values, `data_get`, dates and
//! the PHP word count.

use std::sync::LazyLock;

use laravel::str::Str;
use laravel::time::{Timestamp, civil, tz::TimeZone};
use regex::Regex;
use serde_json::Value;

/// `Str::slug` as Laravel PHP has it: transliterated to ASCII first, so `Ingeniería` is
/// `ingenieria`. Laravel Rust 0.1's own `slug` keeps the accents.
pub fn slug(text: &str) -> String {
    text.ascii().slug()
}

/// `Str::headline`.
pub fn headline(text: &str) -> String {
    text.headline()
}

/// A value written once for every language, or per language: the locale's entry, then the
/// fallback locale's, then the first one.
pub fn localized(value: Option<&Value>, locale: &str, fallback: &str) -> Option<String> {
    let value = value?;

    let picked = match value {
        Value::Object(map) => map
            .get(locale)
            .or_else(|| map.get(fallback))
            .or_else(|| map.values().next())?,
        other => other,
    };

    scalar_text(picked).filter(|text| !text.is_empty())
}

/// A scalar as the text PHP's `(string)` cast gives.
pub fn scalar_text(value: &Value) -> Option<String> {
    match value {
        Value::String(text) => Some(text.clone()),
        Value::Number(number) => Some(number.to_string()),
        Value::Bool(true) => Some("1".to_owned()),
        Value::Bool(false) => Some(String::new()),
        _ => None,
    }
}

/// PHP's `(bool)` cast of a frontmatter value.
pub fn truthy(value: Option<&Value>) -> bool {
    match value {
        None | Some(Value::Null) => false,
        Some(Value::Bool(value)) => *value,
        Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.0),
        Some(Value::String(text)) => !text.is_empty() && text != "0",
        Some(Value::Array(items)) => !items.is_empty(),
        Some(Value::Object(map)) => !map.is_empty(),
    }
}

/// Laravel's `data_get` with dot notation, on a JSON value.
pub fn data_get<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
    path.split('.').try_fold(value, |current, segment| match current {
        Value::Object(map) => map.get(segment),
        Value::Array(items) => segment.parse::<usize>().ok().and_then(|index| items.get(index)),
        _ => None,
    })
}

static TAGS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<[^>]*>").expect("a valid pattern"));
static DATE_ONLY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d{4}-\d{2}-\d{2}$").expect("a valid pattern"));
static WORDS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[A-Za-z][A-Za-z'-]*").expect("a valid pattern"));

/// `str_word_count(strip_tags($text))`. PHP counts words in the C locale, where only ASCII
/// letters, `'` and `-` belong to a word, so `información` is two words. The count is kept so a
/// post's reading time is the one the PHP package gives it.
pub fn word_count(html: &str) -> usize {
    WORDS.find_iter(&TAGS.replace_all(html, "")).count()
}

/// Parse a date the way `Carbon::parse` reads the formats a frontmatter uses, in UTC.
pub fn parse_date(text: &str) -> Option<Timestamp> {
    let text = text.trim();

    if text.is_empty() {
        return None;
    }

    if let Ok(timestamp) = text.parse::<Timestamp>() {
        return Some(timestamp);
    }

    let utc = TimeZone::UTC;

    if DATE_ONLY.is_match(text) {
        let date = text.parse::<civil::Date>().ok()?;

        return date.to_zoned_datetime(utc).ok().map(|zoned| zoned.timestamp());
    }

    let normalized = text.replacen(' ', "T", 1);

    if let Ok(date_time) = normalized.parse::<civil::DateTime>() {
        return date_time.to_zoned_datetime(utc).ok().map(|zoned| zoned.timestamp());
    }

    None
}

/// `2026-09-01T00:00:00+00:00`, Carbon's `toAtomString()` for a UTC date.
pub fn atom(timestamp: Timestamp) -> String {
    timestamp.strftime("%Y-%m-%dT%H:%M:%S+00:00").to_string()
}

/// `Tue, 01 Sep 2026 00:00:00 +0000`, Carbon's `toRssString()` for a UTC date.
pub fn rss(timestamp: Timestamp) -> String {
    timestamp.strftime("%a, %d %b %Y %H:%M:%S +0000").to_string()
}

/// `2026-09-01`, Carbon's `toDateString()`.
pub fn date_string(timestamp: Timestamp) -> String {
    timestamp.strftime("%Y-%m-%d").to_string()
}

/// A long date in the language of the page, Carbon's `isoFormat('LL')`: `September 1, 2026`,
/// `1 de septiembre de 2026`. Languages the crate has no month names for get the ISO date.
pub fn long_date(timestamp: Timestamp, locale: &str) -> String {
    let date = timestamp.to_zoned_datetime(TimeZone::UTC).date();
    let (year, month, day) = (date.year(), usize::try_from(date.month()).unwrap_or(1), date.day());
    let language = locale.split(['-', '_']).next().unwrap_or(locale).to_ascii_lowercase();
    let month_name = |names: &[&'static str; 12]| names[month - 1];

    match language.as_str() {
        "en" => format!("{} {day}, {year}", month_name(&EN)),
        "es" => format!("{day} de {} de {year}", month_name(&ES)),
        "ca" => {
            let name = month_name(&CA);
            let article = if name.starts_with(['a', 'o']) { "d'" } else { "de " };

            format!("{day} {article}{name} de {year}")
        }
        "gl" => format!("{day} de {} de {year}", month_name(&GL)),
        "pt" => format!("{day} de {} de {year}", month_name(&PT)),
        "fr" => format!("{day} {} {year}", month_name(&FR)),
        "it" => format!("{day} {} {year}", month_name(&IT)),
        "de" => format!("{day}. {} {year}", month_name(&DE)),
        _ => date_string(timestamp),
    }
}

const EN: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];
const ES: [&str; 12] = [
    "enero",
    "febrero",
    "marzo",
    "abril",
    "mayo",
    "junio",
    "julio",
    "agosto",
    "septiembre",
    "octubre",
    "noviembre",
    "diciembre",
];
const CA: [&str; 12] = [
    "gener", "febrer", "març", "abril", "maig", "juny", "juliol", "agost", "setembre", "octubre", "novembre",
    "desembre",
];
const GL: [&str; 12] = [
    "xaneiro", "febreiro", "marzo", "abril", "maio", "xuño", "xullo", "agosto", "setembro", "outubro", "novembro",
    "decembro",
];
const PT: [&str; 12] = [
    "janeiro",
    "fevereiro",
    "março",
    "abril",
    "maio",
    "junho",
    "julho",
    "agosto",
    "setembro",
    "outubro",
    "novembro",
    "dezembro",
];
const FR: [&str; 12] = [
    "janvier",
    "février",
    "mars",
    "avril",
    "mai",
    "juin",
    "juillet",
    "août",
    "septembre",
    "octobre",
    "novembre",
    "décembre",
];
const IT: [&str; 12] = [
    "gennaio",
    "febbraio",
    "marzo",
    "aprile",
    "maggio",
    "giugno",
    "luglio",
    "agosto",
    "settembre",
    "ottobre",
    "novembre",
    "dicembre",
];
const DE: [&str; 12] = [
    "Januar",
    "Februar",
    "März",
    "April",
    "Mai",
    "Juni",
    "Juli",
    "August",
    "September",
    "Oktober",
    "November",
    "Dezember",
];

/// The languages of a collection: its own, else the `supported` ones of `laralocale`, else the
/// application's; without repeats and with the application's language first when it is among them.
pub fn resolve_locales(configured: Option<&[String]>, supported: &[String], default: &str) -> Vec<String> {
    let source: Vec<String> = match configured {
        Some(locales) => locales.to_vec(),
        None if supported.is_empty() => vec![default.to_owned()],
        None => supported.to_vec(),
    };

    let mut locales: Vec<String> = Vec::new();

    for locale in source {
        if !locales.contains(&locale) {
            locales.push(locale);
        }
    }

    if let Some(position) = locales.iter().position(|locale| locale == default) {
        let first = locales.remove(position);

        locales.insert(0, first);
    }

    locales
}