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