1 <?php namespace BookStack\Entities;
3 use BookStack\Uploads\Image;
4 use Illuminate\Database\Eloquent\Relations\BelongsTo;
5 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7 class Bookshelf extends Entity implements HasCoverImage
9 protected $table = 'bookshelves';
11 public $searchFactor = 3;
13 protected $fillable = ['name', 'description', 'image_id'];
15 protected $hidden = ['restricted'];
18 * Get the books in this shelf.
19 * Should not be used directly since does not take into account permissions.
20 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
22 public function books()
24 return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
26 ->orderBy('order', 'asc');
30 * Related books that are visible to the current user.
32 public function visibleBooks(): BelongsToMany
34 return $this->books()->visible();
38 * Get the url for this bookshelf.
39 * @param string|bool $path
42 public function getUrl($path = false)
44 if ($path !== false) {
45 return url('/shelves/' . urlencode($this->slug) . '/' . trim($path, '/'));
47 return url('/shelves/' . urlencode($this->slug));
51 * Returns BookShelf cover image, if cover does not exists return default cover image.
52 * @param int $width - Width of the image
53 * @param int $height - Height of the image
56 public function getBookCover($width = 440, $height = 250)
58 // TODO - Make generic, focused on books right now, Perhaps set-up a better image
59 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
60 if (!$this->image_id) {
65 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
66 } catch (\Exception $err) {
73 * Get the cover image of the shelf
75 public function cover(): BelongsTo
77 return $this->belongsTo(Image::class, 'image_id');
81 * Get the type of the image model that is used when storing a cover image.
83 public function coverImageTypeKey(): string
89 * Get an excerpt of this book's description to the specified length or less.
93 public function getExcerpt(int $length = 100)
95 $description = $this->description;
96 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
100 * Check if this shelf contains the given book.
104 public function contains(Book $book): bool
106 return $this->books()->where('id', '=', $book->id)->count() > 0;
110 * Add a book to the end of this shelf.
113 public function appendBook(Book $book)
115 if ($this->contains($book)) {
119 $maxOrder = $this->books()->max('order');
120 $this->books()->attach($book->id, ['order' => $maxOrder + 1]);