1 <?php namespace BookStack\Entities;
3 use BookStack\Uploads\Image;
5 use Illuminate\Database\Eloquent\Relations\BelongsTo;
6 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7 use Illuminate\Database\Eloquent\Relations\HasMany;
8 use Illuminate\Support\Collection;
12 * @property string $description
13 * @property int $image_id
14 * @property Image|null $cover
15 * @package BookStack\Entities
17 class Book extends Entity implements HasCoverImage
19 public $searchFactor = 2;
21 protected $fillable = ['name', 'description', 'image_id'];
24 * Get the url for this book.
25 * @param string|bool $path
28 public function getUrl($path = false)
30 if ($path !== false) {
31 return url('/books/' . urlencode($this->slug) . '/' . trim($path, '/'));
33 return url('/books/' . urlencode($this->slug));
37 * Returns book cover image, if book cover not exists return default cover image.
38 * @param int $width - Width of the image
39 * @param int $height - Height of the image
42 public function getBookCover($width = 440, $height = 250)
44 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
45 if (!$this->image_id) {
50 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
51 } catch (Exception $err) {
58 * Get the cover image of the book
60 public function cover(): BelongsTo
62 return $this->belongsTo(Image::class, 'image_id');
66 * Get the type of the image model that is used when storing a cover image.
68 public function coverImageTypeKey(): string
74 * Get all pages within this book.
77 public function pages()
79 return $this->hasMany(Page::class);
83 * Get the direct child pages of this book.
86 public function directPages()
88 return $this->pages()->where('chapter_id', '=', '0');
92 * Get all chapters within this book.
95 public function chapters()
97 return $this->hasMany(Chapter::class);
101 * Get the shelves this book is contained within.
102 * @return BelongsToMany
104 public function shelves()
106 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
110 * Get the direct child items within this book.
113 public function getDirectChildren(): Collection
115 $pages = $this->directPages()->visible()->get();
116 $chapters = $this->chapters()->visible()->get();
117 return $pages->contact($chapters)->sortBy('priority')->sortByDesc('draft');
121 * Get an excerpt of this book's description to the specified length or less.
125 public function getExcerpt(int $length = 100)
127 $description = $this->description;
128 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;