laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use laralocale::LocaleConfig;
use laravel::config::Config;
use laravel::context::Context;

use crate::config::LaralangConfig;
use crate::pattern;

/// What the package reads from the configuration, resolved once when the application is built.
#[derive(Debug, Clone)]
pub struct Settings {
    /// The locales that get routes, in order.
    pub locales: Vec<String>,
    /// The default locale, which has no prefix unless it is given one.
    pub default_locale: String,
    /// The session key `SetRouteLocale` stores the locale under.
    pub session_key: String,
    prefixes: HashMap<String, String>,
    /// Whether the localized fallback is registered by the provider.
    pub fallback: bool,
    /// The `max-age` of permanent redirects, in seconds.
    pub redirect_max_age: u64,
}

impl Settings {
    /// Read the settings from a final configuration.
    pub fn from_config(config: &Config) -> Self {
        let own = config
            .get::<LaralangConfig>()
            .cloned()
            .unwrap_or_else(|| LaralangConfig {
                locales: Vec::new(),
                prefixes: HashMap::new(),
                fallback: false,
                redirect_max_age: 86_400,
            });
        let locale = config.get::<LocaleConfig>().cloned().unwrap_or_default();
        let locales = if !own.locales.is_empty() {
            own.locales.clone()
        } else if !locale.supported.is_empty() {
            locale.supported.clone()
        } else {
            vec![locale.locale.clone()]
        };

        Self {
            locales,
            default_locale: locale.locale.clone(),
            session_key: locale.detect.session.clone(),
            prefixes: own.prefixes,
            fallback: own.fallback,
            redirect_max_age: own.redirect_max_age,
        }
    }

    /// The URL prefix of a locale, without slashes.
    ///
    /// A value in the configuration is the literal prefix. Without one, the locale code is used,
    /// except for the default locale, which never carries a prefix. An empty string counts as no
    /// value: only the default locale can live at the root, so two locales can never end up
    /// sharing the same URLs.
    pub fn prefix(&self, locale: &str) -> String {
        let configured = self.prefixes.get(locale).map_or("", String::as_str).trim_matches('/');

        if !configured.is_empty() {
            return configured.to_owned();
        }

        if locale == self.default_locale {
            String::new()
        } else {
            locale.to_owned()
        }
    }

    /// The URL prefix of every configured locale, in order.
    pub fn prefixes(&self) -> Vec<(String, String)> {
        self.locales
            .iter()
            .map(|locale| (locale.clone(), self.prefix(locale)))
            .collect()
    }

    /// Whether the locale is one of the configured ones.
    pub fn has_locale(&self, locale: &str) -> bool {
        self.locales.iter().any(|configured| configured == locale)
    }
}

/// One localized route as the registry knows it.
#[derive(Debug, Clone)]
pub struct Entry {
    /// The full route name, such as `es.profile`. Unnamed routes have none.
    pub name: Option<String>,
    /// The name without its locale, such as `profile`.
    pub base: Option<String>,
    /// The locale the route belongs to.
    pub locale: String,
    /// The URI pattern, with its leading slash, such as `/es/perfil/{user}`.
    pub uri: String,
    /// The HTTP methods the route answers.
    pub methods: Vec<String>,
}

#[derive(Default)]
struct Routes {
    entries: Vec<Arc<Entry>>,
    by_name: HashMap<String, Arc<Entry>>,
}

/// The record of the localized routes: their names and their URIs per locale.
///
/// Laravel Rust 0.1 has no named routes, so this is where `route("es.profile")` finds its URI. Every
/// route registered through [`LocalizedRoute`](crate::LocalizedRoute) and
/// [`LocalizedResource`](crate::LocalizedResource) is recorded here, and the application has one,
/// created by the [`LaralangServiceProvider`](crate::LaralangServiceProvider).
#[derive(Default)]
pub struct Registry {
    settings: RwLock<Option<Arc<Settings>>>,
    routes: RwLock<Routes>,
}

impl Registry {
    /// A registry with no settings and no routes.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn configure(&self, settings: Settings) {
        *self.settings.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(settings));
    }

    /// The settings, once the application has registered its providers.
    ///
    /// # Panics
    ///
    /// Panics before the `LaralangServiceProvider` has registered, which means it is missing.
    pub fn settings(&self) -> Arc<Settings> {
        self.settings
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
            .expect("the LaralangServiceProvider is not registered: add it to the application's providers")
    }

    /// Record a route. A later route with the same name replaces the earlier one.
    pub fn add(&self, entry: Entry) {
        let entry = Arc::new(entry);
        let mut routes = self.routes.write().unwrap_or_else(std::sync::PoisonError::into_inner);

        if let Some(name) = &entry.name {
            routes.by_name.insert(name.clone(), Arc::clone(&entry));
        }

        routes.entries.push(entry);
    }

    /// The route with this full name, such as `es.profile`.
    pub fn get(&self, name: &str) -> Option<Arc<Entry>> {
        self.read().by_name.get(name).cloned()
    }

    /// Whether a route has this full name.
    pub fn has(&self, name: &str) -> bool {
        self.read().by_name.contains_key(name)
    }

    /// Every recorded route, in registration order.
    pub fn entries(&self) -> Vec<Arc<Entry>> {
        self.read().entries.clone()
    }

    /// Whether a path is served by any localized route that answers `GET`.
    pub fn serves(&self, path: &str) -> bool {
        self.read()
            .entries
            .iter()
            .any(|entry| entry.methods.iter().any(|method| method == "GET") && pattern::matches(&entry.uri, path))
    }

    fn read(&self) -> std::sync::RwLockReadGuard<'_, Routes> {
        self.routes.read().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// The registry of the running application.
    ///
    /// # Panics
    ///
    /// Panics outside the application, or when the `LaralangServiceProvider` is not registered.
    pub fn current() -> Arc<Self> {
        Self::try_current()
            .expect("the LaralangServiceProvider is not registered: add it to the application's providers")
    }

    /// The registry of the running application, or `None` outside it.
    pub fn try_current() -> Option<Arc<Self>> {
        Context::current()?;

        laravel::config().get::<Handle>().map(|handle| Arc::clone(&handle.0))
    }
}

impl std::fmt::Debug for Registry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Registry")
            .field("routes", &self.read().entries.len())
            .finish_non_exhaustive()
    }
}

/// How the registry travels in the configuration, which helpers can read without awaiting.
#[derive(Clone)]
pub(crate) struct Handle(pub(crate) Arc<Registry>);

thread_local! {
    static REGISTERING: RefCell<Option<Arc<Registry>>> = const { RefCell::new(None) };
}

/// Make a registry the one that `LocalizedRoute` and `LocalizedResource` record into, for the
/// route files that run after this call on this thread.
pub(crate) fn begin_registration(registry: Arc<Registry>) {
    REGISTERING.with(|current| *current.borrow_mut() = Some(registry));
}

/// The registry the routes being registered are recorded into.
///
/// # Panics
///
/// Panics when the `LaralangServiceProvider` is not registered, since nothing set it.
pub(crate) fn registering() -> Arc<Registry> {
    REGISTERING.with(|current| {
        current.borrow().clone().expect(
            "LocalizedRoute needs the LaralangServiceProvider: add it to the application's providers, \
             before the route files that use it",
        )
    })
}