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