]> BookStack Code Mirror - bookstack/blob - app/Activity/CommentRepo.php
Comments: Updated reply-to and general styling
[bookstack] / app / Activity / CommentRepo.php
1 <?php
2
3 namespace BookStack\Activity;
4
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Facades\Activity as ActivityService;
8 use League\CommonMark\CommonMarkConverter;
9
10 class CommentRepo
11 {
12     /**
13      * Get a comment by ID.
14      */
15     public function getById(int $id): Comment
16     {
17         return Comment::query()->findOrFail($id);
18     }
19
20     /**
21      * Create a new comment on an entity.
22      */
23     public function create(Entity $entity, string $text, ?int $parent_id): Comment
24     {
25         $userId = user()->id;
26         $comment = new Comment();
27
28         $comment->text = $text;
29         $comment->html = $this->commentToHtml($text);
30         $comment->created_by = $userId;
31         $comment->updated_by = $userId;
32         $comment->local_id = $this->getNextLocalId($entity);
33         $comment->parent_id = $parent_id;
34
35         $entity->comments()->save($comment);
36         ActivityService::add(ActivityType::COMMENTED_ON, $entity);
37
38         return $comment;
39     }
40
41     /**
42      * Update an existing comment.
43      */
44     public function update(Comment $comment, string $text): Comment
45     {
46         $comment->updated_by = user()->id;
47         $comment->text = $text;
48         $comment->html = $this->commentToHtml($text);
49         $comment->save();
50
51         return $comment;
52     }
53
54     /**
55      * Delete a comment from the system.
56      */
57     public function delete(Comment $comment): void
58     {
59         $comment->delete();
60     }
61
62     /**
63      * Convert the given comment Markdown to HTML.
64      */
65     public function commentToHtml(string $commentText): string
66     {
67         $converter = new CommonMarkConverter([
68             'html_input'         => 'strip',
69             'max_nesting_level'  => 10,
70             'allow_unsafe_links' => false,
71         ]);
72
73         return $converter->convert($commentText);
74     }
75
76     /**
77      * Get the next local ID relative to the linked entity.
78      */
79     protected function getNextLocalId(Entity $entity): int
80     {
81         $currentMaxId = $entity->comments()->max('local_id');
82
83         return $currentMaxId + 1;
84     }
85 }