Completed
Branch master (8e0976)
by Adam
04:13
created

PmController::paste()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
1
<?php
2
3
namespace Coyote\Http\Controllers\User;
4
5
use Coyote\Http\Factories\MediaFactory;
6
use Coyote\Notifications\PmCreatedNotification;
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) {
0 ignored issues
show
Bug introduced by
The expression $pm of type object<Illuminate\Contra...n\LengthAwarePaginator> is not traversable.
Loading history...
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');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->view('user.pm.submit'); of type Illuminate\Contracts\Vie...ry|Illuminate\View\View adds the type Illuminate\Contracts\View\Factory to the return on line 142 which is incompatible with the return type documented by Coyote\Http\Controllers\User\PmController::submit of type Illuminate\View\View.
Loading history...
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')));
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
        $recipient = $this->user->findByName($request->get('recipient'));
174
175
        $pm = $this->transaction(function () use ($request, $recipient) {
176
            return $this->pm->submit($this->auth, $request->all() + ['author_id' => $recipient->id]);
177
        });
178
179
        $recipient->notify(new PmCreatedNotification($pm));
180
181
        // redirect to sent message...
182
        return redirect()->route('user.pm.show', [$pm->id])->with('success', 'Wiadomość została wysłana');
183
    }
184
185
    /**
186
     * @param int $id
187
     * @return \Illuminate\Http\RedirectResponse
188
     */
189
    public function delete($id)
190
    {
191
        $pm = $this->pm->findOrFail($id, ['id', 'user_id', 'author_id']);
192
        $this->authorize('show', $pm);
193
194
        return $this->transaction(function () use ($pm) {
195
            $pm->delete();
196
197
            $redirect = redirect();
198
            $to = $this->pm->findWhere(['author_id' => $pm->author_id, 'user_id' => $this->userId], ['id']);
199
200
            $redirect = $to->count() ? $redirect->route('user.pm.show', [$to->first()->id]) : $redirect->route('user.pm');
201
202
            return $redirect->with('success', 'Wiadomość poprawnie usunięta');
203
        });
204
    }
205
206
    /**
207
     * @param int $authorId
208
     * @return \Illuminate\Http\RedirectResponse
209
     */
210
    public function trash($authorId)
211
    {
212
        $pm = $this->pm->findWhere(['user_id' => $this->userId, 'author_id' => $authorId]);
213
        abort_if($pm->count() == 0, 404);
214
215
        $this->pm->trash($this->userId, $authorId);
216
217
        return redirect()->route('user.pm')->with('success', 'Wątek został bezpowrotnie usunięty.');
218
    }
219
220
    /**
221
     * @return \Illuminate\Http\JsonResponse
222
     */
223
    public function paste()
224
    {
225
        $input = file_get_contents("php://input");
226
227
        $validator = $this->getValidationFactory()->make(
228
            ['length' => strlen($input)],
229
            ['length' => 'max:' . config('filesystems.upload_max_size') * 1024 * 1024]
230
        );
231
232
        $this->validateWith($validator);
233
234
        $media = $this->getMediaFactory()->make('screenshot')->put(file_get_contents('data://' . substr($input, 7)));
235
        $mime = MimeTypeGuesser::getInstance();
236
237
        return response()->json([
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
238
            'size'      => $media->size(),
239
            'suffix'    => 'png',
240
            'name'      => $media->getName(),
241
            'file'      => $media->getFilename(),
242
            'mime'      => $mime->guess($media->path()),
243
            'url'       => (string) $media->url()
244
        ]);
245
    }
246
247
    /**
248
     * @return \Coyote\Services\Parser\Factories\PmFactory
249
     */
250
    private function getParser()
251
    {
252
        return app('parser.pm');
253
    }
254
}
255