1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Entities\Models\BookChild;
4 use BookStack\Interfaces\Sluggable;
5 use Illuminate\Support\Str;
11 * Generate a fresh slug for the given entity.
12 * The slug will generated so it does not conflict within the same parent item.
14 public function generate(Sluggable $model): string
16 $slug = $this->formatNameAsSlug($model->name);
17 while ($this->slugInUse($slug, $model)) {
18 $slug .= '-' . Str::random(3);
24 * Format a name as a url slug.
26 protected function formatNameAsSlug(string $name): string
28 $slug = Str::slug($name);
30 $slug = substr(md5(rand(1, 500)), 0, 5);
36 * Check if a slug is already in-use for this
37 * type of model within the same parent.
39 protected function slugInUse(string $slug, Sluggable $model): bool
41 $query = $model->newQuery()->where('slug', '=', $slug);
43 if ($model instanceof BookChild) {
44 $query->where('book_id', '=', $model->book_id);
48 $query->where('id', '!=', $model->id);
51 return $query->count() > 0;