laravel-sluggable 0.2.0

Easy creation of slugs for your Laravel Rust models: a port of cviebrock/eloquent-sluggable.
Documentation
//! The slug engine: a port of [cocur/slugify](https://github.com/cocur/slugify) 4.8.0, which the
//! PHP package uses. The transliteration rules are cocur/slugify's own files, so slugs match the
//! PHP package's character for character.

use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

use regex::Regex;

use crate::rules::RULESETS;

/// The options of cocur/slugify's `Slugify` constructor: the `slugEngineOptions` setting.
///
/// ```ignore
/// use laravel_sluggable::SlugifyOptions;
///
/// SlugifyOptions { lowercase: false, ..SlugifyOptions::default() }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlugifyOptions {
    /// The characters to replace with the separator, as a PHP regular expression with its
    /// delimiters: `regexp`. `/[^A-Za-z0-9]+/` by default.
    pub regexp: String,
    /// The separator: `separator`. The model's `separator` setting overrides it, as in PHP.
    pub separator: String,
    /// Lowercase the slug: `lowercase`. `true` by default.
    pub lowercase: bool,
    /// Lowercase after replacing with `regexp` rather than before: `lowercase_after_regexp`.
    pub lowercase_after_regexp: bool,
    /// Trim separators from both ends: `trim`. `true` by default.
    pub trim: bool,
    /// Remove HTML tags first: `strip_tags`.
    pub strip_tags: bool,
    /// The rulesets to activate, later ones winning: `rulesets`. cocur/slugify's default list.
    pub rulesets: Vec<String>,
    /// One more ruleset for this call only: `ruleset`.
    pub ruleset: Option<String>,
}

impl Default for SlugifyOptions {
    fn default() -> Self {
        Self {
            regexp: "/[^A-Za-z0-9]+/".to_owned(),
            separator: "-".to_owned(),
            lowercase: true,
            lowercase_after_regexp: false,
            trim: true,
            strip_tags: false,
            rulesets: [
                "default",
                "yiddish",
                "armenian",
                "azerbaijani",
                "burmese",
                "hindi",
                "georgian",
                "norwegian",
                "vietnamese",
                "ukrainian",
                "latvian",
                "finnish",
                "greek",
                "czech",
                "arabic",
                "slovak",
                "turkish",
                "polish",
                "german",
                "russian",
                "romanian",
            ]
            .map(str::to_owned)
            .to_vec(),
            ruleset: None,
        }
    }
}

/// The slug engine: cocur/slugify's `Slugify` class.
///
/// A model changes it with [`Sluggable::customize_slug_engine`](crate::Sluggable::customize_slug_engine),
/// for example to add rules:
///
/// ```ignore
/// fn customize_slug_engine(engine: Slugify, _attribute: &str) -> Slugify {
///     engine.add_rule("&", "and")
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Slugify {
    options: SlugifyOptions,
    rules: HashMap<String, String>,
}

impl Default for Slugify {
    fn default() -> Self {
        Self::new(SlugifyOptions::default())
    }
}

impl Slugify {
    /// Creates the engine with `options`, activating its rulesets: `new Slugify($options)`.
    #[must_use]
    pub fn new(options: SlugifyOptions) -> Self {
        let mut engine = Self {
            rules: HashMap::new(),
            options,
        };
        for ruleset in engine.options.rulesets.clone() {
            engine = engine.activate_rule_set(&ruleset);
        }
        engine
    }

    /// The engine's options.
    #[must_use]
    pub fn options(&self) -> &SlugifyOptions {
        &self.options
    }

    /// Adds a rule replacing `character` with `replacement`: `addRule`.
    #[must_use]
    pub fn add_rule(mut self, character: impl Into<String>, replacement: impl Into<String>) -> Self {
        self.rules.insert(character.into(), replacement.into());
        self
    }

    /// Adds rules: `addRules`.
    #[must_use]
    pub fn add_rules<K: Into<String>, V: Into<String>>(mut self, rules: impl IntoIterator<Item = (K, V)>) -> Self {
        for (character, replacement) in rules {
            self = self.add_rule(character, replacement);
        }
        self
    }

    /// Activates one of cocur/slugify's rulesets, such as `german`: `activateRuleSet`. An unknown
    /// ruleset adds nothing; cocur/slugify throws there.
    #[must_use]
    pub fn activate_rule_set(self, ruleset: &str) -> Self {
        let rules = ruleset_rules(ruleset);
        self.add_rules(rules.iter().map(|(key, value)| (key.clone(), value.clone())))
    }

    /// Slugifies `text` with the engine's options: `slugify($string)`.
    #[must_use]
    pub fn slugify(&self, text: &str) -> String {
        self.slugify_with(text, &self.options)
    }

    /// Slugifies `text` with `separator` instead of the engine's: `slugify($string, $separator)`,
    /// as the PHP package calls it.
    #[must_use]
    pub fn slugify_separator(&self, text: &str, separator: &str) -> String {
        let options = SlugifyOptions {
            separator: separator.to_owned(),
            ..self.options.clone()
        };
        self.slugify_with(text, &options)
    }

    fn slugify_with(&self, text: &str, options: &SlugifyOptions) -> String {
        let mut extra;
        let rules = match &options.ruleset {
            Some(ruleset) => {
                extra = self.rules.clone();
                extra.extend(
                    ruleset_rules(ruleset)
                        .iter()
                        .map(|(key, value)| (key.clone(), value.clone())),
                );
                &extra
            }
            None => &self.rules,
        };

        let mut string = if options.strip_tags {
            strip_tags(text)
        } else {
            text.to_owned()
        };
        string = strtr(&string, rules);

        if options.lowercase && !options.lowercase_after_regexp {
            string = string.to_lowercase();
        }

        string = php_regex(&options.regexp)
            .replace_all(&string, regex::NoExpand(&options.separator))
            .into_owned();

        if options.lowercase && options.lowercase_after_regexp {
            string = string.to_lowercase();
        }

        if options.trim && !options.separator.is_empty() {
            while let Some(rest) = string.strip_prefix(options.separator.as_str()) {
                string = rest.to_owned();
            }
            while let Some(rest) = string.strip_suffix(options.separator.as_str()) {
                string = rest.to_owned();
            }
        }

        string
    }
}

/// A ruleset's rules, parsed once.
fn ruleset_rules(name: &str) -> Arc<HashMap<String, String>> {
    static PARSED: OnceLock<HashMap<&'static str, Arc<HashMap<String, String>>>> = OnceLock::new();
    PARSED
        .get_or_init(|| {
            RULESETS
                .iter()
                .map(|(name, json)| {
                    (
                        *name,
                        Arc::new(serde_json::from_str(json).expect("a cocur/slugify ruleset")),
                    )
                })
                .collect()
        })
        .get(name)
        .cloned()
        .unwrap_or_default()
}

/// PHP's `strtr($string, $rules)`: at each position, the longest matching key wins, and replaced
/// text isn't searched again.
fn strtr(text: &str, rules: &HashMap<String, String>) -> String {
    let longest = rules.keys().map(|key| key.chars().count()).max().unwrap_or(0);
    if longest == 0 {
        return text.to_owned();
    }

    let chars: Vec<(usize, char)> = text.char_indices().collect();
    let mut out = String::with_capacity(text.len());
    let mut index = 0;
    'outer: while index < chars.len() {
        let start = chars[index].0;
        for length in (1..=longest.min(chars.len() - index)).rev() {
            let end = chars.get(index + length).map_or(text.len(), |(offset, _)| *offset);
            if let Some(replacement) = rules.get(&text[start..end]) {
                out.push_str(replacement);
                index += length;
                continue 'outer;
            }
        }
        out.push(chars[index].1);
        index += 1;
    }
    out
}

/// A PHP regular expression such as `/[^A-Za-z0-9]+/i`, with its delimiters and the `i`, `m`, `s`,
/// `x` and `u` flags.
fn php_regex(pattern: &str) -> Regex {
    let mut chars = pattern.chars();
    let compiled = chars.next().and_then(|delimiter| {
        let closing = match delimiter {
            '(' => ')',
            '{' => '}',
            '[' => ']',
            '<' => '>',
            other => other,
        };
        let body = &pattern[delimiter.len_utf8()..];
        let end = body.rfind(closing)?;
        let flags: String = body[end + closing.len_utf8()..]
            .chars()
            .filter(|flag| matches!(flag, 'i' | 'm' | 's' | 'x'))
            .collect();
        let expression = if flags.is_empty() {
            body[..end].to_owned()
        } else {
            format!("(?{flags}){}", &body[..end])
        };
        Regex::new(&expression).ok()
    });
    compiled.unwrap_or_else(|| Regex::new("[^A-Za-z0-9]+").expect("the default pattern"))
}

/// PHP's `strip_tags`, for the common case: removes `<...>` tags.
fn strip_tags(text: &str) -> String {
    static TAGS: OnceLock<Regex> = OnceLock::new();
    TAGS.get_or_init(|| Regex::new(r"<[^>]*>").expect("the tag pattern"))
        .replace_all(text, "")
        .into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slugifies_like_cocur() {
        let engine = Slugify::default();
        assert_eq!(engine.slugify("Hello World"), "hello-world");
        assert_eq!(engine.slugify("Müller straße"), "mueller-strasse");
        assert_eq!(engine.slugify("Привет мир"), "privet-mir");
        assert_eq!(engine.slugify("  --Café au lait!-- "), "cafe-au-lait");
        assert_eq!(engine.slugify_separator("Hello World", "_"), "hello_world");
        assert_eq!(engine.slugify_separator("Hello World", ""), "helloworld");
    }

    #[test]
    fn custom_rules_and_options() {
        let engine = Slugify::default().add_rule("&", "and");
        assert_eq!(engine.slugify("Tom & Jerry"), "tom-and-jerry");

        let engine = Slugify::new(SlugifyOptions {
            lowercase: false,
            ..SlugifyOptions::default()
        });
        assert_eq!(engine.slugify("Hello World"), "Hello-World");

        let engine = Slugify::new(SlugifyOptions {
            regexp: "/[^a-z]+/i".to_owned(),
            ..SlugifyOptions::default()
        });
        assert_eq!(engine.slugify("Abc 123 Def"), "abc-def");
    }
}