]> BookStack Code Mirror - bookstack/blob - app/Entities/Queries/BookQueries.php
API: Added test to cover system info endpoint
[bookstack] / app / Entities / Queries / BookQueries.php
1 <?php
2
3 namespace BookStack\Entities\Queries;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Exceptions\NotFoundException;
7 use Illuminate\Database\Eloquent\Builder;
8
9 class BookQueries implements ProvidesEntityQueries
10 {
11     protected static array $listAttributes = [
12         'id', 'slug', 'name', 'description',
13         'created_at', 'updated_at', 'image_id', 'owned_by',
14     ];
15
16     public function start(): Builder
17     {
18         return Book::query();
19     }
20
21     public function findVisibleById(int $id): ?Book
22     {
23         return $this->start()->scopes('visible')->find($id);
24     }
25
26     public function findVisibleByIdOrFail(int $id): Book
27     {
28         return $this->start()->scopes('visible')->findOrFail($id);
29     }
30
31     public function findVisibleBySlugOrFail(string $slug): Book
32     {
33         /** @var ?Book $book */
34         $book = $this->start()
35             ->scopes('visible')
36             ->where('slug', '=', $slug)
37             ->first();
38
39         if ($book === null) {
40             throw new NotFoundException(trans('errors.book_not_found'));
41         }
42
43         return $book;
44     }
45
46     public function visibleForList(): Builder
47     {
48         return $this->start()->scopes('visible')
49             ->select(static::$listAttributes);
50     }
51
52     public function visibleForListWithCover(): Builder
53     {
54         return $this->visibleForList()->with('cover');
55     }
56
57     public function recentlyViewedForCurrentUser(): Builder
58     {
59         return $this->visibleForList()
60             ->scopes('withLastView')
61             ->having('last_viewed_at', '>', 0)
62             ->orderBy('last_viewed_at', 'desc');
63     }
64
65     public function popularForList(): Builder
66     {
67         return $this->visibleForList()
68             ->scopes('withViewCount')
69             ->having('view_count', '>', 0)
70             ->orderBy('view_count', 'desc');
71     }
72 }