3 namespace BookStack\Entities\Tools;
5 use BookStack\App\Model;
6 use BookStack\App\Sluggable;
7 use BookStack\Entities\Models\BookChild;
8 use Illuminate\Support\Str;
13 * Generate a fresh slug for the given entity.
14 * The slug will be generated so that it doesn't conflict within the same parent item.
16 public function generate(Sluggable $model): string
18 $slug = $this->formatNameAsSlug($model->name);
19 while ($this->slugInUse($slug, $model)) {
20 $slug .= '-' . Str::random(3);
27 * Format a name as a url slug.
29 protected function formatNameAsSlug(string $name): string
31 $slug = Str::slug($name);
33 $slug = substr(md5(rand(1, 500)), 0, 5);
40 * Check if a slug is already in-use for this
41 * type of model within the same parent.
43 * @param Sluggable&Model $model
45 protected function slugInUse(string $slug, Sluggable $model): bool
47 $query = $model->newQuery()->where('slug', '=', $slug);
49 if ($model instanceof BookChild) {
50 $query->where('book_id', '=', $model->book_id);
54 $query->where('id', '!=', $model->id);
57 return $query->count() > 0;