Comment::postReply()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 1
Metric Value
cc 3
eloc 20
c 3
b 2
f 1
nc 3
nop 0
dl 0
loc 33
rs 9.6
1
<?php
2
3
namespace Usamamuneerchaudhary\Commentify\Http\Livewire;
4
5
use Illuminate\Auth\Access\AuthorizationException;
6
use Illuminate\Contracts\View\Factory;
7
use Illuminate\Contracts\View\View;
8
use Illuminate\Foundation\Application;
9
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
10
use Illuminate\Support\Str;
11
use Livewire\Attributes\On;
12
use Livewire\Component;
13
use Usamamuneerchaudhary\Commentify\Events\CommentReported;
14
use Usamamuneerchaudhary\Commentify\Models\CommentReport;
15
use Usamamuneerchaudhary\Commentify\Models\User;
16
17
class Comment extends Component
18
{
19
    use AuthorizesRequests;
20
21
    public $comment;
22
23
    public $users = [];
24
25
    public $isReplying = false;
26
27
    public $hasReplies = false;
28
29
    public $showOptions = false;
30
31
    public $isEditing = false;
32
33
    public $isReporting = false;
34
35
    public $alreadyReported = false;
36
37
    public $reportState = [
38
        'reason' => '',
39
        'additional_details' => '',
40
    ];
41
42
    public $replyState = [
43
        'body' => '',
44
    ];
45
46
    public $editState = [
47
        'body' => '',
48
    ];
49
50
    protected $validationAttributes = [
51
        'replyState.body' => 'Reply',
52
        'editState.body' => 'Reply',
53
        'reportState.reason' => 'reason',
54
    ];
55
56
    public function updatedIsEditing($isEditing): void
57
    {
58
        if (! $isEditing) {
59
            return;
60
        }
61
        $this->editState = [
62
            'body' => $this->comment->body,
63
        ];
64
    }
65
66
    /**
67
     * @throws \Illuminate\Auth\Access\AuthorizationException
68
     */
69
    public function editComment(): void
70
    {
71
        $this->authorize('update', $this->comment);
72
        $this->validate([
73
            'editState.body' => 'required|min:2',
74
        ]);
75
        $this->comment->update($this->editState);
76
        $this->isEditing = false;
77
        $this->showOptions = false;
78
    }
79
80
    /**
81
     * @throws AuthorizationException
82
     */
83
    #[On('refresh')]
84
    public function deleteComment(): void
85
    {
86
        $this->authorize('destroy', $this->comment);
87
        $this->comment->delete();
88
        $this->showOptions = false;
89
        $this->dispatch('refresh');
90
    }
91
92
    /**
93
     * @return Factory|Application|View|\Illuminate\Contracts\Foundation\Application|null
94
     */
95
    public function showReportForm(): void
96
    {
97
        if ($this->comment->isReportedByCurrentUser()) {
98
            $this->alreadyReported = true;
99
            $this->isReporting = true;
100
        } else {
101
            $this->alreadyReported = false;
102
            $this->isReporting = true;
103
        }
104
        $this->showOptions = false;
105
    }
106
107
    public function render(): \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Contracts\View\View|\Illuminate\Contracts\Foundation\Application|null
108
    {
109
        return view('commentify::livewire.comment');
110
    }
111
112
    #[On('refresh')]
113
    public function postReply(): void
114
    {
115
        if (config('commentify.read_only')) {
116
            session()->flash('message', __('commentify::commentify.comments.read_only_message'));
117
            session()->flash('alertType', 'warning');
118
119
            return;
120
        }
121
122
        $this->authorize('create', \Usamamuneerchaudhary\Commentify\Models\Comment::class);
123
124
        if (! $this->comment->isParent()) {
125
            return;
126
        }
127
        $this->validate([
128
            'replyState.body' => 'required',
129
        ]);
130
        $reply = $this->comment->children()->make($this->replyState);
131
        $reply->user()->associate(auth()->user());
132
        $reply->commentable()->associate($this->comment->commentable);
133
134
        // Set approval status based on config
135
        $reply->is_approved = ! config('commentify.require_approval', false);
136
137
        $reply->save();
138
139
        $this->replyState = [
140
            'body' => '',
141
        ];
142
        $this->isReplying = false;
143
        $this->showOptions = false;
144
        $this->dispatch('refresh')->self();
145
    }
146
147
    public function selectUser($userName): void
148
    {
149
        if ($this->replyState['body']) {
150
            $this->replyState['body'] = preg_replace('/@(\w+)$/', '@'.str_replace(' ', '_', Str::lower($userName)).' ',
151
                $this->replyState['body']);
152
            //            $this->replyState['body'] =$userName;
153
            $this->users = [];
154
        } elseif ($this->editState['body']) {
155
            $this->editState['body'] = preg_replace('/@(\w+)$/', '@'.str_replace(' ', '_', Str::lower($userName)).' ',
156
                $this->editState['body']);
157
            $this->users = [];
158
        }
159
    }
160
161
    #[On('getUsers')]
162
    public function getUsers($searchTerm): void
163
    {
164
        if (! empty($searchTerm)) {
165
            $this->users = User::where('name', 'like', '%'.$searchTerm.'%')->take(5)->get();
166
        } else {
167
            $this->users = [];
168
        }
169
    }
170
171
    public function reportComment(): void
172
    {
173
        if (! config('commentify.enable_reporting', true)) {
174
            return;
175
        }
176
177
        // Check if user has already reported this comment
178
        if ($this->comment->isReportedByCurrentUser()) {
179
            session()->flash('message', __('commentify::commentify.comments.already_reported'));
180
            session()->flash('alertType', 'warning');
181
            $this->isReporting = false;
182
            $this->showOptions = false;
183
184
            return;
185
        }
186
187
        $reportReasons = config('commentify.report_reasons', ['spam', 'inappropriate', 'offensive', 'other']);
188
189
        $this->validate([
190
            'reportState.reason' => 'required|in:'.implode(',', $reportReasons),
191
            'reportState.additional_details' => 'nullable|max:500',
192
        ]);
193
194
        $reason = $this->reportState['reason'];
195
        if (! empty($this->reportState['additional_details'])) {
196
            $reason .= ': '.$this->reportState['additional_details'];
197
        }
198
199
        $report = CommentReport::create([
200
            'comment_id' => $this->comment->id,
201
            'user_id' => auth()->id(),
202
            'ip' => request()->ip(),
203
            'user_agent' => request()->userAgent(),
204
            'reason' => $reason,
205
            'status' => 'pending',
206
        ]);
207
208
        if (config('commentify.enable_notifications', false)) {
209
            event(new CommentReported($this->comment, $report));
0 ignored issues
show
Bug introduced by
It seems like $report can also be of type Illuminate\Database\Eloq...gHasThroughRelationship; however, parameter $report of Usamamuneerchaudhary\Com...Reported::__construct() does only seem to accept Usamamuneerchaudhary\Com...fy\Models\CommentReport, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

209
            event(new CommentReported($this->comment, /** @scrutinizer ignore-type */ $report));
Loading history...
210
        }
211
212
        $this->reportState = ['reason' => '', 'additional_details' => ''];
213
        $this->isReporting = false;
214
        $this->alreadyReported = false;
215
        $this->showOptions = false;
216
217
        session()->flash('message', __('commentify::commentify.comments.report_submitted'));
218
        session()->flash('alertType', 'success');
219
    }
220
221
    public function closeReportForm(): void
222
    {
223
        $this->isReporting = false;
224
        $this->alreadyReported = false;
225
    }
226
}
227