1 <?php namespace BookStack\Entities;
3 use Illuminate\Support\Str;
9 * Generate a fresh slug for the given entity.
10 * The slug will generated so it does not conflict within the same parent item.
12 public function generate(Entity $entity): string
14 $slug = $this->formatNameAsSlug($entity->name);
15 while ($this->slugInUse($slug, $entity)) {
16 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
22 * Format a name as a url slug.
24 protected function formatNameAsSlug(string $name): string
26 $slug = Str::slug($name);
28 $slug = substr(md5(rand(1, 500)), 0, 5);
34 * Check if a slug is already in-use for this
35 * type of model within the same parent.
37 protected function slugInUse(string $slug, Entity $entity): bool
39 $query = $entity->newQuery()->where('slug', '=', $slug);
41 if ($entity instanceof BookChild) {
42 $query->where('book_id', '=', $entity->book_id);
46 $query->where('id', '!=', $entity->id);
49 return $query->count() > 0;