use std::cell::RefCell;
use std::sync::Arc;
use laravel::head::Head;
use laravel::http::{IntoMiddleware, Method, MiddlewareGroup};
use laravel::routing::{Route, Router};
use crate::locales::Locales;
use crate::middleware::SetRouteLocale;
use crate::registry::{Entry, Registry, Settings, registering};
use crate::resource::{LocalizedResource, ResourceHandlers};
type Register = Box<dyn for<'r, 'u> Fn(&'r mut Router, &'u [Method], &'u str) -> &'r mut Route>;
type Configure = Box<dyn Fn(&mut Route)>;
thread_local! {
static GROUPS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
pub struct LocalizedRoute<'a> {
router: &'a mut Router,
registry: Arc<Registry>,
methods: Vec<Method>,
paths: Vec<(String, String)>,
base: String,
register: Register,
middleware: Vec<MiddlewareGroup>,
configure: Vec<Configure>,
name: Option<String>,
}
impl<'a> LocalizedRoute<'a> {
fn new<H, T>(router: &'a mut Router, methods: &[Method], uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
let registry = registering();
let paths = paths(®istry.settings(), uri, &locales.into());
let base = router_prefix(router);
Self {
router,
registry,
methods: methods.to_vec(),
paths,
base,
register: Box::new(move |router, methods, uri| router.on(methods, uri, handler.clone())),
middleware: Vec::new(),
configure: Vec::new(),
name: None,
}
}
#[track_caller]
pub fn get<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::GET], uri, locales, handler)
}
#[track_caller]
pub fn post<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::POST], uri, locales, handler)
}
#[track_caller]
pub fn put<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::PUT], uri, locales, handler)
}
#[track_caller]
pub fn patch<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::PATCH], uri, locales, handler)
}
#[track_caller]
pub fn delete<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::DELETE], uri, locales, handler)
}
#[track_caller]
pub fn options<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &[Method::OPTIONS], uri, locales, handler)
}
#[track_caller]
pub fn any<H, T>(router: &'a mut Router, uri: &str, locales: impl Into<Locales>, handler: H) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, &ANY, uri, locales, handler)
}
#[track_caller]
pub fn r#match<H, T>(
router: &'a mut Router,
methods: &[&str],
uri: &str,
locales: impl Into<Locales>,
handler: H,
) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
let methods: Vec<Method> = methods
.iter()
.map(|method| {
method
.to_ascii_uppercase()
.parse()
.unwrap_or_else(|_| panic!("`{method}` is not an HTTP method"))
})
.collect();
Self::new(router, &methods, uri, locales, handler)
}
#[track_caller]
pub fn on<H, T>(
router: &'a mut Router,
methods: &[Method],
uri: &str,
locales: impl Into<Locales>,
handler: H,
) -> Self
where
H: laravel::routing::Handler<T>,
T: 'static,
{
Self::new(router, methods, uri, locales, handler)
}
pub fn fallback(router: &mut Router) -> &mut Route {
router.fallback(crate::fallback::localized_fallback)
}
pub fn resource<'r>(
router: &'r mut Router,
name: &str,
locales: impl Into<Locales>,
handlers: ResourceHandlers,
) -> LocalizedResource<'r> {
LocalizedResource::make(router, name, locales, handlers)
}
pub fn api_resource<'r>(
router: &'r mut Router,
name: &str,
locales: impl Into<Locales>,
handlers: ResourceHandlers,
) -> LocalizedResource<'r> {
LocalizedResource::api(router, name, locales, handlers)
}
pub fn prefix(prefix: &str) -> LocalizedGroup {
LocalizedGroup {
prefix: prefix.trim_matches('/').to_owned(),
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
self.middleware.push(middleware.into_group());
self
}
pub fn with_head(mut self, head: Head) -> Self {
self.configure.push(Box::new(move |route| {
route.with_head(head.clone());
}));
self
}
pub fn without_middleware<M: 'static>(mut self) -> Self {
self.configure.push(Box::new(|route| {
route.without_middleware::<M>();
}));
self
}
pub fn configure(mut self, configure: impl Fn(&mut Route) + 'static) -> Self {
self.configure.push(Box::new(configure));
self
}
pub fn uris(&self) -> Vec<(String, String)> {
self.paths.clone()
}
}
impl Drop for LocalizedRoute<'_> {
fn drop(&mut self) {
for (locale, uri) in std::mem::take(&mut self.paths) {
let route = (self.register)(self.router, &self.methods, &uri);
route.middleware(SetRouteLocale::for_route(locale.clone(), self.name.clone()));
for middleware in &self.middleware {
route.middleware(middleware.clone());
}
for configure in &self.configure {
configure(route);
}
self.registry.add(Entry {
name: self.name.as_ref().map(|name| format!("{locale}.{name}")),
base: self.name.clone(),
locale,
uri: join(&self.base, &uri),
methods: self.methods.iter().map(|method| method.as_str().to_owned()).collect(),
});
}
}
}
#[derive(Debug, Clone)]
pub struct LocalizedGroup {
prefix: String,
}
impl LocalizedGroup {
#[must_use]
pub fn prefix(mut self, prefix: &str) -> Self {
self.prefix = format!("{}/{}", self.prefix, prefix.trim_matches('/'));
self
}
pub fn group(self, router: &mut Router, routes: impl FnOnce(&mut Router)) {
GROUPS.with(|groups| groups.borrow_mut().push(self.prefix));
routes(router);
GROUPS.with(|groups| {
groups.borrow_mut().pop();
});
}
}
const ANY: [Method; 7] = [
Method::GET,
Method::HEAD,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
];
pub(crate) fn paths(settings: &Settings, uri: &str, locales: &Locales) -> Vec<(String, String)> {
let group = GROUPS.with(|groups| {
groups
.borrow()
.iter()
.map(|prefix| prefix.trim_matches('/').to_owned())
.collect::<Vec<_>>()
});
locales
.iter()
.map(|definition| {
let own = definition.uri.as_deref().unwrap_or(uri);
let segments: Vec<String> = std::iter::once(settings.prefix(&definition.locale))
.chain(group.iter().cloned())
.chain(std::iter::once(own.trim_matches('/').to_owned()))
.filter(|segment| !segment.is_empty())
.collect();
(definition.locale.clone(), format!("/{}", segments.join("/")))
})
.collect()
}
pub(crate) fn router_prefix(router: &mut Router) -> String {
let mut prefix = String::new();
router.group(|group| {
prefix = prefix_in(&format!("{group:?}"));
});
prefix
}
fn prefix_in(debug: &str) -> String {
let Some(start) = debug.find("prefix: \"") else {
return String::new();
};
let mut prefix = String::new();
let mut chars = debug[start + "prefix: \"".len()..].chars();
while let Some(character) = chars.next() {
match character {
'"' => break,
'\\' => prefix.extend(chars.next()),
other => prefix.push(other),
}
}
prefix
}
pub(crate) fn join(prefix: &str, uri: &str) -> String {
let joined = format!("{}/{}", prefix.trim_end_matches('/'), uri.trim_start_matches('/'));
let joined = joined.trim_end_matches('/');
if joined.is_empty() {
"/".to_owned()
} else {
format!("/{}", joined.trim_start_matches('/'))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_router_shows_the_prefix_of_its_group() {
let mut router = Router::default();
assert_eq!(router_prefix(&mut router), "");
router.prefix("/admin").prefix("users").group(|inner| {
assert_eq!(router_prefix(inner), "/admin/users");
});
}
}