laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use laralocale::{DetectLocale, DetectSource, LocaleConfig};
use laravel::http::{Middleware, Next, Redirect, Request, Response};

use crate::current::{self, Current, Matched};
use crate::registry::{Registry, Settings};

/// The locale of the URL.
///
/// Every route registered by `LocalizedRoute` and `LocalizedResource` carries one that knows its
/// own locale and name. Used by itself, as `SetRouteLocale::new()`, it reads the locale from the
/// first segment of the path, and from the session when that is not a locale.
///
/// A first segment that is the default locale, when the default locale has no prefix, is
/// redirected with a `301` to the same URL without it, so each page has one canonical URL.
///
/// The locale is kept for the rest of the request with `laralocale::with_locale`, and stored in
/// the session under laralocale's `detect.session` key. Every locale middleware is idempotent:
/// the first one to run resolves the locale and the rest only pass the request on.
#[derive(Debug, Clone, Default)]
pub struct SetRouteLocale {
    route: Option<Bound>,
}

#[derive(Debug, Clone)]
struct Bound {
    locale: String,
    base: Option<String>,
}

impl SetRouteLocale {
    /// The middleware that reads the locale from the URL.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn for_route(locale: impl Into<String>, base: Option<String>) -> Self {
        Self {
            route: Some(Bound {
                locale: locale.into(),
                base,
            }),
        }
    }
}

impl Middleware for SetRouteLocale {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let registry = Registry::current();
        let settings = registry.settings();
        let previous = current::get().unwrap_or_default();
        let mut locale = None;

        if !previous.resolved {
            let segment = first_segment(&request);
            let default = &settings.default_locale;

            if segment == *default && settings.prefix(default).is_empty() {
                return Ok(strip_default_prefix(&request, &settings));
            }

            let resolved = match &self.route {
                Some(bound) => bound.locale.clone(),
                None if settings.has_locale(&segment) => segment,
                None => session_locale(&request, &settings).unwrap_or_else(|| default.clone()),
            };

            remember(&request, &settings, &resolved);
            locale = Some(resolved);
        }

        let matched = self.route.as_ref().map(|bound| Matched {
            name: bound.base.as_ref().map(|base| format!("{}.{base}", bound.locale)),
            base: bound.base.clone(),
            params: request
                .current_route()
                .map(|route| route.params().to_vec())
                .unwrap_or_default(),
        });
        let state = Current {
            resolved: true,
            route: matched.or(previous.route),
        };

        Ok(match locale {
            Some(locale) => laralocale::with_locale(locale, current::scope(state, next.run(request))).await,
            None => current::scope(state, next.run(request)).await,
        })
    }
}

/// The locale stored in the session, when it is one of the configured locales.
#[derive(Debug, Clone, Copy, Default)]
pub struct SetSessionLocale;

impl Middleware for SetSessionLocale {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let previous = current::get().unwrap_or_default();

        if previous.resolved {
            return Ok(next.run(request).await);
        }

        let registry = Registry::current();
        let settings = registry.settings();
        let locale = session_locale(&request, &settings).unwrap_or_else(|| settings.default_locale.clone());
        let state = Current {
            resolved: true,
            ..previous
        };

        Ok(laralocale::with_locale(locale, current::scope(state, next.run(request))).await)
    }
}

/// The locale of the visitor's browser, read from `Accept-Language` the first time and stored in
/// the session, so the rest of the visit keeps it.
#[derive(Debug, Clone, Copy, Default)]
pub struct SetBrowserLocale;

impl Middleware for SetBrowserLocale {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let previous = current::get().unwrap_or_default();

        if previous.resolved {
            return Ok(next.run(request).await);
        }

        let registry = Registry::current();
        let settings = registry.settings();
        let locale = match session_locale(&request, &settings) {
            Some(locale) => locale,
            None => {
                let mut config = locale_config();

                config.detect.sources = vec![DetectSource::Header];

                let detected = DetectLocale::resolve(&request, &config);
                let locale = if settings.has_locale(&detected) {
                    detected
                } else {
                    settings.default_locale.clone()
                };

                remember(&request, &settings, &locale);

                locale
            }
        };
        let state = Current {
            resolved: true,
            ..previous
        };

        Ok(laralocale::with_locale(locale, current::scope(state, next.run(request))).await)
    }
}

/// The universal middleware: the URL prefix first, then the session, then the browser.
#[derive(Debug, Clone, Copy, Default)]
pub struct SetSmartLocale;

impl Middleware for SetSmartLocale {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        if current::get().is_some_and(|current| current.resolved) {
            return Ok(next.run(request).await);
        }

        let registry = Registry::current();

        if registry.settings().has_locale(&first_segment(&request)) {
            return SetRouteLocale::new().handle(request, next).await;
        }

        SetBrowserLocale.handle(request, next).await
    }
}

fn first_segment(request: &Request) -> String {
    request
        .path()
        .trim_start_matches('/')
        .split('/')
        .next()
        .unwrap_or_default()
        .to_owned()
}

fn locale_config() -> LocaleConfig {
    laravel::config().get::<LocaleConfig>().cloned().unwrap_or_default()
}

fn session_locale(request: &Request, settings: &Settings) -> Option<String> {
    let locale: String = request.session().ok()?.get(&settings.session_key)?;

    settings.has_locale(&locale).then_some(locale)
}

fn remember(request: &Request, settings: &Settings, locale: &str) {
    if let Ok(session) = request.session()
        && session.get::<String>(&settings.session_key).as_deref() != Some(locale)
    {
        session.put(&settings.session_key, locale);
    }
}

/// `/en/about?x=1` as `/about?x=1`, permanently, for a bounded time.
fn strip_default_prefix(request: &Request, settings: &Settings) -> Response {
    let target = request.uri().path_and_query().map_or("/", |target| target.as_str());
    let rest = target
        .trim_start_matches('/')
        .strip_prefix(settings.default_locale.as_str())
        .unwrap_or_default();
    let location = format!("/{}", rest.trim_start_matches('/'));

    Response::new(
        Redirect::to(location)
            .permanent()
            .with_header("cache-control", format!("max-age={}", settings.redirect_max_age)),
    )
}