1 <?php namespace BookStack\Entities;
9 * SlugGenerator constructor.
12 public function __construct(Entity $entity)
14 $this->entity = $entity;
18 * Generate a fresh slug for the given entity.
19 * The slug will generated so it does not conflict within the same parent item.
21 public function generate(): string
23 $slug = $this->formatNameAsSlug($this->entity->name);
24 while ($this->slugInUse($slug)) {
25 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
31 * Format a name as a url slug.
33 protected function formatNameAsSlug(string $name): string
35 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
36 $slug = preg_replace('/\s{2,}/', ' ', $slug);
37 $slug = str_replace(' ', '-', $slug);
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;