]> BookStack Code Mirror - bookstack/blob - app/Repos/CommentRepo.php
7d0c4ebd7b419ad11035cb680dfa03995dcc1f13
[bookstack] / app / Repos / CommentRepo.php
1 <?php namespace BookStack\Repos;
2
3 use BookStack\Comment;
4 use BookStack\Page;
5
6 /**
7  * Class TagRepo
8  * @package BookStack\Repos
9  */
10 class CommentRepo {
11     /**
12      *
13      * @var Comment $comment
14      */
15     protected $comment;
16
17     public function __construct(Comment $comment)
18     {
19         $this->comment = $comment;
20     }
21
22     public function create (Page $page, $data = []) {
23         $userId = user()->id;
24         $comment = $this->comment->newInstance();
25         $comment->fill($data);
26         // new comment
27         $comment->page_id = $page->id;
28         $comment->created_by = $userId;
29         $comment->updated_at = null;
30         $comment->save();
31         return $comment;
32     }
33
34     public function update($comment, $input) {
35         $userId = user()->id;
36         $comment->updated_by = $userId;
37         $comment->fill($input);
38         $comment->save();
39         return $comment;
40     }
41
42     public function getPageComments($pageId) {
43         $comments = $this->comment->getAllPageComments($pageId);
44         $index = [];
45         $totalComments = count($comments);
46         // normalizing the response.
47         foreach($comments as &$comment) {
48             $comment = $this->normalizeComment($comment);
49             $parentId = $comment->parent_id;
50             if (empty($parentId)) {
51                 $index[$comment->id] = $comment;
52                 continue;
53             }
54
55             if (empty($index[$parentId])) {
56                 // weird condition should not happen.
57                 continue;
58             }
59             if (empty($index[$parentId]->sub_comments)) {
60                 $index[$parentId]->sub_comments = [];
61             }
62             array_push($index[$parentId]->sub_comments, $comment);
63             $index[$comment->id] = $comment;
64         }
65         return [
66             'comments' => $comments,
67             'total' => $totalComments
68         ];
69     }
70
71     public function getCommentById($commentId) {
72         return $this->normalizeComment($this->comment->getCommentById($commentId));
73     }
74
75     private function normalizeComment($comment) {
76         if (empty($comment)) {
77             return;
78         }
79         $comment->createdBy->avatar_url = $comment->createdBy->getAvatar(50);
80         $comment->createdBy->profile_url = $comment->createdBy->getProfileUrl();
81         if (!empty($comment->updatedBy)) {
82             $comment->updatedBy->profile_url = $comment->updatedBy->getProfileUrl();
83         }
84         return $comment;
85     }
86 }