3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\BookChild;
6 use BookStack\Interfaces\Sluggable;
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.
42 * @param Sluggable&Model $model
44 protected function slugInUse(string $slug, Sluggable $model): bool
46 $query = $model->newQuery()->where('slug', '=', $slug);
48 if ($model instanceof BookChild) {
49 $query->where('book_id', '=', $model->book_id);
53 $query->where('id', '!=', $model->id);
56 return $query->count() > 0;