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