use std::path::PathBuf;
use std::sync::Arc;
use laravel::config::{Config, Env};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
use crate::config::LaracardsConfig;
use crate::contracts::{CardSource, Renderer};
use crate::generator::CardGenerator;
use crate::renderers::ResvgRenderer;
use crate::sources::CardSources;
use crate::support::Manifest;
#[derive(Clone, Default)]
pub struct LaracardsServiceProvider {
sources: Vec<(String, Arc<dyn CardSource>)>,
}
impl LaracardsServiceProvider {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn source(mut self, name: impl Into<String>, source: impl CardSource + 'static) -> Self {
let name = name.into();
self.sources.retain(|(existing, _)| *existing != name);
self.sources.push((name, Arc::new(source)));
self
}
}
impl ServiceProvider for LaracardsServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
fn register(&self, app: &mut Registrar) {
let sources = self.sources.clone();
app.singleton_as(async |app| {
let config = app.config().section::<LaracardsConfig>();
let base = &app.config().app.base_path;
let fonts: Vec<PathBuf> = config
.fonts
.values()
.chain(&config.renderers.resvg.font_files)
.map(|path| LaracardsConfig::resolve(base, path))
.collect();
Ok(Arc::new(ResvgRenderer::new(&fonts, config.renderers.resvg.system_fonts)) as Arc<dyn Renderer>)
});
app.singleton(async |app| {
let config = app.config().section::<LaracardsConfig>();
let manifest = LaracardsConfig::resolve(&app.config().app.base_path, &config.paths.manifest);
Ok(CardGenerator::new(
app.resolve::<dyn Renderer>().await?,
Manifest::new(manifest),
))
});
app.instance(CardSources::new(sources));
app.discover(env!("CARGO_CRATE_NAME"));
}
}