3 namespace BookStack\Activity;
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Facades\Activity as ActivityService;
8 use League\CommonMark\CommonMarkConverter;
20 public function __construct(Comment $comment)
22 $this->comment = $comment;
26 * Get a comment by ID.
28 public function getById(int $id): Comment
30 return $this->comment->newQuery()->findOrFail($id);
34 * Create a new comment on an entity.
36 public function create(Entity $entity, string $text, ?int $parent_id): Comment
39 $comment = $this->comment->newInstance();
41 $comment->text = $text;
42 $comment->html = $this->commentToHtml($text);
43 $comment->created_by = $userId;
44 $comment->updated_by = $userId;
45 $comment->local_id = $this->getNextLocalId($entity);
46 $comment->parent_id = $parent_id;
48 $entity->comments()->save($comment);
49 ActivityService::add(ActivityType::COMMENTED_ON, $entity);
55 * Update an existing comment.
57 public function update(Comment $comment, string $text): Comment
59 $comment->updated_by = user()->id;
60 $comment->text = $text;
61 $comment->html = $this->commentToHtml($text);
68 * Delete a comment from the system.
70 public function delete(Comment $comment): void
76 * Convert the given comment Markdown to HTML.
78 public function commentToHtml(string $commentText): string
80 $converter = new CommonMarkConverter([
81 'html_input' => 'strip',
82 'max_nesting_level' => 10,
83 'allow_unsafe_links' => false,
86 return $converter->convertToHtml($commentText);
90 * Get the next local ID relative to the linked entity.
92 protected function getNextLocalId(Entity $entity): int
94 /** @var Comment $comment */
95 $comment = $entity->comments(false)->orderBy('local_id', 'desc')->first();
97 return ($comment->local_id ?? 0) + 1;