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