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};
#[derive(Clone, Default)]
pub struct LarablogServiceProvider {
collections: Vec<(String, Option<MiddlewareGroup>)>,
}
impl LarablogServiceProvider {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn routes(mut self, collection: impl Into<String>) -> Self {
self.collections.push((collection.into(), None));
self
}
#[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(())
}
}