]> BookStack Code Mirror - bookstack/blob - app/Entities/Queries/ChapterQueries.php
Add optional OIDC avatar fetching from the “picture” claim
[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         'book_id', 'created_at', 'updated_at', 'owned_by',
14     ];
15
16     public function start(): Builder
17     {
18         return Chapter::query();
19     }
20
21     public function findVisibleById(int $id): ?Chapter
22     {
23         return $this->start()->scopes('visible')->find($id);
24     }
25
26     public function findVisibleByIdOrFail(int $id): Chapter
27     {
28         return $this->start()->scopes('visible')->findOrFail($id);
29     }
30
31     public function findVisibleBySlugsOrFail(string $bookSlug, string $chapterSlug): Chapter
32     {
33         /** @var ?Chapter $chapter */
34         $chapter = $this->start()
35             ->scopes('visible')
36             ->with('book')
37             ->whereHas('book', function (Builder $query) use ($bookSlug) {
38                 $query->where('slug', '=', $bookSlug);
39             })
40             ->where('slug', '=', $chapterSlug)
41             ->first();
42
43         if (is_null($chapter)) {
44             throw new NotFoundException(trans('errors.chapter_not_found'));
45         }
46
47         return $chapter;
48     }
49
50     public function usingSlugs(string $bookSlug, string $chapterSlug): Builder
51     {
52         return $this->start()
53             ->where('slug', '=', $chapterSlug)
54             ->whereHas('book', function (Builder $query) use ($bookSlug) {
55                 $query->where('slug', '=', $bookSlug);
56             });
57     }
58
59     public function visibleForList(): Builder
60     {
61         return $this->start()
62             ->scopes('visible')
63             ->select(array_merge(static::$listAttributes, ['book_slug' => function ($builder) {
64                 $builder->select('slug')
65                     ->from('books')
66                     ->whereColumn('books.id', '=', 'chapters.book_id');
67             }]));
68     }
69 }