Skip to main content

laravel_sluggable/
config.rs

1//! The package's settings: `config/sluggable.php`, and the per-slug settings that a model's
2//! `sluggable()` returns.
3
4use std::fmt;
5use std::sync::Arc;
6
7use laravel::config::Section;
8
9use crate::slugify::SlugifyOptions;
10
11type MethodFn = dyn Fn(&str, &str) -> String + Send + Sync;
12type SuffixFn = dyn Fn(&str, &str, &[String], &str) -> String + Send + Sync;
13
14/// A custom slug method, the `method` setting: called with the source text and the separator,
15/// it returns the slug instead of the slug engine.
16#[derive(Clone)]
17pub struct SlugMethod(Arc<MethodFn>);
18
19impl SlugMethod {
20    /// Wraps a closure `|source, separator| slug`.
21    pub fn new(method: impl Fn(&str, &str) -> String + Send + Sync + 'static) -> Self {
22        Self(Arc::new(method))
23    }
24
25    pub(crate) fn call(&self, source: &str, separator: &str) -> String {
26        (self.0)(source, separator)
27    }
28}
29
30impl fmt::Debug for SlugMethod {
31    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32        formatter.write_str("SlugMethod")
33    }
34}
35
36/// A custom suffix generator, the `uniqueSuffix` setting: called with the slug, the separator,
37/// the similar slugs and the `firstUniqueSuffix`, it returns the suffix to append.
38#[derive(Clone)]
39pub struct UniqueSuffix(Arc<SuffixFn>);
40
41impl UniqueSuffix {
42    /// Wraps a closure `|slug, separator, similar_slugs, first_suffix| suffix`.
43    pub fn new(suffix: impl Fn(&str, &str, &[String], &str) -> String + Send + Sync + 'static) -> Self {
44        Self(Arc::new(suffix))
45    }
46
47    pub(crate) fn call(&self, slug: &str, separator: &str, list: &[String], first: &str) -> String {
48        (self.0)(slug, separator, list, first)
49    }
50}
51
52impl fmt::Debug for UniqueSuffix {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        formatter.write_str("UniqueSuffix")
55    }
56}
57
58/// The package's settings: `config/sluggable.php`. A model's [`Slug`](crate::Slug) overrides any
59/// of them for one slug column, as the PHP package merges a model's settings over the file.
60///
61/// ```ignore
62/// Application::configure()
63///     .with_config(|config, _| {
64///         config.section_mut::<SluggableConfig>().separator = "_".to_owned();
65///     })
66/// ```
67#[derive(Debug, Clone, Section)]
68pub struct SluggableConfig {
69    /// The longest slug, in characters: `maxLength`. `None` for no limit.
70    pub max_length: Option<usize>,
71
72    /// Cut a long slug at a word boundary instead of mid-word: `maxLengthKeepWords`.
73    #[section(default = true)]
74    pub max_length_keep_words: bool,
75
76    /// A custom slug method: `method`. `None` uses the slug engine.
77    pub method: Option<SlugMethod>,
78
79    /// The separator between words: `separator`.
80    #[section(default = "-".to_owned())]
81    pub separator: String,
82
83    /// Make slugs unique by adding a suffix: `unique`.
84    #[section(default = true)]
85    pub unique: bool,
86
87    /// A custom suffix generator: `uniqueSuffix`. `None` adds `-2`, `-3` and so on.
88    pub unique_suffix: Option<UniqueSuffix>,
89
90    /// The suffix of the first duplicate: `firstUniqueSuffix`.
91    #[section(default = "2".to_owned())]
92    pub first_unique_suffix: String,
93
94    /// Slugs that may not be used; such a slug gets a suffix: `reserved`.
95    pub reserved: Option<Vec<String>>,
96
97    /// Regenerate the slug every time the model is updated: `onUpdate`.
98    #[section(default = false)]
99    pub on_update: bool,
100
101    /// The slug engine's options: `slugEngineOptions`.
102    #[section(default = SlugifyOptions::default())]
103    pub slug_engine_options: SlugifyOptions,
104}
105
106/// The settings of one slug, the PHP package's merged config array: the model's settings over
107/// [`SluggableConfig`]. [`Sluggable::with_unique_slug_constraints`](crate::Sluggable::with_unique_slug_constraints)
108/// receives it.
109#[derive(Debug, Clone)]
110pub struct SlugOptions {
111    /// `maxLength`.
112    pub max_length: Option<usize>,
113    /// `maxLengthKeepWords`.
114    pub max_length_keep_words: bool,
115    /// `method`.
116    pub method: Option<SlugMethod>,
117    /// `separator`.
118    pub separator: String,
119    /// `unique`.
120    pub unique: bool,
121    /// `uniqueSuffix`.
122    pub unique_suffix: Option<UniqueSuffix>,
123    /// `firstUniqueSuffix`.
124    pub first_unique_suffix: String,
125    /// `reserved`, after calling a reserved closure.
126    pub reserved: Option<Vec<String>>,
127    /// `onUpdate`.
128    pub on_update: bool,
129    /// `slugEngineOptions`.
130    pub slug_engine_options: SlugifyOptions,
131}
132
133/// The application's settings, or the defaults when the provider isn't registered or no
134/// application is running.
135pub(crate) fn current() -> SluggableConfig {
136    if laravel::context::Context::current().is_none() {
137        return SluggableConfig::default();
138    }
139
140    laravel::config().get::<SluggableConfig>().cloned().unwrap_or_default()
141}