]> BookStack Code Mirror - bookstack/blob - app/Actions/CommentRepo.php
Fixed occurances of altered titles in search results
[bookstack] / app / Actions / CommentRepo.php
1 <?php
2
3 namespace BookStack\Actions;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Facades\Activity as ActivityService;
7 use League\CommonMark\CommonMarkConverter;
8
9 /**
10  * Class CommentRepo.
11  */
12 class CommentRepo
13 {
14     /**
15      * @var Comment
16      */
17     protected $comment;
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
50         return $comment;
51     }
52
53     /**
54      * Update an existing comment.
55      */
56     public function update(Comment $comment, string $text): Comment
57     {
58         $comment->updated_by = user()->id;
59         $comment->text = $text;
60         $comment->html = $this->commentToHtml($text);
61         $comment->save();
62
63         return $comment;
64     }
65
66     /**
67      * Delete a comment from the system.
68      */
69     public function delete(Comment $comment): void
70     {
71         $comment->delete();
72     }
73
74     /**
75      * Convert the given comment Markdown to HTML.
76      */
77     public function commentToHtml(string $commentText): string
78     {
79         $converter = new CommonMarkConverter([
80             'html_input'         => 'strip',
81             'max_nesting_level'  => 10,
82             'allow_unsafe_links' => false,
83         ]);
84
85         return $converter->convertToHtml($commentText);
86     }
87
88     /**
89      * Get the next local ID relative to the linked entity.
90      */
91     protected function getNextLocalId(Entity $entity): int
92     {
93         /** @var Comment $comment */
94         $comment = $entity->comments(false)->orderBy('local_id', 'desc')->first();
95
96         return ($comment->local_id ?? 0) + 1;
97     }
98 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.