1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Entities\Models\Bookshelf;
4 use BookStack\Entities\Models\Chapter;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Entities\Models\HasCoverImage;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Uploads\Image;
10 use Illuminate\Database\Eloquent\Relations\BelongsTo;
11 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
12 use Illuminate\Database\Eloquent\Relations\HasMany;
13 use Illuminate\Support\Collection;
17 * @property string $description
18 * @property int $image_id
19 * @property Image|null $cover
21 class Book extends Entity implements HasCoverImage
23 public $searchFactor = 2;
25 protected $fillable = ['name', 'description'];
26 protected $hidden = ['restricted', 'pivot', 'image_id'];
29 * Get the url for this book.
30 * @param string|bool $path
33 public function getUrl($path = false)
35 if ($path !== false) {
36 return url('/books/' . urlencode($this->slug) . '/' . trim($path, '/'));
38 return url('/books/' . urlencode($this->slug));
42 * Returns book cover image, if book cover not exists return default cover image.
43 * @param int $width - Width of the image
44 * @param int $height - Height of the image
47 public function getBookCover($width = 440, $height = 250)
49 $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
50 if (!$this->image_id) {
55 $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
56 } catch (Exception $err) {
63 * Get the cover image of the book
65 public function cover(): BelongsTo
67 return $this->belongsTo(Image::class, 'image_id');
71 * Get the type of the image model that is used when storing a cover image.
73 public function coverImageTypeKey(): string
79 * Get all pages within this book.
82 public function pages()
84 return $this->hasMany(Page::class);
88 * Get the direct child pages of this book.
91 public function directPages()
93 return $this->pages()->where('chapter_id', '=', '0');
97 * Get all chapters within this book.
100 public function chapters()
102 return $this->hasMany(Chapter::class);
106 * Get the shelves this book is contained within.
107 * @return BelongsToMany
109 public function shelves()
111 return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
115 * Get the direct child items within this book.
118 public function getDirectChildren(): Collection
120 $pages = $this->directPages()->visible()->get();
121 $chapters = $this->chapters()->visible()->get();
122 return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft');
126 * Get an excerpt of this book's description to the specified length or less.
130 public function getExcerpt(int $length = 100)
132 $description = $this->description;
133 return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;