1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Entities\Models\Entity;
4 use Illuminate\Support\Str;
10 * Generate a fresh slug for the given entity.
11 * The slug will generated so it does not conflict within the same parent item.
13 public function generate(Entity $entity): string
15 $slug = $this->formatNameAsSlug($entity->name);
16 while ($this->slugInUse($slug, $entity)) {
17 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
23 * Format a name as a url slug.
25 protected function formatNameAsSlug(string $name): string
27 $slug = Str::slug($name);
29 $slug = substr(md5(rand(1, 500)), 0, 5);
35 * Check if a slug is already in-use for this
36 * type of model within the same parent.
38 protected function slugInUse(string $slug, Entity $entity): bool
40 $query = $entity->newQuery()->where('slug', '=', $slug);
42 if ($entity instanceof BookChild) {
43 $query->where('book_id', '=', $entity->book_id);
47 $query->where('id', '!=', $entity->id);
50 return $query->count() > 0;