]> BookStack Code Mirror - bookstack/blob - app/Activity/CommentRepo.php
Comments: Added back-end content reference handling
[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 BookStack\Util\HtmlDescriptionFilter;
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 $html, ?int $parent_id, string $content_ref): Comment
24     {
25         $userId = user()->id;
26         $comment = new Comment();
27
28         $comment->html = HtmlDescriptionFilter::filterFromString($html);
29         $comment->created_by = $userId;
30         $comment->updated_by = $userId;
31         $comment->local_id = $this->getNextLocalId($entity);
32         $comment->parent_id = $parent_id;
33         $comment->content_ref = preg_match('/^bkmrk-(.*?):\d+:(\d*-\d*)?$/', $content_ref) === 1 ? $content_ref : '';
34
35         $entity->comments()->save($comment);
36         ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
37         ActivityService::add(ActivityType::COMMENTED_ON, $entity);
38
39         return $comment;
40     }
41
42     /**
43      * Update an existing comment.
44      */
45     public function update(Comment $comment, string $html): Comment
46     {
47         $comment->updated_by = user()->id;
48         $comment->html = HtmlDescriptionFilter::filterFromString($html);
49         $comment->save();
50
51         ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
52
53         return $comment;
54     }
55
56     /**
57      * Delete a comment from the system.
58      */
59     public function delete(Comment $comment): void
60     {
61         $comment->delete();
62
63         ActivityService::add(ActivityType::COMMENT_DELETE, $comment);
64     }
65
66     /**
67      * Get the next local ID relative to the linked entity.
68      */
69     protected function getNextLocalId(Entity $entity): int
70     {
71         $currentMaxId = $entity->comments()->max('local_id');
72
73         return $currentMaxId + 1;
74     }
75 }