laralocale 0.1.0

The current locale for Laravel Rust, with the API of laravel::lang: locale, set_locale, locales, negotiate and preferred_locale.
Documentation
use laravel::config::Section;
use laravel::context::Context;

/// Where `DetectLocale` looks for the locale of a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetectSource {
    /// The session value named by `detect.session`.
    Session,
    /// The cookie named by `detect.cookie`.
    Cookie,
    /// The `Accept-Language` header, honouring q-values.
    Header,
    /// The query string parameter named by `detect.query`.
    Query,
}

/// How `DetectLocale` detects the locale.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DetectSettings {
    /// The sources to try, in order. The first one that yields a supported locale wins.
    pub sources: Vec<DetectSource>,
    /// The session key.
    pub session: String,
    /// The cookie name.
    pub cookie: String,
    /// The query string parameter.
    pub query: String,
}

impl Default for DetectSettings {
    fn default() -> Self {
        Self {
            sources: vec![
                DetectSource::Query,
                DetectSource::Session,
                DetectSource::Cookie,
                DetectSource::Header,
            ],
            session: "locale".to_owned(),
            cookie: "locale".to_owned(),
            query: "locale".to_owned(),
        }
    }
}

/// The package's configuration: the equivalent of the `app.locale` and `app.fallback_locale` of
/// Laravel Rust's own localization, plus the `supported` and `detect` settings of this crate.
///
/// `locale` and `fallback_locale` read `APP_LOCALE` and `APP_FALLBACK_LOCALE`, as Laravel's
/// `config/app.php` does. The rest is set in `src/app.rs` with `with_config`.
#[derive(Debug, Clone, Section)]
pub struct LocaleConfig {
    /// The default locale: what `locale()` returns until `set_locale` chooses another, and what
    /// `negotiate` returns when nothing matches.
    #[env("APP_LOCALE", default = "en")]
    pub locale: String,

    /// The locale translations fall back to. `fallback_locale()` returns it.
    #[env("APP_FALLBACK_LOCALE", default = "en")]
    pub fallback_locale: String,

    /// The locales the application speaks. When it is empty, they are `locale` plus the languages
    /// that have a `{locale}.json` file in the `lang` directory, as in Laravel Rust's own
    /// localization. Set it to name them yourself.
    pub supported: Vec<String>,

    /// How `DetectLocale` detects the locale.
    pub detect: DetectSettings,
}

impl LocaleConfig {
    /// The languages the application speaks: `supported` when it is set, else `locale` followed
    /// by the languages of the `lang` directory, sorted.
    pub fn locales(&self) -> Vec<String> {
        if !self.supported.is_empty() {
            return self.supported.clone();
        }

        let mut others: Vec<String> = lang_files()
            .into_iter()
            .filter(|locale| !same_locale(locale, &self.locale))
            .collect();

        others.sort();

        std::iter::once(self.locale.clone()).chain(others).collect()
    }

    /// The locale of the application that a tag stands for, spelled as the application spells it.
    ///
    /// The comparison ignores case and treats `-` as `_`. A tag such as `es-MX` matches `es_MX`
    /// exactly, then the first locale of the same language, such as `es`, and `pt` matches `pt_BR`.
    pub fn match_supported(&self, tag: &str) -> Option<String> {
        find(&self.locales(), tag).map(str::to_owned)
    }

    /// The locales to look in for a locale, in order: the locale, its language without the region
    /// (`pt` for `pt_BR`), then the same two for `fallback_locale`, without repeats.
    pub fn candidates(&self, locale: &str) -> Vec<String> {
        let mut found: Vec<String> = Vec::with_capacity(4);

        for candidate in [
            locale,
            language(locale),
            &self.fallback_locale,
            language(&self.fallback_locale),
        ] {
            if !found.iter().any(|earlier| same_locale(earlier, candidate)) {
                found.push(candidate.to_owned());
            }
        }

        found
    }
}

/// The position-wise best locale for a tag: the same locale, else the first of the same language.
pub(crate) fn find<'a>(locales: &'a [String], tag: &str) -> Option<&'a str> {
    locales
        .iter()
        .find(|locale| same_locale(locale, tag))
        .or_else(|| {
            locales
                .iter()
                .find(|locale| same_locale(language(locale), language(tag)))
        })
        .map(String::as_str)
}

/// The languages that have a top-level `{locale}.json` file in the `lang` directory.
fn lang_files() -> Vec<String> {
    if Context::current().is_none() {
        return Vec::new();
    }

    let directory = laravel::config().app.base_path.join("lang");

    let Ok(entries) = std::fs::read_dir(directory) else {
        return Vec::new();
    };

    entries
        .filter_map(Result::ok)
        .filter(|entry| entry.path().is_file())
        .filter_map(|entry| {
            let name = entry.file_name().into_string().ok()?;
            let locale = name.strip_suffix(".json")?;

            (!locale.is_empty() && !locale.starts_with('.')).then(|| locale.to_owned())
        })
        .collect()
}

pub(crate) fn language(locale: &str) -> &str {
    locale.split(['_', '-']).next().unwrap_or(locale)
}

/// Whether two locales name the same language, ignoring case and `-` versus `_`.
pub(crate) fn same_locale(left: &str, right: &str) -> bool {
    normalize(left) == normalize(right)
}

fn normalize(locale: &str) -> String {
    locale.trim().replace('-', "_").to_lowercase()
}