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>;
#[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 {
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()
}
}
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,
}
}
pub fn make(router: &'a mut Router, name: &str, locales: impl Into<Locales>, handlers: ResourceHandlers) -> Self {
Self::new(router, name, locales, handlers, false)
}
pub fn api(router: &'a mut Router, name: &str, locales: impl Into<Locales>, handlers: ResourceHandlers) -> Self {
Self::new(router, name, locales, handlers, true)
}
pub fn only(mut self, actions: impl Actions) -> Self {
self.only = Some(actions.into_actions());
self
}
pub fn except(mut self, actions: impl Actions) -> Self {
self.except.extend(actions.into_actions());
self
}
pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
self.middleware.push((None, middleware.into_group()));
self
}
pub fn middleware_for(mut self, actions: impl Actions, middleware: impl IntoMiddleware) -> Self {
self.middleware
.push((Some(actions.into_actions()), middleware.into_group()));
self
}
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",
}
}