]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Bookshelf.php
Merge pull request #5917 from BookStackApp/copy_references
[bookstack] / app / Entities / Models / Bookshelf.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\Entities\Tools\EntityCover;
6 use BookStack\Uploads\Image;
7 use Illuminate\Database\Eloquent\Factories\HasFactory;
8 use Illuminate\Database\Eloquent\Relations\BelongsTo;
9 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
10
11 /**
12  * @property string $description
13  * @property string $description_html
14  */
15 class Bookshelf extends Entity implements HasDescriptionInterface, HasCoverInterface
16 {
17     use HasFactory;
18     use ContainerTrait;
19
20     public float $searchFactor = 1.2;
21
22     protected $hidden = ['image_id', 'deleted_at', 'description_html', 'priority', 'default_template_id', 'sort_rule_id', 'entity_id', 'entity_type', 'chapter_id', 'book_id'];
23     protected $fillable = ['name'];
24
25     /**
26      * Get the books in this shelf.
27      * Should not be used directly since it does not take into account permissions.
28      */
29     public function books(): BelongsToMany
30     {
31         return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id')
32             ->select(['entities.*', 'entity_container_data.*'])
33             ->withPivot('order')
34             ->orderBy('order', 'asc');
35     }
36
37     /**
38      * Related books that are visible to the current user.
39      */
40     public function visibleBooks(): BelongsToMany
41     {
42         return $this->books()->scopes('visible');
43     }
44
45     /**
46      * Get the url for this bookshelf.
47      */
48     public function getUrl(string $path = ''): string
49     {
50         return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')]));
51     }
52
53     /**
54      * Check if this shelf contains the given book.
55      */
56     public function contains(Book $book): bool
57     {
58         return $this->books()->where('id', '=', $book->id)->count() > 0;
59     }
60
61     /**
62      * Add a book to the end of this shelf.
63      */
64     public function appendBook(Book $book): void
65     {
66         if ($this->contains($book)) {
67             return;
68         }
69
70         $maxOrder = $this->books()->max('order');
71         $this->books()->attach($book->id, ['order' => $maxOrder + 1]);
72     }
73
74     public function coverInfo(): EntityCover
75     {
76         return new EntityCover($this);
77     }
78
79     public function cover(): BelongsTo
80     {
81         return $this->belongsTo(Image::class, 'image_id');
82     }
83 }