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