use std::sync::Arc;
use laravel::db::{self, Builder, Condition};
use laravel::model::{__query, Changes, Column, Draft, Model};
use crate::config::{self, SlugMethod, SlugOptions, UniqueSuffix};
use crate::error::InvalidSlugAttribute;
use crate::slugify::{Slugify, SlugifyOptions};
pub enum SlugSubject<'a, M> {
Creating(&'a Draft<M>),
Model(&'a M),
None,
}
impl<M: Model> SlugSubject<'_, M> {
#[must_use]
pub fn get<T: 'static>(&self, column: Column<M, T>) -> Option<&T> {
match self {
Self::Creating(draft) => draft.get(column),
Self::Model(model) => Some(column.get(model)),
Self::None => None,
}
}
#[must_use]
pub fn key(&self) -> Option<&M::Key> {
self.get(M::META.key)
}
#[must_use]
pub fn exists(&self) -> bool {
matches!(self, Self::Model(_))
}
}
pub trait SourceValue {
fn source_text(&self) -> String;
}
macro_rules! display_source {
($($type:ty),+) => {$(
impl SourceValue for $type {
fn source_text(&self) -> String {
self.to_string()
}
}
)+};
}
display_source!(String, i8, i16, i32, i64, u8, u16, u32, u64, f32, f64);
impl SourceValue for bool {
fn source_text(&self) -> String {
if *self { "1" } else { "0" }.to_owned()
}
}
impl<T: SourceValue> SourceValue for Option<T> {
fn source_text(&self) -> String {
self.as_ref().map(SourceValue::source_text).unwrap_or_default()
}
}
pub trait SlugSource<M>: Send + Sync + 'static {
fn text(&self, subject: &SlugSubject<'_, M>) -> String;
}
impl<M: Model, T: SourceValue + 'static> SlugSource<M> for Column<M, T> {
fn text(&self, subject: &SlugSubject<'_, M>) -> String {
subject.get(*self).map(SourceValue::source_text).unwrap_or_default()
}
}
struct FnSource<F>(F);
impl<M, F> SlugSource<M> for FnSource<F>
where
F: Fn(&SlugSubject<'_, M>) -> String + Send + Sync + 'static,
{
fn text(&self, subject: &SlugSubject<'_, M>) -> String {
(self.0)(subject)
}
}
pub trait SlugColumn<M>: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn current(&self, subject: &SlugSubject<'_, M>) -> Option<String>;
#[doc(hidden)]
fn set_draft(&self, draft: &mut Draft<M>, slug: String);
#[doc(hidden)]
fn set_model(&self, model: &mut M, slug: String);
#[doc(hidden)]
fn changed(&self, changes: &Changes<M>) -> bool;
fn equals(&self, value: &str) -> Condition;
fn like(&self, pattern: &str) -> Condition;
}
impl<M: Model> SlugColumn<M> for Column<M, String> {
fn name(&self) -> &'static str {
Column::name(self)
}
fn current(&self, subject: &SlugSubject<'_, M>) -> Option<String> {
subject.get(*self).cloned()
}
fn set_draft(&self, draft: &mut Draft<M>, slug: String) {
draft.set(*self, slug);
}
fn set_model(&self, model: &mut M, slug: String) {
*self.__get_mut(model) = slug;
}
fn changed(&self, changes: &Changes<M>) -> bool {
changes.has(*self)
}
fn equals(&self, value: &str) -> Condition {
self.eq(value.to_owned())
}
fn like(&self, pattern: &str) -> Condition {
Column::like(*self, pattern)
}
}
impl<M: Model> SlugColumn<M> for Column<M, Option<String>> {
fn name(&self) -> &'static str {
Column::name(self)
}
fn current(&self, subject: &SlugSubject<'_, M>) -> Option<String> {
subject.get(*self).cloned().flatten()
}
fn set_draft(&self, draft: &mut Draft<M>, slug: String) {
draft.set(*self, Some(slug));
}
fn set_model(&self, model: &mut M, slug: String) {
*self.__get_mut(model) = Some(slug);
}
fn changed(&self, changes: &Changes<M>) -> bool {
changes.has(*self)
}
fn equals(&self, value: &str) -> Condition {
self.eq(Some(value.to_owned()))
}
fn like(&self, pattern: &str) -> Condition {
Column::like(*self, pattern)
}
}
type ReservedFn<M> = dyn Fn(&SlugSubject<'_, M>) -> Option<Vec<String>> + Send + Sync;
enum Reserved<M> {
List(Vec<String>),
With(Arc<ReservedFn<M>>),
}
pub struct Slug<M> {
column: Box<dyn SlugColumn<M>>,
sources: Vec<Box<dyn SlugSource<M>>>,
max_length: Option<Option<usize>>,
max_length_keep_words: Option<bool>,
method: Option<Option<SlugMethod>>,
separator: Option<String>,
unique: Option<bool>,
unique_suffix: Option<Option<UniqueSuffix>>,
first_unique_suffix: Option<String>,
reserved: Option<Option<Reserved<M>>>,
on_update: Option<bool>,
slug_engine_options: Option<SlugifyOptions>,
}
impl<M: Model> Slug<M> {
#[must_use]
pub fn new(column: impl SlugColumn<M>) -> Self {
Self {
column: Box::new(column),
sources: Vec::new(),
max_length: None,
max_length_keep_words: None,
method: None,
separator: None,
unique: None,
unique_suffix: None,
first_unique_suffix: None,
reserved: None,
on_update: None,
slug_engine_options: None,
}
}
#[must_use]
pub fn source(mut self, source: impl SlugSource<M>) -> Self {
self.sources.push(Box::new(source));
self
}
#[must_use]
pub fn source_with(mut self, source: impl Fn(&SlugSubject<'_, M>) -> String + Send + Sync + 'static) -> Self {
self.sources.push(Box::new(FnSource(source)));
self
}
#[must_use]
pub fn max_length(mut self, max_length: impl Into<Option<usize>>) -> Self {
self.max_length = Some(max_length.into());
self
}
#[must_use]
pub fn max_length_keep_words(mut self, keep: bool) -> Self {
self.max_length_keep_words = Some(keep);
self
}
#[must_use]
pub fn method(mut self, method: impl Fn(&str, &str) -> String + Send + Sync + 'static) -> Self {
self.method = Some(Some(SlugMethod::new(method)));
self
}
#[must_use]
pub fn separator(mut self, separator: impl Into<String>) -> Self {
self.separator = Some(separator.into());
self
}
#[must_use]
pub fn unique(mut self, unique: bool) -> Self {
self.unique = Some(unique);
self
}
#[must_use]
pub fn unique_suffix(
mut self,
suffix: impl Fn(&str, &str, &[String], &str) -> String + Send + Sync + 'static,
) -> Self {
self.unique_suffix = Some(Some(UniqueSuffix::new(suffix)));
self
}
#[must_use]
pub fn first_unique_suffix(mut self, first: impl ToString) -> Self {
self.first_unique_suffix = Some(first.to_string());
self
}
#[must_use]
pub fn reserved<S: Into<String>>(mut self, reserved: impl IntoIterator<Item = S>) -> Self {
self.reserved = Some(Some(Reserved::List(reserved.into_iter().map(Into::into).collect())));
self
}
#[must_use]
pub fn reserved_with(
mut self,
reserved: impl Fn(&SlugSubject<'_, M>) -> Option<Vec<String>> + Send + Sync + 'static,
) -> Self {
self.reserved = Some(Some(Reserved::With(Arc::new(reserved))));
self
}
#[must_use]
pub fn on_update(mut self, on_update: bool) -> Self {
self.on_update = Some(on_update);
self
}
#[must_use]
pub fn slug_engine_options(mut self, options: SlugifyOptions) -> Self {
self.slug_engine_options = Some(options);
self
}
#[must_use]
pub fn attribute(&self) -> &'static str {
self.column.name()
}
#[must_use]
pub fn merge(mut self, other: Self) -> Self {
if !other.sources.is_empty() {
self.sources = other.sources;
}
macro_rules! take {
($($field:ident),+) => {$( if other.$field.is_some() { self.$field = other.$field; } )+};
}
take!(
max_length,
max_length_keep_words,
method,
separator,
unique,
unique_suffix,
first_unique_suffix,
reserved,
on_update,
slug_engine_options
);
self
}
fn options(&self, subject: &SlugSubject<'_, M>) -> SlugOptions {
let defaults = config::current();
SlugOptions {
max_length: self.max_length.unwrap_or(defaults.max_length),
max_length_keep_words: self.max_length_keep_words.unwrap_or(defaults.max_length_keep_words),
method: self.method.clone().unwrap_or(defaults.method),
separator: self.separator.clone().unwrap_or(defaults.separator),
unique: self.unique.unwrap_or(defaults.unique),
unique_suffix: self.unique_suffix.clone().unwrap_or(defaults.unique_suffix),
first_unique_suffix: self.first_unique_suffix.clone().unwrap_or(defaults.first_unique_suffix),
reserved: match &self.reserved {
None => defaults.reserved,
Some(None) => None,
Some(Some(Reserved::List(list))) => Some(list.clone()),
Some(Some(Reserved::With(reserved))) => reserved(subject),
},
on_update: self.on_update.unwrap_or(defaults.on_update),
slug_engine_options: self.slug_engine_options.clone().unwrap_or(defaults.slug_engine_options),
}
}
fn source_text(&self, subject: &SlugSubject<'_, M>) -> String {
self.sources
.iter()
.map(|source| source.text(subject))
.collect::<Vec<_>>()
.join(" ")
}
}
pub trait Sluggable: Model {
fn sluggable() -> Vec<Slug<Self>>;
fn customize_slug_engine(engine: Slugify, _attribute: &str) -> Slugify {
engine
}
fn find_similar_slugs(
query: Builder<Self>,
column: &dyn SlugColumn<Self>,
config: &SlugOptions,
slug: &str,
) -> Builder<Self> {
let pattern = format!("{slug}{}%", config.separator);
query.filter(db::any([column.equals(slug), column.like(&pattern)]))
}
fn with_unique_slug_constraints(
query: Builder<Self>,
_model: &SlugSubject<'_, Self>,
_attribute: &str,
_config: &SlugOptions,
_slug: &str,
) -> Builder<Self> {
query
}
}
pub async fn creating<M: Sluggable>(draft: &mut Draft<M>) -> laravel::Result<()> {
for slug in M::sluggable() {
let built = {
let subject = SlugSubject::Creating(&*draft);
let config = slug.options(&subject);
let current = slug.column.current(&subject);
if needs_slugging(current.as_deref(), &config, false) {
build(&slug, &subject, &config).await?
} else {
None
}
};
if let Some(value) = built {
slug.column.set_draft(draft, value);
}
}
Ok(())
}
pub async fn updating<M: Sluggable>(model: &mut M, _changes: &Changes<M>) -> laravel::Result<()> {
for slug in M::sluggable() {
let built = {
let subject = SlugSubject::Model(&*model);
let config = slug.options(&subject);
let current = slug.column.current(&subject);
if needs_slugging(current.as_deref(), &config, false) {
build(&slug, &subject, &config).await?
} else {
None
}
};
if let Some(value) = built {
slug.column.set_model(model, value);
}
}
Ok(())
}
#[macro_export]
macro_rules! sluggable_hooks {
($model:ty) => {
impl ::laravel::model::Hooks for $model {
async fn creating(draft: &mut ::laravel::model::Draft<Self>) -> ::laravel::Result<()> {
$crate::creating(draft).await
}
async fn updating(&mut self, changes: &::laravel::model::Changes<Self>) -> ::laravel::Result<()> {
$crate::updating(self, changes).await
}
}
};
}
pub struct SlugService;
impl SlugService {
pub async fn slug<M: Sluggable>(model: &mut M, force: bool) -> laravel::Result<bool> {
let mut changed = false;
for slug in M::sluggable() {
let built = {
let subject = SlugSubject::Model(&*model);
let config = slug.options(&subject);
let current = slug.column.current(&subject);
if force || needs_slugging(current.as_deref(), &config, false) {
build(&slug, &subject, &config)
.await?
.filter(|value| Some(value) != current.as_ref())
} else {
None
}
};
if let Some(value) = built {
slug.column.set_model(model, value);
changed = true;
}
}
Ok(changed)
}
pub async fn create_slug<M: Sluggable>(
model: Option<&M>,
attribute: &str,
from_string: &str,
config: Option<Slug<M>>,
) -> laravel::Result<String> {
let subject = model.map_or(SlugSubject::None, SlugSubject::Model);
let own = M::sluggable().into_iter().find(|slug| slug.attribute() == attribute);
let slug = match (own, config) {
(Some(own), Some(config)) => own.merge(config),
(Some(own), None) => own,
(None, Some(config)) => config,
(None, None) => {
return Err(InvalidSlugAttribute {
attribute: attribute.to_owned(),
model: M::META.name,
}
.into());
}
};
let options = slug.options(&subject);
let generated = generate_slug(from_string, &options, attribute, M::customize_slug_engine);
let validated = validate_slug(generated, &options);
make_slug_unique(validated, &slug, &subject, &options).await
}
}
fn needs_slugging(current: Option<&str>, config: &SlugOptions, force: bool) -> bool {
force || config.on_update || is_blank(current)
}
fn is_blank(value: Option<&str>) -> bool {
value.is_none_or(|value| value.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']).is_empty())
}
async fn build<M: Sluggable>(
slug: &Slug<M>,
subject: &SlugSubject<'_, M>,
config: &SlugOptions,
) -> laravel::Result<Option<String>> {
let source = slug.source_text(subject);
if source.is_empty() {
return Ok(None);
}
let generated = generate_slug(&source, config, slug.attribute(), M::customize_slug_engine);
let validated = validate_slug(generated, config);
Ok(Some(make_slug_unique(validated, slug, subject, config).await?))
}
fn generate_slug(
source: &str,
config: &SlugOptions,
attribute: &str,
customize: fn(Slugify, &str) -> Slugify,
) -> String {
let separator = config.separator.as_str();
let slug = match &config.method {
None => {
customize(Slugify::new(config.slug_engine_options.clone()), attribute).slugify_separator(source, separator)
}
Some(method) => method.call(source, separator),
};
let length = slug.chars().count();
match config.max_length {
Some(max) if max > 0 && length > max => {
let last_separator = (!separator.is_empty())
.then(|| last_separator_at_or_before(&slug, separator, max))
.flatten();
match last_separator {
Some(position) if config.max_length_keep_words => slug.chars().take(position).collect(),
_ => {
let cut: String = slug.chars().take(max).collect();
cut.trim_matches(|character| separator.contains(character)).to_owned()
}
}
}
_ => slug,
}
}
fn last_separator_at_or_before(slug: &str, separator: &str, max: usize) -> Option<usize> {
let chars: Vec<char> = slug.chars().collect();
let needle: Vec<char> = separator.chars().collect();
let last_start = max.min(chars.len().checked_sub(needle.len())?);
(0..=last_start)
.rev()
.find(|&start| chars[start..start + needle.len()] == needle[..])
}
fn validate_slug(slug: String, config: &SlugOptions) -> String {
let Some(reserved) = &config.reserved else {
return slug;
};
if !reserved.contains(&slug) {
return slug;
}
let suffix = match &config.unique_suffix {
None => generate_suffix(&slug, &config.separator, reserved, false, &config.first_unique_suffix),
Some(suffix) => suffix.call(&slug, &config.separator, reserved, &config.first_unique_suffix),
};
format!("{slug}{}{suffix}", config.separator)
}
async fn make_slug_unique<M: Sluggable>(
slug: String,
definition: &Slug<M>,
subject: &SlugSubject<'_, M>,
config: &SlugOptions,
) -> laravel::Result<String> {
if !config.unique {
return Ok(slug);
}
let list = existing_slugs(&slug, definition, subject, config).await?;
if list.is_empty() || !list.iter().any(|(_, existing)| *existing == slug) {
return Ok(slug);
}
let own = subject
.key()
.and_then(|key| list.iter().find(|(existing, _)| existing == key));
if let Some((_, current)) = own
&& (*current == slug || slug.is_empty() || slug == "0" || current.starts_with(&slug))
{
return Ok(current.clone());
}
let first_with_slug = list.iter().find(|(_, existing)| *existing == slug).map(|(key, _)| key);
let is_own = subject.key().is_some() && first_with_slug == subject.key();
let slugs: Vec<String> = list.into_iter().map(|(_, existing)| existing).collect();
let suffix = match &config.unique_suffix {
None => generate_suffix(&slug, &config.separator, &slugs, is_own, &config.first_unique_suffix),
Some(suffix) => suffix.call(&slug, &config.separator, &slugs, &config.first_unique_suffix),
};
Ok(format!("{slug}{}{suffix}", config.separator))
}
fn generate_suffix(slug: &str, separator: &str, list: &[String], is_own: bool, first: &str) -> String {
if is_own {
if separator.is_empty() {
return slug.to_owned();
}
return slug.rsplit(separator).next().unwrap_or(slug).to_owned();
}
let length = slug.len() + separator.len();
let max = list
.iter()
.map(|value| php_int(value.as_bytes().get(length..).unwrap_or_default()))
.max();
match max {
Some(0) => first.to_owned(),
Some(max) => (max + 1).to_string(),
None => "1".to_owned(),
}
}
fn php_int(bytes: &[u8]) -> i64 {
let text = String::from_utf8_lossy(bytes);
let text = text.trim_start_matches([' ', '\t', '\n', '\r', '\x0B', '\x0C']);
let (negative, digits) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
let digits: String = digits.chars().take_while(char::is_ascii_digit).collect();
let value = digits
.parse::<i64>()
.unwrap_or(if digits.is_empty() { 0 } else { i64::MAX });
if negative { -value } else { value }
}
async fn existing_slugs<M: Sluggable>(
slug: &str,
definition: &Slug<M>,
subject: &SlugSubject<'_, M>,
config: &SlugOptions,
) -> laravel::Result<Vec<(M::Key, String)>> {
let query = M::find_similar_slugs(__query::<M>(), definition.column.as_ref(), config, slug);
let query = M::with_unique_slug_constraints(query, subject, definition.attribute(), config, slug);
let rows = query.get().await?;
let mut list: Vec<(M::Key, String)> = Vec::with_capacity(rows.len());
for row in &rows {
let key = M::META.key.get(row).clone();
let value = definition.column.current(&SlugSubject::Model(row)).unwrap_or_default();
list.push((key, value));
}
Ok(list)
}
pub trait SluggableScopeHelpers: Sluggable {
fn slug_key_name() -> &'static str {
Self::primary_slug().attribute()
}
#[doc(hidden)]
fn primary_slug() -> Slug<Self> {
let mut slugs = Self::sluggable();
assert!(!slugs.is_empty(), "{} has no slugs", Self::META.name);
slugs.remove(0)
}
fn slug_key(&self) -> Option<String> {
let name = Self::slug_key_name();
Self::sluggable()
.into_iter()
.find(|slug| slug.attribute() == name)
.and_then(|slug| slug.column.current(&SlugSubject::Model(self)))
}
fn where_slug(slug: &str) -> Builder<Self> {
let name = Self::slug_key_name();
let definition = Self::sluggable()
.into_iter()
.find(|definition| definition.attribute() == name)
.unwrap_or_else(Self::primary_slug);
__query::<Self>().filter(definition.column.equals(slug))
}
fn find_by_slug(slug: &str) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
Self::where_slug(slug).first()
}
fn find_by_slug_or_fail(slug: &str) -> impl Future<Output = laravel::Result<Self>> + Send {
Self::where_slug(slug).first_or_fail()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn suffixes_and_ints_like_php() {
assert_eq!(php_int(b"12abc"), 12);
assert_eq!(php_int(b""), 0);
assert_eq!(php_int(b" -3"), -3);
let list = ["foo".to_owned(), "foo-2".to_owned(), "foo-7".to_owned()];
assert_eq!(generate_suffix("foo", "-", &list, false, "2"), "8");
assert_eq!(generate_suffix("foo", "-", &list[..1], false, "2"), "2");
assert_eq!(generate_suffix("foo-bar-3", "-", &list, true, "2"), "3");
}
#[test]
fn max_length_cuts_at_words() {
assert_eq!(last_separator_at_or_before("hello-world", "-", 5), Some(5));
assert_eq!(last_separator_at_or_before("hello-world", "-", 4), None);
}
}