]> BookStack Code Mirror - bookstack/blob - app/Entities/Queries/ChapterQueries.php
Queries: Extracted PageRepo queries to own class
[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 findVisibleBySlugsOrFail(string $bookSlug, string $chapterSlug): Chapter
28     {
29         /** @var ?Chapter $chapter */
30         $chapter = $this->start()->with('book')
31             ->whereHas('book', function (Builder $query) use ($bookSlug) {
32                 $query->where('slug', '=', $bookSlug);
33             })
34             ->where('slug', '=', $chapterSlug)
35             ->first();
36
37         if (is_null($chapter)) {
38             throw new NotFoundException(trans('errors.chapter_not_found'));
39         }
40
41         return $chapter;
42     }
43
44     public function visibleForList(): Builder
45     {
46         return $this->start()
47             ->select(array_merge(static::$listAttributes, ['book_slug' => function ($builder) {
48                 $builder->select('slug')
49                     ->from('books')
50                     ->whereColumn('books.id', '=', 'chapters.book_id');
51             }]));
52     }
53 }