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