1 <?php namespace BookStack\Entities;
3 use Illuminate\Support\Str;
11 * SlugGenerator constructor.
14 public function __construct(Entity $entity)
16 $this->entity = $entity;
20 * Generate a fresh slug for the given entity.
21 * The slug will generated so it does not conflict within the same parent item.
23 public function generate(): string
25 $slug = $this->formatNameAsSlug($this->entity->name);
26 while ($this->slugInUse($slug)) {
27 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
33 * Format a name as a url slug.
35 protected function formatNameAsSlug(string $name): string
37 $slug = Str::slug($name);
39 $slug = substr(md5(rand(1, 500)), 0, 5);
45 * Check if a slug is already in-use for this
46 * type of model within the same parent.
48 protected function slugInUse(string $slug): bool
50 $query = $this->entity->newQuery()->where('slug', '=', $slug);
52 if ($this->entity instanceof BookChild) {
53 $query->where('book_id', '=', $this->entity->book_id);
56 if ($this->entity->id) {
57 $query->where('id', '!=', $this->entity->id);
60 return $query->count() > 0;