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;
#[derive(Clone)]
pub struct SlugMethod(Arc<MethodFn>);
impl SlugMethod {
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")
}
}
#[derive(Clone)]
pub struct UniqueSuffix(Arc<SuffixFn>);
impl UniqueSuffix {
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")
}
}
#[derive(Debug, Clone, Section)]
pub struct SluggableConfig {
pub max_length: Option<usize>,
#[section(default = true)]
pub max_length_keep_words: bool,
pub method: Option<SlugMethod>,
#[section(default = "-".to_owned())]
pub separator: String,
#[section(default = true)]
pub unique: bool,
pub unique_suffix: Option<UniqueSuffix>,
#[section(default = "2".to_owned())]
pub first_unique_suffix: String,
pub reserved: Option<Vec<String>>,
#[section(default = false)]
pub on_update: bool,
#[section(default = SlugifyOptions::default())]
pub slug_engine_options: SlugifyOptions,
}
#[derive(Debug, Clone)]
pub struct SlugOptions {
pub max_length: Option<usize>,
pub max_length_keep_words: bool,
pub method: Option<SlugMethod>,
pub separator: String,
pub unique: bool,
pub unique_suffix: Option<UniqueSuffix>,
pub first_unique_suffix: String,
pub reserved: Option<Vec<String>>,
pub on_update: bool,
pub slug_engine_options: SlugifyOptions,
}
pub(crate) fn current() -> SluggableConfig {
if laravel::context::Context::current().is_none() {
return SluggableConfig::default();
}
laravel::config().get::<SluggableConfig>().cloned().unwrap_or_default()
}