]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SlugGenerator.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Entities / Tools / SlugGenerator.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\App\Model;
6 use BookStack\App\Sluggable;
7 use BookStack\Entities\Models\BookChild;
8 use Illuminate\Support\Str;
9
10 class SlugGenerator
11 {
12     /**
13      * Generate a fresh slug for the given entity.
14      * The slug will be generated so that it doesn't conflict within the same parent item.
15      */
16     public function generate(Sluggable $model): string
17     {
18         $slug = $this->formatNameAsSlug($model->name);
19         while ($this->slugInUse($slug, $model)) {
20             $slug .= '-' . Str::random(3);
21         }
22
23         return $slug;
24     }
25
26     /**
27      * Format a name as a url slug.
28      */
29     protected function formatNameAsSlug(string $name): string
30     {
31         $slug = Str::slug($name);
32         if ($slug === '') {
33             $slug = substr(md5(rand(1, 500)), 0, 5);
34         }
35
36         return $slug;
37     }
38
39     /**
40      * Check if a slug is already in-use for this
41      * type of model within the same parent.
42      *
43      * @param Sluggable&Model $model
44      */
45     protected function slugInUse(string $slug, Sluggable $model): bool
46     {
47         $query = $model->newQuery()->where('slug', '=', $slug);
48
49         if ($model instanceof BookChild) {
50             $query->where('book_id', '=', $model->book_id);
51         }
52
53         if ($model->id) {
54             $query->where('id', '!=', $model->id);
55         }
56
57         return $query->count() > 0;
58     }
59 }