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 std::cell::RefCell;
use std::future::Future;

use laravel::context::Context;

use crate::config::{LocaleConfig, find};

tokio::task_local! {
    static CURRENT: RefCell<String>;
}

/// The current language, such as `en`: the one `set_locale` chose for this request, command or
/// job, or else `APP_LOCALE`.
///
/// It is `laravel::lang::locale()` in Laravel Rust's own localization.
pub fn locale() -> String {
    CURRENT
        .try_with(|current| current.borrow().clone())
        .unwrap_or_else(|_| config().locale)
}

/// Sets the language of the rest of the current request, command or job, such as `es` or `pt_BR`.
///
/// Every `locale()` after it, in the handler, the views and the middleware that run later,
/// returns the new language. Concurrent requests keep their own. Nothing is validated: the
/// locale does not have to be one the application speaks.
///
/// Outside a request, which has its own scope, and outside `with_locale`, there is nowhere to
/// keep the language, so the call is ignored and a warning is logged.
///
/// It is `laravel::lang::set_locale` in Laravel Rust's own localization.
pub fn set_locale(locale: impl Into<String>) {
    let locale = locale.into();
    let stored = CURRENT.try_with(|current| *current.borrow_mut() = locale.clone());

    if stored.is_err() {
        tracing::warn!(
            locale,
            "set_locale was called outside a request or with_locale and was ignored"
        );
    }
}

/// The fallback language, `APP_FALLBACK_LOCALE`: the one translations fall back to. It does not
/// follow the current locale.
pub fn fallback_locale() -> String {
    config().fallback_locale
}

/// The languages the application speaks: `APP_LOCALE` followed by the languages that have a
/// `{locale}.json` file in the `lang` directory, or the `supported` list of `LocaleConfig` when
/// it is set.
pub fn locales() -> Vec<String> {
    config().locales()
}

/// The language of the application that best matches `preferred`, a list of language tags such
/// as `es-mx`, most preferred first, or `APP_LOCALE` when none matches.
///
/// `es-MX` matches `es`, `pt` matches `pt_BR`, case and `-` versus `_` are ignored, and the
/// wildcard `*` stands for `APP_LOCALE`.
pub fn negotiate(preferred: &[String]) -> String {
    let config = config();
    let locales = config.locales();

    for tag in preferred {
        if tag == "*" {
            return config.locale;
        }

        if let Some(found) = find(&locales, tag) {
            return found.to_owned();
        }
    }

    config.locale
}

/// The languages to look in for `locale`, in order: the locale, its language without the region
/// (`pt` for `pt_BR`), and the same for `APP_FALLBACK_LOCALE`, without repeats.
///
/// `candidates("pt_BR")` is `["pt_BR", "pt", "en"]` with the default fallback.
pub fn candidates(locale: &str) -> Vec<String> {
    config().candidates(locale)
}

/// Runs a future in a language, for jobs, commands and tests.
///
/// The language applies to the future and to what it awaits, and is gone when it ends. Scopes
/// nest, and a `set_locale` inside one does not leak into the one around it. A task you spawn
/// with `tokio::spawn` does not inherit it: wrap its future in `with_locale` as well.
///
/// ```ignore
/// laralocale::with_locale("es", async {
///     assert_eq!(laralocale::locale(), "es");
/// })
/// .await;
/// ```
pub async fn with_locale<F: Future>(locale: impl Into<String>, future: F) -> F::Output {
    CURRENT.scope(RefCell::new(locale.into()), future).await
}

/// A copy of the application's `LocaleConfig`, or its defaults when there is no application,
/// such as in a plain `tokio` test.
pub(crate) fn config() -> LocaleConfig {
    if Context::current().is_none() {
        return LocaleConfig::default();
    }

    laravel::config().get::<LocaleConfig>().cloned().unwrap_or_default()
}