]> BookStack Code Mirror - bookstack/blob - app/Entities/Queries/ChapterQueries.php
DB: Aligned entity structure to a common table
[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 /**
10  * @implements ProvidesEntityQueries<Chapter>
11  */
12 class ChapterQueries implements ProvidesEntityQueries
13 {
14     protected static array $listAttributes = [
15         'id', 'slug', 'name', 'description', 'priority',
16         'book_id', 'created_at', 'updated_at', 'owned_by',
17     ];
18
19     public function start(): Builder
20     {
21         return Chapter::query();
22     }
23
24     public function findVisibleById(int $id): ?Chapter
25     {
26         return $this->start()->scopes('visible')->find($id);
27     }
28
29     public function findVisibleByIdOrFail(int $id): Chapter
30     {
31         return $this->start()->scopes('visible')->findOrFail($id);
32     }
33
34     public function findVisibleBySlugsOrFail(string $bookSlug, string $chapterSlug): Chapter
35     {
36         /** @var ?Chapter $chapter */
37         $chapter = $this->start()
38             ->scopes('visible')
39             ->with('book')
40             ->whereHas('book', function (Builder $query) use ($bookSlug) {
41                 $query->where('slug', '=', $bookSlug);
42             })
43             ->where('slug', '=', $chapterSlug)
44             ->first();
45
46         if (is_null($chapter)) {
47             throw new NotFoundException(trans('errors.chapter_not_found'));
48         }
49
50         return $chapter;
51     }
52
53     public function usingSlugs(string $bookSlug, string $chapterSlug): Builder
54     {
55         return $this->start()
56             ->where('slug', '=', $chapterSlug)
57             ->whereHas('book', function (Builder $query) use ($bookSlug) {
58                 $query->where('slug', '=', $bookSlug);
59             });
60     }
61
62     public function visibleForList(): Builder
63     {
64         return $this->start()
65             ->scopes('visible')
66             ->select(array_merge(static::$listAttributes, ['book_slug' => function ($builder) {
67                 $builder->select('slug')
68                     ->from('entities as books')
69                     ->where('type', '=', 'book')
70                     ->whereColumn('books.id', '=', 'entities.book_id');
71             }]));
72     }
73
74     public function visibleForContent(): Builder
75     {
76         return $this->start()->scopes('visible');
77     }
78 }