]> BookStack Code Mirror - bookstack/blob - app/Actions/CommentRepo.php
Fixed canonical redirects on non-root url app instances
[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         return $comment;
48     }
49
50     /**
51      * Update an existing comment.
52      */
53     public function update(Comment $comment, string $text): Comment
54     {
55         $comment->updated_by = user()->id;
56         $comment->text = $text;
57         $comment->html = $this->commentToHtml($text);
58         $comment->save();
59         return $comment;
60     }
61
62     /**
63      * Delete a comment from the system.
64      */
65     public function delete(Comment $comment)
66     {
67         $comment->delete();
68     }
69
70     /**
71      * Convert the given comment markdown text to HTML.
72      */
73     public function commentToHtml(string $commentText): string
74     {
75         $converter = new CommonMarkConverter([
76             'html_input' => 'strip',
77             'max_nesting_level' => 10,
78             'allow_unsafe_links' => false,
79         ]);
80
81         return $converter->convertToHtml($commentText);
82     }
83
84     /**
85      * Get the next local ID relative to the linked entity.
86      */
87     protected function getNextLocalId(Entity $entity): int
88     {
89         $comments = $entity->comments(false)->orderBy('local_id', 'desc')->first();
90         return ($comments->local_id ?? 0) + 1;
91     }
92 }