laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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()) };
}

/// Localized routes: a route per language, each with its own path.
///
/// ```ignore
/// use laralang::{LocalizedRoute, locales};
///
/// pub fn routes(route: &mut Router) {
///     LocalizedRoute::get(route, "dashboard", locales!["en", "es" => "panel"], dashboard)
///         .middleware(Authenticate)
///         .name("dashboard");
/// }
/// ```
///
/// With `en` as the default locale, that registers `/dashboard` as `en.dashboard` and `/es/panel`
/// as `es.dashboard`. The routes are registered when the value drops, at the end of the statement.
///
/// The handler is shared by every locale, so it must be `Clone`, which functions and closures
/// that capture nothing are.
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(&registry.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,
        }
    }

    /// Register a localized route for `GET` and `HEAD` requests.
    #[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)
    }

    /// Register a localized route for `POST` requests.
    #[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)
    }

    /// Register a localized route for `PUT` requests.
    #[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)
    }

    /// Register a localized route for `PATCH` requests.
    #[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)
    }

    /// Register a localized route for `DELETE` requests.
    #[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)
    }

    /// Register a localized route for `OPTIONS` requests.
    #[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)
    }

    /// Register a localized route for every method `Router::any` accepts: one route per locale,
    /// each answering them all.
    #[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)
    }

    /// Register a localized route for the given methods, such as `&["PUT", "PATCH"]`.
    ///
    /// # Panics
    ///
    /// Panics when a method is not a valid HTTP method.
    #[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)
    }

    /// Register a localized route for the given methods, as `Router::on` does.
    #[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)
    }

    /// Register the localized fallback, which rescues a URL that exists under another locale
    /// before it becomes a `404`. See [`localized_fallback`](crate::localized_fallback).
    ///
    /// A fallback registered later replaces an earlier one, so call this after your own fallback
    /// only when you want the rescue to take its place.
    pub fn fallback(router: &mut Router) -> &mut Route {
        router.fallback(crate::fallback::localized_fallback)
    }

    /// Register a localized resource, as [`LocalizedResource::make`] does.
    pub fn resource<'r>(
        router: &'r mut Router,
        name: &str,
        locales: impl Into<Locales>,
        handlers: ResourceHandlers,
    ) -> LocalizedResource<'r> {
        LocalizedResource::make(router, name, locales, handlers)
    }

    /// Register a localized API resource, without the `create` and `edit` routes.
    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)
    }

    /// Start a group whose prefix goes after the locale's, as `/es/admin/panel`.
    ///
    /// `Router::prefix` cannot do that: it puts its prefix first, so a localized route inside it
    /// is `/admin/es/panel`. The registry follows the router, so URLs are right either way.
    pub fn prefix(prefix: &str) -> LocalizedGroup {
        LocalizedGroup {
            prefix: prefix.trim_matches('/').to_owned(),
        }
    }

    /// Name the routes. Each one is named after its locale, `es.dashboard`, and `route("dashboard")`
    /// resolves to the current locale's.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());

        self
    }

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

        self
    }

    /// Merge head metadata into every locale's route, as `Route::with_head` does.
    pub fn with_head(mut self, head: Head) -> Self {
        self.configure.push(Box::new(move |route| {
            route.with_head(head.clone());
        }));

        self
    }

    /// Opt every locale's route out of middleware of type `M`.
    pub fn without_middleware<M: 'static>(mut self) -> Self {
        self.configure.push(Box::new(|route| {
            route.without_middleware::<M>();
        }));

        self
    }

    /// Change every locale's route with a closure, for what the other methods do not cover.
    pub fn configure(mut self, configure: impl Fn(&mut Route) + 'static) -> Self {
        self.configure.push(Box::new(configure));

        self
    }

    /// The path each locale's route is registered at, such as `("es", "/es/panel")`.
    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(),
            });
        }
    }
}

/// A group of localized routes that share a prefix, from [`LocalizedRoute::prefix`].
#[derive(Debug, Clone)]
pub struct LocalizedGroup {
    prefix: String,
}

impl LocalizedGroup {
    /// Add another prefix after this one.
    #[must_use]
    pub fn prefix(mut self, prefix: &str) -> Self {
        self.prefix = format!("{}/{}", self.prefix, prefix.trim_matches('/'));

        self
    }

    /// Register the group's routes. Localized routes inside it get the group's prefix after their
    /// locale's. Routes registered with `route.get(..)` are not affected.
    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,
];

/// The path of each locale: its prefix, the group's prefix, then its own URI.
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()
}

/// The prefix of the router's own group, which the router adds in front of a route's URI.
///
/// The router offers no way to read it, but a group starts as an empty router with the same
/// attributes, so printing one shows it. The tests fail if the output stops carrying it.
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");
        });
    }
}