Passed
Branch master (249862)
by Adam
07:51
created

PmController   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 249
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 249
rs 10
c 0
b 0
f 0
wmc 20

11 Methods

Rating   Name   Duplication   Size   Complexity  
A submit() 0 6 1
A delete() 0 14 2
B save() 0 38 2
A trash() 0 8 1
A preview() 0 3 1
A index() 0 12 2
A ajax() 0 10 2
A getParser() 0 3 1
B show() 0 34 6
A paste() 0 21 1
A __construct() 0 12 1
1
<?php
2
3
namespace Coyote\Http\Controllers\User;
4
5
use Coyote\Events\PmWasSent;
6
use Coyote\Http\Factories\MediaFactory;
7
use Coyote\Repositories\Contracts\NotificationRepositoryInterface as NotificationRepository;
8
use Coyote\Repositories\Contracts\PmRepositoryInterface as PmRepository;
9
use Coyote\Repositories\Contracts\UserRepositoryInterface as UserRepository;
10
use Illuminate\Validation\Validator;
11
use Illuminate\Http\Request;
12
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
13
14
/**
15
 * Class PmController
16
 * @package Coyote\Http\Controllers\User
17
 */
18
class PmController extends BaseController
19
{
20
    use HomeTrait, MediaFactory;
21
22
    /**
23
     * @var UserRepository
24
     */
25
    private $user;
26
27
    /**
28
     * @var NotificationRepository
29
     */
30
    private $notification;
31
32
    /**
33
     * @var PmRepository
34
     */
35
    private $pm;
36
37
    /**
38
     * @param UserRepository $user
39
     * @param NotificationRepository $notification
40
     * @param PmRepository $pm
41
     */
42
    public function __construct(UserRepository $user, NotificationRepository $notification, PmRepository $pm)
43
    {
44
        parent::__construct();
45
46
        $this->user = $user;
47
        $this->notification = $notification;
48
        $this->pm = $pm;
49
50
        $this->middleware(function (Request $request, $next) {
51
            $request->attributes->set('preview_url', route('user.pm.preview'));
52
53
            return $next($request);
54
        });
55
    }
56
57
    /**
58
     * @return \Illuminate\View\View
59
     */
60
    public function index()
61
    {
62
        $this->breadcrumb->push('Wiadomości prywatne', route('user.pm'));
63
64
        $pm = $this->pm->paginate($this->userId);
65
        $parser = $this->getParser();
66
67
        foreach ($pm as &$row) {
68
            $row->text = $parser->parse($row->text);
69
        }
70
71
        return $this->view('user.pm.home')->with(compact('pm'));
72
    }
73
74
    /**
75
     * Show conversation
76
     *
77
     * @param int $id
78
     * @param Request $request
79
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
80
     */
81
    public function show($id, Request $request)
82
    {
83
        $this->breadcrumb->push('Wiadomości prywatne', route('user.pm'));
84
85
        $pm = $this->pm->findOrFail($id, ['user_id', 'author_id', 'root_id', 'id']);
86
        $this->authorize('show', $pm);
87
88
        $talk = $this->pm->talk($this->userId, $pm->author_id, 10, (int) $request->query('offset', 0));
89
        $parser = $this->getParser();
90
91
        foreach ($talk as &$row) {
92
            $row['text'] = $parser->parse($row['text']);
93
94
            // we have to mark this message as read
95
            if (!$row['read_at'] && $row['folder'] == \Coyote\Pm::INBOX) {
96
                // database trigger will decrease pm counter in "users" table.
97
                $this->pm->markAsRead($row['text_id']);
98
                $this->auth->pm_unread--;
99
100
                // IF we have unread alert that is connected with that message... then we also have to mark it as read
101
                if ($this->auth->notifications_unread) {
102
                    $this->notification->markAsReadByUrl($this->userId, route('user.pm.show', [$row['id']], false));
103
                }
104
            }
105
        }
106
107
        if ($request->ajax()) {
108
            return view('user.pm.infinite')->with('talk', $talk);
109
        }
110
111
        $this->request->attributes->set('infinity_url', route('user.pm.show', [$id]));
112
113
        $recipient = $this->user->find($pm->author_id, ['name']);
114
        return $this->view('user.pm.show')->with(compact('pm', 'talk', 'recipient'));
115
    }
116
117
    /**
118
     * Get last 10 conversations
119
     *
120
     * @return \Illuminate\View\View
121
     */
122
    public function ajax()
123
    {
124
        $parser = $this->getParser();
125
126
        $pm = $this->pm->takeForUser($this->userId);
127
        foreach ($pm as &$row) {
128
            $row->text = $parser->parse($row->text);
129
        }
130
131
        return view('user.pm.ajax')->with(compact('pm'));
132
    }
133
134
    /**
135
     * @return \Illuminate\View\View
136
     */
137
    public function submit()
138
    {
139
        $this->breadcrumb->push('Wiadomości prywatne', route('user.pm'));
140
        $this->breadcrumb->push('Napisz wiadomość', route('user.pm.submit'));
141
142
        return $this->view('user.pm.submit');
143
    }
144
145
    /**
146
     * @param Request $request
147
     * @return \Symfony\Component\HttpFoundation\Response
148
     */
149
    public function preview(Request $request)
150
    {
151
        return response($this->getParser()->parse($request->get('text')));
0 ignored issues
show
Bug Best Practice introduced by
The expression return response($this->g...$request->get('text'))) also could return the type Illuminate\Contracts\Routing\ResponseFactory which is incompatible with the documented return type Symfony\Component\HttpFoundation\Response.
Loading history...
152
    }
153
154
    /**
155
     * @param Request $request
156
     * @return \Illuminate\Http\RedirectResponse
157
     */
158
    public function save(Request $request)
159
    {
160
        $validator = $this->getValidationFactory()->make($request->all(), [
161
            'recipient'          => 'required|user_exist',
162
            'text'               => 'required',
163
            'root_id'            => 'sometimes|exists:pm'
164
        ]);
165
166
        $validator->after(function (Validator $validator) use ($request) {
167
            if (mb_strtolower($request->get('recipient')) === mb_strtolower($this->auth->name)) {
168
                $validator->errors()->add('recipient', trans('validation.custom.recipient.different'));
169
            }
170
        });
171
172
        $this->validateWith($validator);
173
174
        return $this->transaction(function () use ($request) {
175
            $recipient = $this->user->findByName($request->get('recipient'));
176
177
            $pm = $this->pm->submit($this->auth, $request->all() + ['author_id' => $recipient->id]);
178
179
            $excerpt = excerpt($text = $this->getParser()->parse($request->get('text')));
180
181
            // we need to send notification to recipient
182
            app('notification.pm')->with([
183
                'user_id'     => $pm->author_id,
184
                'sender_id'   => $this->auth->id,
185
                'sender_name' => $this->auth->name,
186
                'subject'     => $excerpt,
187
                'text'        => $text,
188
                'url'         => route('user.pm.show', [$pm->id - 1], false)
189
            ])->notify();
190
191
            // broadcast event: we can use it to show message in real time
192
            event(new PmWasSent($pm->author_id, $this->auth->id, $this->auth->name, $excerpt));
193
194
            // redirect to sent message...
195
            return redirect()->route('user.pm.show', [$pm->id])->with('success', 'Wiadomość została wysłana');
196
        });
197
    }
198
199
    /**
200
     * @param int $id
201
     * @return \Illuminate\Http\RedirectResponse
202
     */
203
    public function delete($id)
204
    {
205
        $pm = $this->pm->findOrFail($id, ['id', 'user_id', 'author_id']);
206
        $this->authorize('show', $pm);
207
208
        return $this->transaction(function () use ($pm) {
209
            $pm->delete();
210
211
            $redirect = redirect();
212
            $to = $this->pm->findWhere(['author_id' => $pm->author_id, 'user_id' => $this->userId], ['id']);
213
214
            $redirect = $to->count() ? $redirect->route('user.pm.show', [$to->first()->id]) : $redirect->route('user.pm');
215
216
            return $redirect->with('success', 'Wiadomość poprawnie usunięta');
217
        });
218
    }
219
220
    /**
221
     * @param int $authorId
222
     * @return \Illuminate\Http\RedirectResponse
223
     */
224
    public function trash($authorId)
225
    {
226
        $pm = $this->pm->findWhere(['user_id' => $this->userId, 'author_id' => $authorId]);
227
        abort_if($pm->count() == 0, 404);
228
229
        $this->pm->trash($this->userId, $authorId);
230
231
        return redirect()->route('user.pm')->with('success', 'Wątek został bezpowrotnie usunięty.');
232
    }
233
234
    /**
235
     * @return \Illuminate\Http\JsonResponse
236
     */
237
    public function paste()
238
    {
239
        $input = file_get_contents("php://input");
240
241
        $validator = $this->getValidationFactory()->make(
242
            ['length' => strlen($input)],
243
            ['length' => 'max:' . config('filesystems.upload_max_size') * 1024 * 1024]
244
        );
245
246
        $this->validateWith($validator);
247
248
        $media = $this->getMediaFactory()->make('screenshot')->put(file_get_contents('data://' . substr($input, 7)));
249
        $mime = MimeTypeGuesser::getInstance();
250
251
        return response()->json([
252
            'size'      => $media->size(),
253
            'suffix'    => 'png',
254
            'name'      => $media->getName(),
255
            'file'      => $media->getFilename(),
256
            'mime'      => $mime->guess($media->path()),
257
            'url'       => (string) $media->url()
258
        ]);
259
    }
260
261
    /**
262
     * @return \Coyote\Services\Parser\Factories\PmFactory
263
     */
264
    private function getParser()
265
    {
266
        return app('parser.pm');
267
    }
268
}
269