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'];
22 protected $hidden = ['restricted'];
25 * Get the url for this book.
26 * @param string|bool $path
29 public function getUrl($path = false)
31 if ($path !== false) {
32 return url('/books/' . urlencode($this->slug) . '/' . trim($path, '/'));
34 return url('/books/' . urlencode($this->slug));
38 * Returns book cover image, if book cover not exists return default cover image.
39 * @param int $width - Width of the image
40 * @param int $height - Height of the image
43 public function getBookCover($width = 440, $height = 250)
45 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
46 if (!$this->image_id) {
51 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
52 } catch (Exception $err) {
59 * Get the cover image of the book
61 public function cover(): BelongsTo
63 return $this->belongsTo(Image::class, 'image_id');
67 * Get the type of the image model that is used when storing a cover image.
69 public function coverImageTypeKey(): string
75 * Get all pages within this book.
78 public function pages()
80 return $this->hasMany(Page::class);
84 * Get the direct child pages of this book.
87 public function directPages()
89 return $this->pages()->where('chapter_id', '=', '0');
93 * Get all chapters within this book.
96 public function chapters()
98 return $this->hasMany(Chapter::class);
102 * Get the shelves this book is contained within.
103 * @return BelongsToMany
105 public function shelves()
107 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
111 * Get the direct child items within this book.
114 public function getDirectChildren(): Collection
116 $pages = $this->directPages()->visible()->get();
117 $chapters = $this->chapters()->visible()->get();
118 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');
122 * Get an excerpt of this book's description to the specified length or less.
126 public function getExcerpt(int $length = 100)
128 $description = $this->description;
129 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;