use laravel::config::Section;
use laravel::context::Context;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetectSource {
Session,
Cookie,
Header,
Query,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DetectSettings {
pub sources: Vec<DetectSource>,
pub session: String,
pub cookie: String,
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(),
}
}
}
#[derive(Debug, Clone, Section)]
pub struct LocaleConfig {
#[env("APP_LOCALE", default = "en")]
pub locale: String,
#[env("APP_FALLBACK_LOCALE", default = "en")]
pub fallback_locale: String,
pub supported: Vec<String>,
pub detect: DetectSettings,
}
impl LocaleConfig {
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()
}
pub fn match_supported(&self, tag: &str) -> Option<String> {
find(&self.locales(), tag).map(str::to_owned)
}
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
}
}
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)
}
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)
}
pub(crate) fn same_locale(left: &str, right: &str) -> bool {
normalize(left) == normalize(right)
}
fn normalize(locale: &str) -> String {
locale.trim().replace('-', "_").to_lowercase()
}