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