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