]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/CommentController.php
Cleaned up namespacing in routes
[bookstack] / app / Activity / Controllers / CommentController.php
1 <?php
2
3 namespace BookStack\Activity\Controllers;
4
5 use BookStack\Activity\CommentRepo;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Http\Controller;
8 use Illuminate\Http\Request;
9 use Illuminate\Validation\ValidationException;
10
11 class CommentController extends Controller
12 {
13     protected $commentRepo;
14
15     public function __construct(CommentRepo $commentRepo)
16     {
17         $this->commentRepo = $commentRepo;
18     }
19
20     /**
21      * Save a new comment for a Page.
22      *
23      * @throws ValidationException
24      */
25     public function savePageComment(Request $request, int $pageId)
26     {
27         $this->validate($request, [
28             'text'      => ['required', 'string'],
29             'parent_id' => ['nullable', 'integer'],
30         ]);
31
32         $page = Page::visible()->find($pageId);
33         if ($page === null) {
34             return response('Not found', 404);
35         }
36
37         // Prevent adding comments to draft pages
38         if ($page->draft) {
39             return $this->jsonError(trans('errors.cannot_add_comment_to_draft'), 400);
40         }
41
42         // Create a new comment.
43         $this->checkPermission('comment-create-all');
44         $comment = $this->commentRepo->create($page, $request->get('text'), $request->get('parent_id'));
45
46         return view('comments.comment', ['comment' => $comment]);
47     }
48
49     /**
50      * Update an existing comment.
51      *
52      * @throws ValidationException
53      */
54     public function update(Request $request, int $commentId)
55     {
56         $this->validate($request, [
57             'text' => ['required', 'string'],
58         ]);
59
60         $comment = $this->commentRepo->getById($commentId);
61         $this->checkOwnablePermission('page-view', $comment->entity);
62         $this->checkOwnablePermission('comment-update', $comment);
63
64         $comment = $this->commentRepo->update($comment, $request->get('text'));
65
66         return view('comments.comment', ['comment' => $comment]);
67     }
68
69     /**
70      * Delete a comment from the system.
71      */
72     public function destroy(int $id)
73     {
74         $comment = $this->commentRepo->getById($id);
75         $this->checkOwnablePermission('comment-delete', $comment);
76
77         $this->commentRepo->delete($comment);
78
79         return response()->json(['message' => trans('entities.comment_deleted')]);
80     }
81 }