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::config::{Config, Env};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

use crate::registry::{Handle, Registry, Settings, begin_registration};
use crate::route::LocalizedRoute;

/// Wires Laralang into the application: its configuration, the registry that names the localized
/// routes, the `route()`, `laralang_alternates()` and `route_is()` functions in the views, and
/// the localized fallback when `fallback` is on.
///
/// Register it after `LaralocaleServiceProvider`, and before the route files that use
/// `LocalizedRoute`:
///
/// ```ignore
/// Application::configure()
///     .with_providers(|providers| {
///         providers.add(LaralocaleServiceProvider::new().with_detection());
///         providers.add(LaralangServiceProvider::new());
///     })
///     .with_config(|config, _| {
///         config.section_mut::<LocaleConfig>().supported = ["en", "es"].map(str::to_owned).to_vec();
///     })
/// ```
#[derive(Clone, Default)]
pub struct LaralangServiceProvider {
    registry: Arc<Registry>,
}

impl LaralangServiceProvider {
    /// The provider.
    pub fn new() -> Self {
        Self::default()
    }
}

impl ServiceProvider for LaralangServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
        config.set(Handle(Arc::clone(&self.registry)));
    }

    fn register(&self, app: &mut Registrar) {
        let settings = Settings::from_config(app.config());
        let fallback = settings.fallback;

        self.registry.configure(settings);

        // The route files run after every provider has registered, without access to the
        // application, so the first of them hands the registry to the ones that follow.
        let registry = Arc::clone(&self.registry);

        app.routing().routes(move |_| begin_registration(registry));

        if fallback {
            app.routing().web(|route| {
                LocalizedRoute::fallback(route);
            });
        }

        #[cfg(feature = "minijinja")]
        app.views().minijinja(crate::views::register);
    }
}