]> BookStack Code Mirror - bookstack/blob - app/Entities/SlugGenerator.php
Add support Windows Authentication via SAML
[bookstack] / app / Entities / SlugGenerator.php
1 <?php namespace BookStack\Entities;
2
3 class SlugGenerator
4 {
5
6     protected $entity;
7
8     /**
9      * SlugGenerator constructor.
10      * @param $entity
11      */
12     public function __construct(Entity $entity)
13     {
14         $this->entity = $entity;
15     }
16
17     /**
18      * Generate a fresh slug for the given entity.
19      * The slug will generated so it does not conflict within the same parent item.
20      */
21     public function generate(): string
22     {
23         $slug = $this->formatNameAsSlug($this->entity->name);
24         while ($this->slugInUse($slug)) {
25             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
26         }
27         return $slug;
28     }
29
30     /**
31      * Format a name as a url slug.
32      */
33     protected function formatNameAsSlug(string $name): string
34     {
35         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
36         $slug = preg_replace('/\s{2,}/', ' ', $slug);
37         $slug = str_replace(' ', '-', $slug);
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 }