]> BookStack Code Mirror - bookstack/blob - app/Repos/CommentRepo.php
Update entities.php
[bookstack] / app / Repos / CommentRepo.php
1 <?php namespace BookStack\Repos;
2
3 use BookStack\Comment;
4 use BookStack\Entity;
5
6 /**
7  * Class CommentRepo
8  * @package BookStack\Repos
9  */
10 class CommentRepo {
11
12     /**
13      * @var Comment $comment
14      */
15     protected $comment;
16
17     /**
18      * CommentRepo constructor.
19      * @param Comment $comment
20      */
21     public function __construct(Comment $comment)
22     {
23         $this->comment = $comment;
24     }
25
26     /**
27      * Get a comment by ID.
28      * @param $id
29      * @return Comment|\Illuminate\Database\Eloquent\Model
30      */
31     public function getById($id)
32     {
33         return $this->comment->newQuery()->findOrFail($id);
34     }
35
36     /**
37      * Create a new comment on an entity.
38      * @param Entity $entity
39      * @param array $data
40      * @return Comment
41      */
42     public function create (Entity $entity, $data = [])
43     {
44         $userId = user()->id;
45         $comment = $this->comment->newInstance($data);
46         $comment->created_by = $userId;
47         $comment->updated_by = $userId;
48         $comment->local_id = $this->getNextLocalId($entity);
49         $entity->comments()->save($comment);
50         return $comment;
51     }
52
53     /**
54      * Update an existing comment.
55      * @param Comment $comment
56      * @param array $input
57      * @return mixed
58      */
59     public function update($comment, $input)
60     {
61         $comment->updated_by = user()->id;
62         $comment->update($input);
63         return $comment;
64     }
65
66     /**
67      * Delete a comment from the system.
68      * @param Comment $comment
69      * @return mixed
70      */
71     public function delete($comment)
72     {
73         return $comment->delete();
74     }
75
76     /**
77      * Get the next local ID relative to the linked entity.
78      * @param Entity $entity
79      * @return int
80      */
81     protected function getNextLocalId(Entity $entity)
82     {
83         $comments = $entity->comments(false)->orderBy('local_id', 'desc')->first();
84         if ($comments === null) return 1;
85         return $comments->local_id + 1;
86     }
87 }