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