]> BookStack Code Mirror - bookstack/blobdiff - app/Entities/Tools/SlugGenerator.php
Extend /users API endpoint
[bookstack] / app / Entities / Tools / SlugGenerator.php
index 884f126e8ecf7edd9d1ce61f2fe5c0a36395b0aa..4501279f2a31d3c367e6a2ce34be9f1afedaf639 100644 (file)
@@ -1,5 +1,7 @@
-<?php namespace BookStack\Entities;
+<?php namespace BookStack\Entities\Tools;
 
+use BookStack\Entities\Models\BookChild;
+use BookStack\Interfaces\Sluggable;
 use Illuminate\Support\Str;
 
 class SlugGenerator
@@ -9,11 +11,11 @@ class SlugGenerator
      * Generate a fresh slug for the given entity.
      * The slug will generated so it does not conflict within the same parent item.
      */
-    public function generate(Entity $entity): string
+    public function generate(Sluggable $model): string
     {
-        $slug = $this->formatNameAsSlug($entity->name);
-        while ($this->slugInUse($slug, $entity)) {
-            $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
+        $slug = $this->formatNameAsSlug($model->name);
+        while ($this->slugInUse($slug, $model)) {
+            $slug .= '-' . Str::random(3);
         }
         return $slug;
     }
@@ -34,16 +36,16 @@ class SlugGenerator
      * Check if a slug is already in-use for this
      * type of model within the same parent.
      */
-    protected function slugInUse(string $slug, Entity $entity): bool
+    protected function slugInUse(string $slug, Sluggable $model): bool
     {
-        $query = $entity->newQuery()->where('slug', '=', $slug);
+        $query = $model->newQuery()->where('slug', '=', $slug);
 
-        if ($entity instanceof BookChild) {
-            $query->where('book_id', '=', $entity->book_id);
+        if ($model instanceof BookChild) {
+            $query->where('book_id', '=', $model->book_id);
         }
 
-        if ($entity->id) {
-            $query->where('id', '!=', $entity->id);
+        if ($model->id) {
+            $query->where('id', '!=', $model->id);
         }
 
         return $query->count() > 0;