]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/ChapterApiController.php
Default chapter templates: Added tests, extracted repo logic
[bookstack] / app / Entities / Controllers / ChapterApiController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Repos\ChapterRepo;
8 use BookStack\Exceptions\PermissionsException;
9 use BookStack\Http\ApiController;
10 use Exception;
11 use Illuminate\Database\Eloquent\Relations\HasMany;
12 use Illuminate\Http\Request;
13
14 class ChapterApiController extends ApiController
15 {
16     protected $rules = [
17         'create' => [
18             'book_id'             => ['required', 'integer'],
19             'name'                => ['required', 'string', 'max:255'],
20             'description'         => ['string', 'max:1900'],
21             'description_html'    => ['string', 'max:2000'],
22             'tags'                => ['array'],
23             'priority'            => ['integer'],
24             'default_template_id' => ['nullable', 'integer'],
25         ],
26         'update' => [
27             'book_id'             => ['integer'],
28             'name'                => ['string', 'min:1', 'max:255'],
29             'description'         => ['string', 'max:1900'],
30             'description_html'    => ['string', 'max:2000'],
31             'tags'                => ['array'],
32             'priority'            => ['integer'],
33             'default_template_id' => ['nullable', 'integer'],
34         ],
35     ];
36
37     public function __construct(
38         protected ChapterRepo $chapterRepo
39     ) {
40     }
41
42     /**
43      * Get a listing of chapters visible to the user.
44      */
45     public function list()
46     {
47         $chapters = Chapter::visible();
48
49         return $this->apiListingResponse($chapters, [
50             'id', 'book_id', 'name', 'slug', 'description', 'priority',
51             'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by',
52         ]);
53     }
54
55     /**
56      * Create a new chapter in the system.
57      */
58     public function create(Request $request)
59     {
60         $requestData = $this->validate($request, $this->rules['create']);
61
62         $bookId = $request->get('book_id');
63         $book = Book::visible()->findOrFail($bookId);
64         $this->checkOwnablePermission('chapter-create', $book);
65
66         $chapter = $this->chapterRepo->create($requestData, $book);
67
68         return response()->json($this->forJsonDisplay($chapter));
69     }
70
71     /**
72      * View the details of a single chapter.
73      */
74     public function read(string $id)
75     {
76         $chapter = Chapter::visible()->findOrFail($id);
77         $chapter = $this->forJsonDisplay($chapter);
78
79         $chapter->load([
80             'createdBy', 'updatedBy', 'ownedBy',
81             'pages' => function (HasMany $query) {
82                 $query->scopes('visible')->get(['id', 'name', 'slug']);
83             }
84         ]);
85
86         return response()->json($chapter);
87     }
88
89     /**
90      * Update the details of a single chapter.
91      * Providing a 'book_id' property will essentially move the chapter
92      * into that parent element if you have permissions to do so.
93      */
94     public function update(Request $request, string $id)
95     {
96         $requestData = $this->validate($request, $this->rules()['update']);
97         $chapter = Chapter::visible()->findOrFail($id);
98         $this->checkOwnablePermission('chapter-update', $chapter);
99
100         if ($request->has('book_id') && $chapter->book_id !== intval($requestData['book_id'])) {
101             $this->checkOwnablePermission('chapter-delete', $chapter);
102
103             try {
104                 $this->chapterRepo->move($chapter, "book:{$requestData['book_id']}");
105             } catch (Exception $exception) {
106                 if ($exception instanceof PermissionsException) {
107                     $this->showPermissionError();
108                 }
109
110                 return $this->jsonError(trans('errors.selected_book_not_found'));
111             }
112         }
113
114         $updatedChapter = $this->chapterRepo->update($chapter, $requestData);
115
116         return response()->json($this->forJsonDisplay($updatedChapter));
117     }
118
119     /**
120      * Delete a chapter.
121      * This will typically send the chapter to the recycle bin.
122      */
123     public function delete(string $id)
124     {
125         $chapter = Chapter::visible()->findOrFail($id);
126         $this->checkOwnablePermission('chapter-delete', $chapter);
127
128         $this->chapterRepo->destroy($chapter);
129
130         return response('', 204);
131     }
132
133     protected function forJsonDisplay(Chapter $chapter): Chapter
134     {
135         $chapter = clone $chapter;
136         $chapter->unsetRelations()->refresh();
137
138         $chapter->load(['tags']);
139         $chapter->makeVisible('description_html')
140             ->setAttribute('description_html', $chapter->descriptionHtml());
141
142         return $chapter;
143     }
144 }