laravel-sluggable 0.2.0

Easy creation of slugs for your Laravel Rust models: a port of cviebrock/eloquent-sluggable.
Documentation
//! The package's settings: `config/sluggable.php`, and the per-slug settings that a model's
//! `sluggable()` returns.

use std::fmt;
use std::sync::Arc;

use laravel::config::Section;

use crate::slugify::SlugifyOptions;

type MethodFn = dyn Fn(&str, &str) -> String + Send + Sync;
type SuffixFn = dyn Fn(&str, &str, &[String], &str) -> String + Send + Sync;

/// A custom slug method, the `method` setting: called with the source text and the separator,
/// it returns the slug instead of the slug engine.
#[derive(Clone)]
pub struct SlugMethod(Arc<MethodFn>);

impl SlugMethod {
    /// Wraps a closure `|source, separator| slug`.
    pub fn new(method: impl Fn(&str, &str) -> String + Send + Sync + 'static) -> Self {
        Self(Arc::new(method))
    }

    pub(crate) fn call(&self, source: &str, separator: &str) -> String {
        (self.0)(source, separator)
    }
}

impl fmt::Debug for SlugMethod {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("SlugMethod")
    }
}

/// A custom suffix generator, the `uniqueSuffix` setting: called with the slug, the separator,
/// the similar slugs and the `firstUniqueSuffix`, it returns the suffix to append.
#[derive(Clone)]
pub struct UniqueSuffix(Arc<SuffixFn>);

impl UniqueSuffix {
    /// Wraps a closure `|slug, separator, similar_slugs, first_suffix| suffix`.
    pub fn new(suffix: impl Fn(&str, &str, &[String], &str) -> String + Send + Sync + 'static) -> Self {
        Self(Arc::new(suffix))
    }

    pub(crate) fn call(&self, slug: &str, separator: &str, list: &[String], first: &str) -> String {
        (self.0)(slug, separator, list, first)
    }
}

impl fmt::Debug for UniqueSuffix {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("UniqueSuffix")
    }
}

/// The package's settings: `config/sluggable.php`. A model's [`Slug`](crate::Slug) overrides any
/// of them for one slug column, as the PHP package merges a model's settings over the file.
///
/// ```ignore
/// Application::configure()
///     .with_config(|config, _| {
///         config.section_mut::<SluggableConfig>().separator = "_".to_owned();
///     })
/// ```
#[derive(Debug, Clone, Section)]
pub struct SluggableConfig {
    /// The longest slug, in characters: `maxLength`. `None` for no limit.
    pub max_length: Option<usize>,

    /// Cut a long slug at a word boundary instead of mid-word: `maxLengthKeepWords`.
    #[section(default = true)]
    pub max_length_keep_words: bool,

    /// A custom slug method: `method`. `None` uses the slug engine.
    pub method: Option<SlugMethod>,

    /// The separator between words: `separator`.
    #[section(default = "-".to_owned())]
    pub separator: String,

    /// Make slugs unique by adding a suffix: `unique`.
    #[section(default = true)]
    pub unique: bool,

    /// A custom suffix generator: `uniqueSuffix`. `None` adds `-2`, `-3` and so on.
    pub unique_suffix: Option<UniqueSuffix>,

    /// The suffix of the first duplicate: `firstUniqueSuffix`.
    #[section(default = "2".to_owned())]
    pub first_unique_suffix: String,

    /// Slugs that may not be used; such a slug gets a suffix: `reserved`.
    pub reserved: Option<Vec<String>>,

    /// Regenerate the slug every time the model is updated: `onUpdate`.
    #[section(default = false)]
    pub on_update: bool,

    /// The slug engine's options: `slugEngineOptions`.
    #[section(default = SlugifyOptions::default())]
    pub slug_engine_options: SlugifyOptions,
}

/// The settings of one slug, the PHP package's merged config array: the model's settings over
/// [`SluggableConfig`]. [`Sluggable::with_unique_slug_constraints`](crate::Sluggable::with_unique_slug_constraints)
/// receives it.
#[derive(Debug, Clone)]
pub struct SlugOptions {
    /// `maxLength`.
    pub max_length: Option<usize>,
    /// `maxLengthKeepWords`.
    pub max_length_keep_words: bool,
    /// `method`.
    pub method: Option<SlugMethod>,
    /// `separator`.
    pub separator: String,
    /// `unique`.
    pub unique: bool,
    /// `uniqueSuffix`.
    pub unique_suffix: Option<UniqueSuffix>,
    /// `firstUniqueSuffix`.
    pub first_unique_suffix: String,
    /// `reserved`, after calling a reserved closure.
    pub reserved: Option<Vec<String>>,
    /// `onUpdate`.
    pub on_update: bool,
    /// `slugEngineOptions`.
    pub slug_engine_options: SlugifyOptions,
}

/// The application's settings, or the defaults when the provider isn't registered or no
/// application is running.
pub(crate) fn current() -> SluggableConfig {
    if laravel::context::Context::current().is_none() {
        return SluggableConfig::default();
    }

    laravel::config().get::<SluggableConfig>().cloned().unwrap_or_default()
}