larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::http::MiddlewareGroup;

use crate::larablog::{Larablog, Runtime};
use crate::{LarablogConfig, http};

/// Wires Larablog into the application: the configuration, the collections, their routes, the
/// views, the commands and the social cards.
///
/// ```ignore
/// Application::configure().with_providers(|providers| {
///     providers.add(LarablogServiceProvider::new().routes("blog"));
/// })
/// ```
///
/// PHP registers the routes of a collection in `routes/web.php` with `Larablog::routes('blog')`. A
/// provider is where a Laravel Rust package puts routes, so each collection that has pages is named
/// here instead.
#[derive(Clone, Default)]
pub struct LarablogServiceProvider {
    collections: Vec<(String, Option<MiddlewareGroup>)>,
}

impl LarablogServiceProvider {
    /// A provider that registers no routes yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register the pages of a collection in every language it is written in: the listing, a post,
    /// a category, a tag and the feed, named `{locale}.{collection}.{index|show|category|tag|feed}`.
    ///
    /// Several collections (a blog, guides, case studies) each get their own call.
    #[must_use]
    pub fn routes(mut self, collection: impl Into<String>) -> Self {
        self.collections.push((collection.into(), None));

        self
    }

    /// [`routes`](Self::routes) with middleware added to the pages, after the `web` group and
    /// [`UseLocale`](crate::UseLocale): PHP's `Larablog::routes('blog', ['throttle:60,1'])`.
    #[must_use]
    pub fn routes_with(mut self, collection: impl Into<String>, middleware: MiddlewareGroup) -> Self {
        self.collections.push((collection.into(), Some(middleware)));

        self
    }
}

impl ServiceProvider for LarablogServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
        config.set(Runtime(Larablog::new()));
    }

    fn register(&self, app: &mut Registrar) {
        if let Some(runtime) = app.config().get::<Runtime>() {
            let manager = runtime.0.clone();

            app.instance(manager);
        }
        app.views().namespace("larablog", laravel::embed!("resources/views"));

        let settings = app.config().section::<LarablogConfig>().clone();
        let app_locale = app
            .config()
            .get::<laralocale::LocaleConfig>()
            .map_or_else(|| "en".to_owned(), |config| config.locale.clone());
        let supported = app
            .config()
            .get::<laralocale::LocaleConfig>()
            .map(|config| config.supported.clone())
            .unwrap_or_default();
        let collections = self.collections.clone();

        app.routing().web(move |route| {
            for (name, middleware) in &collections {
                let Some(collection) = settings.collections.get(name) else {
                    tracing::warn!(collection = %name, "Larablog routes were asked for a collection the configuration does not have");

                    continue;
                };

                let locales = crate::support::resolve_locales(collection.locales.as_deref(), &supported, &app_locale);

                http::register(route, name, collection, &locales, &app_locale, middleware.as_ref());
            }
        });

        app.discover(env!("CARGO_CRATE_NAME"));
    }

    async fn boot(&self, _app: &Container) -> laravel::Result<()> {
        #[cfg(feature = "cards")]
        if let Err(error) = laracards::source("larablog", crate::cards::PostCards).await {
            tracing::warn!(%error, "Larablog's social cards were not registered: is the LaracardsServiceProvider added?");
        }

        Ok(())
    }
}