3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\BookChild;
6 use BookStack\Interfaces\Sluggable;
7 use Illuminate\Support\Str;
12 * Generate a fresh slug for the given entity.
13 * The slug will generated so it does not conflict within the same parent item.
15 public function generate(Sluggable $model): string
17 $slug = $this->formatNameAsSlug($model->name);
18 while ($this->slugInUse($slug, $model)) {
19 $slug .= '-' . Str::random(3);
26 * Format a name as a url slug.
28 protected function formatNameAsSlug(string $name): string
30 $slug = Str::slug($name);
32 $slug = substr(md5(rand(1, 500)), 0, 5);
39 * Check if a slug is already in-use for this
40 * type of model within the same parent.
42 protected function slugInUse(string $slug, Sluggable $model): bool
44 $query = $model->newQuery()->where('slug', '=', $slug);
46 if ($model instanceof BookChild) {
47 $query->where('book_id', '=', $model->book_id);
51 $query->where('id', '!=', $model->id);
54 return $query->count() > 0;