laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
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;

/// Wires Laracards into the application: configuration, the generator, the renderer and the commands.
///
/// ```ignore
/// Application::configure().with_providers(|providers| {
///     providers.add(LaracardsServiceProvider::new().source("post", BlogPostCards));
/// })
/// ```
#[derive(Clone, Default)]
pub struct LaracardsServiceProvider {
    sources: Vec<(String, Arc<dyn CardSource>)>,
}

impl LaracardsServiceProvider {
    /// A provider with no card sources yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a card source for `cards:generate`, the `sources` key of the PHP config. A source with the
    /// same name replaces the earlier one.
    #[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"));
    }
}