1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Entities\Models\Entity;
4 use BookStack\Entities\Models\HasCoverImage;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Uploads\Image;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
10 class Bookshelf extends Entity implements HasCoverImage
12 protected $table = 'bookshelves';
14 public $searchFactor = 3;
16 protected $fillable = ['name', 'description', 'image_id'];
18 protected $hidden = ['restricted', 'image_id'];
21 * Get the books in this shelf.
22 * Should not be used directly since does not take into account permissions.
23 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
25 public function books()
27 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
29 ->orderBy('order', 'asc');
33 * Related books that are visible to the current user.
35 public function visibleBooks(): BelongsToMany
37 return $this->books()->visible();
41 * Get the url for this bookshelf.
42 * @param string|bool $path
45 public function getUrl($path = false)
47 if ($path !== false) {
48 return url('/shelves/' . urlencode($this->slug) . '/' . trim($path, '/'));
50 return url('/shelves/' . urlencode($this->slug));
54 * Returns BookShelf cover image, if cover does not exists return default cover image.
55 * @param int $width - Width of the image
56 * @param int $height - Height of the image
59 public function getBookCover($width = 440, $height = 250)
61 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
62 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
63 if (!$this->image_id) {
68 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
69 } catch (\Exception $err) {
76 * Get the cover image of the shelf
78 public function cover(): BelongsTo
80 return $this->belongsTo(Image::class, 'image_id');
84 * Get the type of the image model that is used when storing a cover image.
86 public function coverImageTypeKey(): string
92 * Get an excerpt of this book's description to the specified length or less.
96 public function getExcerpt(int $length = 100)
98 $description = $this->description;
99 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
103 * Check if this shelf contains the given book.
107 public function contains(Book $book): bool
109 return $this->books()->where('id', '=', $book->id)->count() > 0;
113 * Add a book to the end of this shelf.
116 public function appendBook(Book $book)
118 if ($this->contains($book)) {
122 $maxOrder = $this->books()->max('order');
123 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);