]> BookStack Code Mirror - bookstack/blob - app/Entities/Queries/ChapterQueries.php
Queries: Updated all app book static query uses
[bookstack] / app / Entities / Queries / ChapterQueries.php
1 <?php
2
3 namespace BookStack\Entities\Queries;
4
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Exceptions\NotFoundException;
7 use Illuminate\Database\Eloquent\Builder;
8
9 class ChapterQueries implements ProvidesEntityQueries
10 {
11     protected static array $listAttributes = [
12         'id', 'slug', 'name', 'description', 'priority',
13         'created_at', 'updated_at',
14         'created_by', 'updated_by', 'owned_by',
15     ];
16
17     public function start(): Builder
18     {
19         return Chapter::query();
20     }
21
22     public function findVisibleById(int $id): ?Chapter
23     {
24         return $this->start()->scopes('visible')->find($id);
25     }
26
27     public function findVisibleByIdOrFail(int $id): Chapter
28     {
29         return $this->start()->scopes('visible')->findOrFail($id);
30     }
31
32     public function findVisibleBySlugsOrFail(string $bookSlug, string $chapterSlug): Chapter
33     {
34         /** @var ?Chapter $chapter */
35         $chapter = $this->start()
36             ->scopes('visible')
37             ->with('book')
38             ->whereHas('book', function (Builder $query) use ($bookSlug) {
39                 $query->where('slug', '=', $bookSlug);
40             })
41             ->where('slug', '=', $chapterSlug)
42             ->first();
43
44         if (is_null($chapter)) {
45             throw new NotFoundException(trans('errors.chapter_not_found'));
46         }
47
48         return $chapter;
49     }
50
51     public function usingSlugs(string $bookSlug, string $chapterSlug): Builder
52     {
53         return $this->start()
54             ->where('slug', '=', $chapterSlug)
55             ->whereHas('book', function (Builder $query) use ($bookSlug) {
56                 $query->where('slug', '=', $bookSlug);
57             });
58     }
59
60     public function visibleForList(): Builder
61     {
62         return $this->start()
63             ->scopes('visible')
64             ->select(array_merge(static::$listAttributes, ['book_slug' => function ($builder) {
65                 $builder->select('slug')
66                     ->from('books')
67                     ->whereColumn('books.id', '=', 'chapters.book_id');
68             }]));
69     }
70 }