]> BookStack Code Mirror - bookstack/blobdiff - app/Entities/Bookshelf.php
Show bookshelves that a book belongs to on a book view
[bookstack] / app / Entities / Bookshelf.php
index 08ce8d8cba06d8f71d0d452a3829ea4a971978c5..7ad2415ed938628725d88ece0f010638c6f6493c 100644 (file)
@@ -26,7 +26,9 @@ class Bookshelf extends Entity
      */
     public function books()
     {
-        return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')->orderBy('order', 'asc');
+        return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
+            ->withPivot('order')
+            ->orderBy('order', 'asc');
     }
 
     /**
@@ -37,9 +39,9 @@ class Bookshelf extends Entity
     public function getUrl($path = false)
     {
         if ($path !== false) {
-            return baseUrl('/shelves/' . urlencode($this->slug) . '/' . trim($path, '/'));
+            return url('/shelves/' . urlencode($this->slug) . '/' . trim($path, '/'));
         }
-        return baseUrl('/shelves/' . urlencode($this->slug));
+        return url('/shelves/' . urlencode($this->slug));
     }
 
     /**
@@ -57,7 +59,7 @@ class Bookshelf extends Entity
         }
 
         try {
-            $cover = $this->cover ? baseUrl($this->cover->getThumb($width, $height, false)) : $default;
+            $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
         } catch (\Exception $err) {
             $cover = $default;
         }
@@ -81,7 +83,7 @@ class Bookshelf extends Entity
     public function getExcerpt(int $length = 100)
     {
         $description = $this->description;
-        return strlen($description) > $length ? substr($description, 0, $length-3) . '...' : $description;
+        return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
     }
 
     /**
@@ -98,8 +100,22 @@ class Bookshelf extends Entity
      * @param Book $book
      * @return bool
      */
-    public function contains(Book $book)
+    public function contains(Book $book): bool 
     {
         return $this->books()->where('id', '=', $book->id)->count() > 0;
     }
+
+    /**
+     * Add a book to the end of this shelf.
+     * @param Book $book
+     */
+    public function appendBook(Book $book)
+    {
+       if ($this->contains($book)) {
+           return;
+       }
+
+       $maxOrder = $this->books()->max('order');
+       $this->books()->attach($book->id, ['order' => $maxOrder + 1]);
+    }
 }