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