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::http::{Middleware, Next, Request, Response};

use crate::config::{DetectSource, LocaleConfig};
use crate::locale::{config, with_locale};

/// A convenience that resolves the locale of each request from several sources and keeps it for
/// the rest of the request.
///
/// Laravel Rust's own localization has no such middleware: there you call
/// `set_locale(request.preferred_locale())` yourself. Use `DetectLocale` when the visitor can
/// also choose a language in the session, a cookie or the query string.
///
/// It tries the sources of `detect.sources` in order and takes the first value that is a
/// supported locale. A value that is not supported is skipped, and when no source yields one the
/// request gets the configured `locale`. After it, `locale()` returns the result, and a later
/// middleware or handler may call `set_locale` to change it for the rest of the request.
///
/// It is not added by default. `LaralocaleServiceProvider::new().with_detection()` appends it to
/// the `web` group, after the session starts, or you attach it to the `api` group or to a single
/// route yourself.
///
/// ```ignore
/// route.get("/", home).middleware(DetectLocale);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct DetectLocale;

impl DetectLocale {
    /// The locale this request carries, or the configured default.
    pub fn resolve(request: &Request, config: &LocaleConfig) -> String {
        config
            .detect
            .sources
            .iter()
            .find_map(|source| match source {
                DetectSource::Session => session(request, config),
                DetectSource::Cookie => request
                    .cookie(&config.detect.cookie)
                    .and_then(|value| config.match_supported(&value)),
                DetectSource::Header => request
                    .header("accept-language")
                    .and_then(|value| from_header(value, config)),
                DetectSource::Query => query(request, config),
            })
            .unwrap_or_else(|| config.locale.clone())
    }
}

impl Middleware for DetectLocale {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let config = config();
        let detected = Self::resolve(&request, &config);

        Ok(with_locale(detected, next.run(request)).await)
    }
}

fn session(request: &Request, config: &LocaleConfig) -> Option<String> {
    let value: String = request.session().ok()?.get(&config.detect.session)?;

    config.match_supported(&value)
}

fn query(request: &Request, config: &LocaleConfig) -> Option<String> {
    let query = request.uri().query()?;

    form_urlencoded::parse(query.as_bytes())
        .filter(|(name, _)| *name == config.detect.query)
        .last()
        .and_then(|(_, value)| config.match_supported(&value))
}

fn from_header(header: &str, config: &LocaleConfig) -> Option<String> {
    languages(header)
        .into_iter()
        .find_map(|language| config.match_supported(language))
}

/// The languages of an `Accept-Language` header, best first. A language with `q=0` and the
/// wildcard are left out, and languages of equal weight keep the order they were sent in.
pub(crate) fn languages(header: &str) -> Vec<&str> {
    let mut weighted: Vec<(&str, f32)> = header
        .split(',')
        .filter_map(|part| {
            let mut pieces = part.split(';');
            let tag = pieces.next()?.trim();
            let weight = pieces
                .find_map(|parameter| parameter.trim().strip_prefix("q=").map(str::trim))
                .map_or(Some(1.0), |value| value.parse::<f32>().ok())?;

            (!tag.is_empty() && tag != "*" && weight > 0.0).then_some((tag, weight))
        })
        .collect();

    weighted.sort_by(|a, b| b.1.total_cmp(&a.1));

    weighted.into_iter().map(|(tag, _)| tag).collect()
}

#[cfg(test)]
mod tests {
    use super::languages;

    #[test]
    fn orders_languages_by_weight_and_keeps_ties_in_order() {
        assert_eq!(languages("fr;q=0.5, es-ES, en;q=0.8, de"), ["es-ES", "de", "en", "fr"]);
    }

    #[test]
    fn drops_the_wildcard_zero_weights_and_garbage() {
        assert_eq!(languages("*, en;q=0, ;q=1, es;q=abc, ca;q=0.1"), ["ca"]);
    }
}