laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use std::sync::Arc;

use laravel::http::{IntoMiddleware, Method, MiddlewareGroup};
use laravel::routing::{Action, Actions, Handler, Route, Router};
use laravel::str::Str;

use crate::locales::Locales;
use crate::middleware::SetRouteLocale;
use crate::registry::{Entry, Registry, registering};
use crate::route::{join, paths, router_prefix};

type Register = Box<dyn for<'r, 'u> Fn(&'r mut Router, &'u [Method], &'u str) -> &'r mut Route>;

/// The handlers of a resource, one for each action it handles.
///
/// PHP takes a controller class here. Laravel Rust has handler functions, so a resource is the set
/// of them, as with `laravel::routing::Resource`, which cannot be reused because it fixes the
/// `create` and `edit` segments.
///
/// ```ignore
/// ResourceHandlers::new().index(photos::index).create(photos::create).show(photos::show)
/// ```
#[derive(Default)]
#[must_use]
pub struct ResourceHandlers {
    actions: Vec<(Action, Register)>,
}

macro_rules! actions {
    ($($name:ident => $action:ident: $description:literal),* $(,)?) => {
        $(
            #[doc = $description]
            pub fn $name<H, T>(self, handler: H) -> Self
            where
                H: Handler<T>,
                T: 'static,
            {
                self.action(Action::$action, handler)
            }
        )*
    };
}

impl ResourceHandlers {
    /// A resource with no actions yet.
    pub fn new() -> Self {
        Self::default()
    }

    fn action<H, T>(mut self, action: Action, handler: H) -> Self
    where
        H: Handler<T>,
        T: 'static,
    {
        self.actions.retain(|(existing, _)| *existing != action);
        self.actions.push((
            action,
            Box::new(move |router, methods, uri| router.on(methods, uri, handler.clone())),
        ));

        self
    }

    actions! {
        index => Index: "Handle listing the resources: `GET /photos`.",
        create => Create: "Handle showing the form for a new resource: `GET /photos/create`.",
        store => Store: "Handle storing a new resource: `POST /photos`.",
        show => Show: "Handle showing a resource: `GET /photos/{photo}`.",
        edit => Edit: "Handle showing the form for editing a resource: `GET /photos/{photo}/edit`.",
        update => Update: "Handle updating a resource: `PUT` and `PATCH /photos/{photo}`.",
        destroy => Destroy: "Handle deleting a resource: `DELETE /photos/{photo}`.",
    }
}

impl std::fmt::Debug for ResourceHandlers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(self.actions.iter().map(|(action, _)| action))
            .finish()
    }
}

/// A resource registered once per locale.
///
/// ```ignore
/// LocalizedResource::make(
///     route,
///     "photos",
///     locales!["en", "es" => ("fotos", "create" => "crear", "edit" => "editar")],
///     ResourceHandlers::new().index(photos::index).create(photos::create).show(photos::show),
/// )
/// .only([Action::Index, Action::Show]);
/// ```
///
/// With `en` as the default locale that is `/photos`, `/photos/{photo}`, `/es/fotos`,
/// `/es/fotos/crear` and `/es/fotos/{photo}`. The route names use the base name in every locale,
/// as `es.photos.index`, so `route("photos.index")` resolves to the current language, and the
/// parameter is `{photo}` in every locale, derived from the base name, so one `show` handler works
/// whichever language resolved the URL.
///
/// The routes are registered when the value drops, at the end of the statement.
pub struct LocalizedResource<'a> {
    router: &'a mut Router,
    registry: Arc<Registry>,
    name: String,
    api: bool,
    locales: Locales,
    handlers: ResourceHandlers,
    only: Option<Vec<Action>>,
    except: Vec<Action>,
    middleware: Vec<(Option<Vec<Action>>, MiddlewareGroup)>,
    parameter: String,
    base: String,
}

impl<'a> LocalizedResource<'a> {
    fn new(
        router: &'a mut Router,
        name: &str,
        locales: impl Into<Locales>,
        handlers: ResourceHandlers,
        api: bool,
    ) -> Self {
        let name = name.trim_matches('/').to_owned();
        let parameter = name.rsplit('/').next().unwrap_or(&name).replace('-', "_").singular();
        let base = router_prefix(router);

        Self {
            router,
            registry: registering(),
            name,
            api,
            locales: locales.into(),
            handlers,
            only: None,
            except: Vec::new(),
            middleware: Vec::new(),
            parameter,
            base,
        }
    }

    /// Register a localized resource. `name` is the base name, used for route names and
    /// parameters.
    pub fn make(router: &'a mut Router, name: &str, locales: impl Into<Locales>, handlers: ResourceHandlers) -> Self {
        Self::new(router, name, locales, handlers, false)
    }

    /// Register a localized API resource, without the `create` and `edit` routes.
    ///
    /// Localizing an API is rarely what you want, since machines consume its URLs and the language
    /// is usually negotiated with `Accept-Language`.
    pub fn api(router: &'a mut Router, name: &str, locales: impl Into<Locales>, handlers: ResourceHandlers) -> Self {
        Self::new(router, name, locales, handlers, true)
    }

    /// Register only these actions.
    pub fn only(mut self, actions: impl Actions) -> Self {
        self.only = Some(actions.into_actions());

        self
    }

    /// Leave these actions out.
    pub fn except(mut self, actions: impl Actions) -> Self {
        self.except.extend(actions.into_actions());

        self
    }

    /// Add middleware to every action's route in every locale.
    pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
        self.middleware.push((None, middleware.into_group()));

        self
    }

    /// Add middleware to the routes of some actions, in every locale.
    pub fn middleware_for(mut self, actions: impl Actions, middleware: impl IntoMiddleware) -> Self {
        self.middleware
            .push((Some(actions.into_actions()), middleware.into_group()));

        self
    }

    /// Name the route parameter, instead of the singular of the base name.
    pub fn parameter(mut self, name: impl Into<String>) -> Self {
        self.parameter = name.into();

        self
    }

    fn wanted(&self, action: Action) -> bool {
        if self.api && matches!(action, Action::Create | Action::Edit) {
            return false;
        }

        self.only.as_ref().is_none_or(|only| only.contains(&action)) && !self.except.contains(&action)
    }
}

impl Drop for LocalizedResource<'_> {
    fn drop(&mut self) {
        let settings = self.registry.settings().clone();
        let handlers = std::mem::take(&mut self.handlers);

        for definition in self.locales.iter() {
            let segment = definition.uri.clone().unwrap_or_else(|| self.name.clone());
            let verb = |verb: &str| {
                definition
                    .verbs
                    .iter()
                    .find(|(name, _)| name == verb)
                    .map_or_else(|| verb.to_owned(), |(_, translation)| translation.clone())
            };

            for (action, register) in &handlers.actions {
                if !self.wanted(*action) {
                    continue;
                }

                let tail = match action {
                    Action::Index | Action::Store => segment.clone(),
                    Action::Create => format!("{segment}/{}", verb("create")),
                    Action::Show | Action::Update | Action::Destroy => format!("{segment}/{{{}}}", self.parameter),
                    Action::Edit => format!("{segment}/{{{}}}/{}", self.parameter, verb("edit")),
                };
                let methods = methods(*action);
                let single = Locales::new().locale(definition.locale.clone());
                let (_, uri) = paths(&settings, &tail, &single).remove(0);
                let base = format!("{}.{}", self.name, action_name(*action));
                let route = register(self.router, &methods, &uri);

                route.middleware(SetRouteLocale::for_route(definition.locale.clone(), Some(base.clone())));

                for (only, middleware) in &self.middleware {
                    if only.as_ref().is_none_or(|actions| actions.contains(action)) {
                        route.middleware(middleware.clone());
                    }
                }

                self.registry.add(Entry {
                    name: Some(format!("{}.{base}", definition.locale)),
                    base: Some(base),
                    locale: definition.locale.clone(),
                    uri: join(&self.base, &uri),
                    methods: methods.iter().map(|method| method.as_str().to_owned()).collect(),
                });
            }
        }
    }
}

fn methods(action: Action) -> Vec<Method> {
    match action {
        Action::Index | Action::Create | Action::Show | Action::Edit => vec![Method::GET],
        Action::Store => vec![Method::POST],
        Action::Update => vec![Method::PUT, Method::PATCH],
        Action::Destroy => vec![Method::DELETE],
    }
}

fn action_name(action: Action) -> &'static str {
    match action {
        Action::Index => "index",
        Action::Create => "create",
        Action::Store => "store",
        Action::Show => "show",
        Action::Edit => "edit",
        Action::Update => "update",
        Action::Destroy => "destroy",
    }
}