laravel-sluggable 0.2.0

Easy creation of slugs for your Laravel Rust models: a port of cviebrock/eloquent-sluggable.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! `Sluggable`, `SlugService` and `SluggableScopeHelpers`: the PHP package's trait, service and
//! helper trait.

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};

/// What a slug is made from: the model being saved, or the columns a create is about to insert.
pub enum SlugSubject<'a, M> {
    /// A create, before the row exists: PHP's unsaved model.
    Creating(&'a Draft<M>),
    /// A saved model.
    Model(&'a M),
    /// No model: [`SlugService::create_slug`] called with only the model's type.
    None,
}

impl<M: Model> SlugSubject<'_, M> {
    /// The value of `column`, or `None` when a create doesn't set it.
    #[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,
        }
    }

    /// The model's key: PHP's `getKey()`, `None` before the row exists.
    #[must_use]
    pub fn key(&self) -> Option<&M::Key> {
        self.get(M::META.key)
    }

    /// Whether the row exists: PHP's `$model->exists`.
    #[must_use]
    pub fn exists(&self) -> bool {
        matches!(self, Self::Model(_))
    }
}

/// A value a slug can be made from. PHP joins the sources' values with spaces, writing `true` and
/// `false` as `1` and `0`, and `null` as nothing.
pub trait SourceValue {
    /// The value as source text.
    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()
    }
}

/// One source of a slug: a column, or a closure given with [`Slug::source_with`].
pub trait SlugSource<M>: Send + Sync + 'static {
    /// The source's text.
    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)
    }
}

/// A column that holds a slug: a `String` or `Option<String>` column.
pub trait SlugColumn<M>: Send + Sync + 'static {
    /// The column's name.
    fn name(&self) -> &'static str;
    /// The current slug.
    fn current(&self, subject: &SlugSubject<'_, M>) -> Option<String>;
    /// Sets the slug on a create.
    #[doc(hidden)]
    fn set_draft(&self, draft: &mut Draft<M>, slug: String);
    /// Sets the slug on a model.
    #[doc(hidden)]
    fn set_model(&self, model: &mut M, slug: String);
    /// Whether the update changes the column.
    #[doc(hidden)]
    fn changed(&self, changes: &Changes<M>) -> bool;
    /// Rows whose slug is `value`.
    fn equals(&self, value: &str) -> Condition;
    /// Rows whose slug matches the `LIKE` pattern.
    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>>),
}

/// One slug column and its settings: an entry of the array that PHP's `sluggable()` returns.
/// Settings it doesn't set come from [`SluggableConfig`](crate::SluggableConfig).
///
/// ```ignore
/// Slug::new(Post::slug).source(Post::title)                       // ['slug' => ['source' => 'title']]
/// Slug::new(Post::slug).source(Post::title).source(Post::subtitle) // 'source' => ['title', 'subtitle']
/// Slug::new(Post::slug).source(Post::title).max_length(10).separator("_").on_update(true)
/// ```
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> {
    /// A slug stored in `column`, with no source yet.
    #[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,
        }
    }

    /// Adds a source column: `source`. Several sources are joined with spaces, in order.
    #[must_use]
    pub fn source(mut self, source: impl SlugSource<M>) -> Self {
        self.sources.push(Box::new(source));
        self
    }

    /// Adds a computed source, as PHP's sources that name an accessor or a relation's attribute.
    #[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
    }

    /// `maxLength`.
    #[must_use]
    pub fn max_length(mut self, max_length: impl Into<Option<usize>>) -> Self {
        self.max_length = Some(max_length.into());
        self
    }

    /// `maxLengthKeepWords`.
    #[must_use]
    pub fn max_length_keep_words(mut self, keep: bool) -> Self {
        self.max_length_keep_words = Some(keep);
        self
    }

    /// `method`: a closure `|source, separator| slug` used instead of the slug engine.
    #[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
    }

    /// `separator`.
    #[must_use]
    pub fn separator(mut self, separator: impl Into<String>) -> Self {
        self.separator = Some(separator.into());
        self
    }

    /// `unique`.
    #[must_use]
    pub fn unique(mut self, unique: bool) -> Self {
        self.unique = Some(unique);
        self
    }

    /// `uniqueSuffix`: a closure `|slug, separator, similar_slugs, first_suffix| suffix`.
    #[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
    }

    /// `firstUniqueSuffix`.
    #[must_use]
    pub fn first_unique_suffix(mut self, first: impl ToString) -> Self {
        self.first_unique_suffix = Some(first.to_string());
        self
    }

    /// `reserved` as a list.
    #[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
    }

    /// `reserved` as a closure of the model, returning the list or `None`.
    #[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
    }

    /// `onUpdate`.
    #[must_use]
    pub fn on_update(mut self, on_update: bool) -> Self {
        self.on_update = Some(on_update);
        self
    }

    /// `slugEngineOptions`.
    #[must_use]
    pub fn slug_engine_options(mut self, options: SlugifyOptions) -> Self {
        self.slug_engine_options = Some(options);
        self
    }

    /// The slug column's name.
    #[must_use]
    pub fn attribute(&self) -> &'static str {
        self.column.name()
    }

    /// Takes the settings `other` sets: PHP's `array_merge($modelConfig, $config)` in
    /// `createSlug`.
    #[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
    }

    /// The merged settings: PHP's `getConfiguration`.
    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),
        }
    }

    /// The source text: PHP's `getSlugSource`.
    fn source_text(&self, subject: &SlugSubject<'_, M>) -> String {
        self.sources
            .iter()
            .map(|source| source.text(subject))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// A model with slugs: the PHP package's `Sluggable` trait.
///
/// ```ignore
/// use laravel_sluggable::{Slug, Sluggable};
///
/// #[model(hooks)]
/// pub struct Post {
///     pub id: i64,
///     pub title: String,
///     pub slug: Option<String>,
/// }
///
/// impl Sluggable for Post {
///     fn sluggable() -> Vec<Slug<Self>> {
///         vec![Slug::new(Post::slug).source(Post::title)]
///     }
/// }
///
/// laravel_sluggable::sluggable_hooks!(Post);
/// ```
///
/// PHP hooks into the model's `saving` event; here the model's [`Hooks`](laravel::model::Hooks)
/// call [`creating`](crate::creating) and [`updating`](crate::updating), which
/// [`sluggable_hooks!`](crate::sluggable_hooks) does for you.
pub trait Sluggable: Model {
    /// The slug columns and their settings: `sluggable()`.
    fn sluggable() -> Vec<Slug<Self>>;

    /// Customizes the slug engine for one slug column: `customizeSlugEngine`.
    fn customize_slug_engine(engine: Slugify, _attribute: &str) -> Slugify {
        engine
    }

    /// The query for "similar" slugs, which decides uniqueness: `scopeFindSimilarSlugs`. By
    /// default, slugs equal to `slug` or `LIKE` `slug` + separator + `%`.
    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)]))
    }

    /// Adds constraints to the uniqueness query, such as limiting it to the same author:
    /// `scopeWithUniqueSlugConstraints`.
    fn with_unique_slug_constraints(
        query: Builder<Self>,
        _model: &SlugSubject<'_, Self>,
        _attribute: &str,
        _config: &SlugOptions,
        _slug: &str,
    ) -> Builder<Self> {
        query
    }
}

/// Generates the slugs of a create: call it from your model's `Hooks::creating`, as PHP's
/// observer does on `saving`.
///
/// # Errors
///
/// Fails when the uniqueness query fails.
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(())
}

/// Regenerates the slugs of an update when needed: call it from your model's `Hooks::updating`.
///
/// # Errors
///
/// Fails when the uniqueness query fails.
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);
            // PHP's `needsSlugging`: past `onUpdate` and a blank slug, a slug the update sets
            // itself is kept, and an existing row keeps its slug either way.
            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(())
}

/// Implements [`Hooks`](laravel::model::Hooks) for a [`Sluggable`] model, calling
/// [`creating`](crate::creating) and [`updating`](crate::updating). A model with hooks of its own
/// calls those two functions from them instead.
#[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
            }
        }
    };
}

/// The PHP package's `SlugService`.
pub struct SlugService;

impl SlugService {
    /// Slugs a saved model in memory: `SlugService::slug($model, $force)`. With `force`, every
    /// slug is regenerated. Returns whether a slug changed; save the model afterwards.
    ///
    /// # Errors
    ///
    /// Fails when the uniqueness query fails.
    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)
    }

    /// A unique slug for `from_string`, without saving anything:
    /// `SlugService::createSlug($model, $attribute, $fromString, $config)`. `model` is `None`
    /// when PHP is given the class name; `config` overrides the model's settings for `attribute`.
    ///
    /// # Errors
    ///
    /// Fails with [`InvalidSlugAttribute`] when `attribute` isn't one of the model's slugs and
    /// no `config` is given, and when the uniqueness query fails.
    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
    }
}

/// PHP's `needsSlugging`, before the dirty check.
fn needs_slugging(current: Option<&str>, config: &SlugOptions, force: bool) -> bool {
    force || config.on_update || is_blank(current)
}

/// `null` or `trim($value) === ''`.
fn is_blank(value: Option<&str>) -> bool {
    value.is_none_or(|value| value.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']).is_empty())
}

/// PHP's `buildSlug` after the `needsSlugging` check: `None` keeps the current slug.
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?))
}

/// PHP's `generateSlug`.
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,
    }
}

/// `mb_strrpos($slug, $separator, $maxLength - mb_strlen($slug))`: the character position of the
/// last separator that starts at or before `max`.
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[..])
}

/// PHP's `validateSlug`: a reserved slug gets a suffix.
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)
}

/// PHP's `makeSlugUnique`.
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))
}

/// PHP's `generateSuffix`. `is_own` is PHP's `$list->search($slug) === $this->model->getKey()`.
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(),
    }
}

/// PHP's `(int) $string`: leading whitespace, an optional sign, then digits.
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 }
}

/// PHP's `getExistingSlugs`: the similar slugs, by model key.
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)
}

/// The PHP package's `SluggableScopeHelpers` trait: the model's primary slug, and finding a
/// model by it. Implement it with an empty `impl SluggableScopeHelpers for Post {}`.
pub trait SluggableScopeHelpers: Sluggable {
    /// The primary slug column: `getSlugKeyName`. The first slug by default, as in PHP; override
    /// it as PHP's `$slugKeyName` property.
    fn slug_key_name() -> &'static str {
        Self::primary_slug().attribute()
    }

    /// The primary slug's column, for queries. The slug named by
    /// [`slug_key_name`](Self::slug_key_name).
    #[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)
    }

    /// The primary slug's value: `getSlugKey`.
    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)))
    }

    /// Models whose primary slug is `slug`: `scopeWhereSlug`.
    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))
    }

    /// The model whose primary slug is `slug`: `findBySlug`.
    fn find_by_slug(slug: &str) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
        Self::where_slug(slug).first()
    }

    /// The model whose primary slug is `slug`, or a `ModelNotFound` error (a 404 in a
    /// handler): `findBySlugOrFail`.
    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);
    }
}