Completed
Push — master ( 005576...ac2f13 )
by Emmanuel
01:10
created

TicketController::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
4
namespace RexlManu\LaravelTickets\Controllers;
5
6
7
use Illuminate\Database\Eloquent\Relations\Relation;
8
use Illuminate\Http\JsonResponse;
9
use Illuminate\Http\RedirectResponse;
10
use Illuminate\Http\Request;
11
use Illuminate\Routing\Controller;
12
use Illuminate\Validation\Rule;
13
use Illuminate\View\View;
14
use RexlManu\LaravelTickets\Events\TicketCloseEvent;
15
use RexlManu\LaravelTickets\Events\TicketMessageEvent;
16
use RexlManu\LaravelTickets\Events\TicketOpenEvent;
17
use RexlManu\LaravelTickets\Models\Ticket;
18
use RexlManu\LaravelTickets\Models\TicketMessage;
19
use RexlManu\LaravelTickets\Models\TicketReference;
20
use RexlManu\LaravelTickets\Models\TicketUpload;
21
use RexlManu\LaravelTickets\Rule\TicketReferenceRule;
22
use Symfony\Component\HttpFoundation\BinaryFileResponse;
23
24
/**
25
 * Class TicketController
26
 *
27
 * The main logic of the ticket system. All actions are performed here.
28
 *
29
 * If the accept header is json, the response will be a json response
30
 *
31
 * @package RexlManu\LaravelTickets\Controllers
32
 */
33
class TicketController extends Controller
34
{
35
36
    /**
37
     * @link TicketController constructor
38
     */
39
    public function __construct()
40
    {
41
        if (! config('laravel-tickets.permission')) {
42
            return;
43
        }
44
45
        $this->middleware(config('laravel-tickets.permissions.list-ticket'))->only('index');
46
        $this->middleware(config('laravel-tickets.permissions.create-ticket'))->only('store', 'create');
47
        $this->middleware(config('laravel-tickets.permissions.close-ticket'))->only('close');
48
        $this->middleware(config('laravel-tickets.permissions.show-ticket'))->only('show');
49
        $this->middleware(config('laravel-tickets.permissions.message-ticket'))->only('message');
50
        $this->middleware(config('laravel-tickets.permissions.download-ticket'))->only('download');
51
    }
52
53
    /**
54
     * Show every @return View|JsonResponse
55
     *
56
     * @link Ticket that the user has created
57
     *
58
     * If the accept header is json, the response will be a json response
59
     *
60
     */
61
    public function index()
62
    {
63
        if (\request()->user()->can(config('laravel-tickets.permissions.all-ticket'))) {
64
            $tickets = Ticket::query();
65
        } else {
66
            $tickets = request()->user()->tickets();
67
        }
68
        $tickets = $tickets->orderBy('id', 'desc')->paginate(10);
69
70
        return request()->wantsJson() ?
71
            response()->json(compact('tickets')) :
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...
72
            view('laravel-tickets::tickets.index',
73
                compact('tickets')
74
            );
75
    }
76
77
    /**
78
     * Show the create form
79
     *
80
     * @return View
81
     */
82
    public function create()
83
    {
84
        return view('laravel-tickets::tickets.create');
85
    }
86
87
    /**
88
     * Creates a @param Request $request the request
89
     *
90
     * @return View|JsonResponse|RedirectResponse
91
     * @link Ticket
92
     *
93
     */
94
    public function store(Request $request)
95
    {
96
        $rules = [
97
            'subject' => [ 'required', 'string', 'max:191' ],
98
            'priority' => [ 'required', Rule::in(config('laravel-tickets.priorities')) ],
99
            'message' => [ 'required', 'string' ],
100
            'files' => [ 'max:' . config('laravel-tickets.file.max-files') ],
101
            'files.*' => [
102
                'sometimes',
103
                'file',
104
                'max:' . config('laravel-tickets.file.size-limit'),
105
                'mimes:' . config('laravel-tickets.file.memes'),
106
            ],
107
        ];
108
        if (config('laravel-tickets.category')) {
109
            $rules[ 'category_id' ] = [
110
                'required',
111
                Rule::exists(config('laravel-tickets.database.ticket-categories-table'), 'id'),
112
            ];
113
        }
114
        if (config('laravel-tickets.references')) {
115
            $rules[ 'reference' ] = [
116
                config('laravel-tickets.references-nullable') ? 'nullable' : 'required',
117
                new TicketReferenceRule(),
118
            ];
119
        }
120
        $data = $request->validate($rules);
0 ignored issues
show
Bug introduced by
The call to validate() misses a required argument $...$params.

This check looks for function calls that miss required arguments.

Loading history...
121
        if ($request->user()->tickets()->where('state', '!=', 'CLOSED')->count() >= config('laravel-tickets.maximal-open-tickets')) {
122
            $message = trans('You have reached the limit of open tickets');
123
            return \request()->wantsJson() ?
124
                response()->json(compact('message')) :
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...
125
                back()->with(
126
                    'message',
127
                    $message
128
                );
129
        }
130
        $ticket = $request->user()->tickets()->create(
131
            $data
132
        );
133
134
        if (array_key_exists('reference', $data)) {
135
            $reference = explode(',', $data[ 'reference' ]);
136
            $ticketReference = new TicketReference();
137
            $ticketReference->ticket()->associate($ticket);
138
            $ticketReference->referenceable()->associate(
139
                resolve($reference[ 0 ])->find($reference[ 1 ])
140
            );
141
            $ticketReference->save();
142
        }
143
144
        $ticketMessage = new TicketMessage($data);
145
        $ticketMessage->user()->associate($request->user());
146
        $ticketMessage->ticket()->associate($ticket);
147
        $ticketMessage->save();
148
149
        $this->handleFiles($data[ 'files' ] ?? [], $ticketMessage);
150
151
        event(new TicketOpenEvent($ticket));
152
153
        $message = trans('The ticket was successfully created');
154
        return $request->wantsJson() ?
155
            response()->json(compact('message', 'ticket', 'ticketMessage')) :
156
            redirect(route(
157
                'laravel-tickets.tickets.show',
158
                compact('ticket')
159
            ))->with(
160
                'message',
161
                $message
162
            );
163
    }
164
165
    /**
166
     * Show detailed informations about the @param Ticket $ticket
167
     *
168
     * @return View|JsonResponse|RedirectResponse|void
169
     * @link Ticket and the informations
170
     *
171
     */
172
    public function show(Ticket $ticket)
173
    {
174 View Code Duplication
        if (! $ticket->user()->get()->contains(\request()->user()) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
175
            ! request()->user()->can(config('laravel-tickets.permissions.all-ticket'))) {
176
            return abort(403);
177
        }
178
179
        $messages = $ticket->messages()->with('uploads')->orderBy('created_at', 'desc')->paginate(4);
180
181
        return \request()->wantsJson() ?
182
            response()->json(compact(
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...
183
                'ticket',
184
                'messages'
185
            )) :
186
            view('laravel-tickets::tickets.show',
187
                compact(
188
                    'ticket',
189
                    'messages'
190
                )
191
            );
192
    }
193
194
    /**
195
     * Send a message to the @param Request $request
196
     *
197
     * @param Ticket $ticket
198
     *
199
     * @return JsonResponse|RedirectResponse|void
200
     * @link Ticket
201
     *
202
     */
203
    public function message(Request $request, Ticket $ticket)
204
    {
205 View Code Duplication
        if (! $ticket->user()->get()->contains(\request()->user()) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
            ! request()->user()->can(config('laravel-tickets.permissions.all-ticket'))) {
207
            return abort(403);
208
        }
209
210 View Code Duplication
        if (! config('laravel-tickets.open-ticket-with-answer') && $ticket->state === 'CLOSED') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
211
            $message = trans('You cannot reply to a closed ticket');
212
            return \request()->wantsJson() ?
213
                response()->json(compact('message')) :
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...
214
                back()->with(
215
                    'message',
216
                    $message
217
                );
218
        }
219
220
        $data = $request->validate([
0 ignored issues
show
Bug introduced by
The call to validate() misses a required argument $...$params.

This check looks for function calls that miss required arguments.

Loading history...
221
            'message' => [ 'required', 'string' ],
222
            'files' => [ 'max:' . config('laravel-tickets.file.max-files') ],
223
            'files.*' => [
224
                'sometimes',
225
                'file',
226
                'max:' . config('laravel-tickets.file.size-limit'),
227
                'mimes:' . config('laravel-tickets.file.memes'),
228
            ]
229
        ]);
230
231
        $ticketMessage = new TicketMessage($data);
232
        $ticketMessage->user()->associate($request->user());
233
        $ticketMessage->ticket()->associate($ticket);
234
        $ticketMessage->save();
235
236
        $this->handleFiles($data[ 'files' ] ?? [], $ticketMessage);
237
238
        $ticket->update([ 'state' => 'OPEN' ]);
239
240
        event(new TicketMessageEvent($ticket, $ticketMessage));
241
242
        $message = trans('Your answer was sent successfully');
243
        return $request->wantsJson() ?
244
            response()->json(compact('message')) :
245
            back()->with(
246
                'message',
247
                $message
248
            );
249
    }
250
251
    /**
252
     * Declare the @param Ticket $ticket
253
     *
254
     * @return JsonResponse|RedirectResponse|void
255
     * @link Ticket as closed.
256
     *
257
     */
258
    public function close(Ticket $ticket)
259
    {
260 View Code Duplication
        if (! $ticket->user()->get()->contains(\request()->user()) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
261
            ! request()->user()->can(config('laravel-tickets.permissions.all-ticket'))) {
262
            return abort(403);
263
        }
264 View Code Duplication
        if ($ticket->state === 'CLOSED') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
265
            $message = trans('The ticket is already closed');
266
            return \request()->wantsJson() ?
267
                response()->json(compact('message')) :
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...
268
                back()->with(
269
                    'message',
270
                    $message
271
                );
272
        }
273
        $ticket->update([ 'state' => 'CLOSED' ]);
274
        event(new TicketCloseEvent($ticket));
275
276
        $message = trans('The ticket was successfully closed');
277
        return \request()->wantsJson() ?
278
            response()->json(compact('message')) :
279
            back()->with(
280
                'message',
281
                $message
282
            );
283
    }
284
285
    /**
286
     * Downloads the file from @param Ticket $ticket
287
     *
288
     * @param TicketUpload $ticketUpload
289
     *
290
     * @return BinaryFileResponse
291
     * @link TicketUpload
292
     *
293
     */
294
    public function download(Ticket $ticket, TicketUpload $ticketUpload)
295
    {
296 View Code Duplication
        if (! $ticket->user()->get()->contains(\request()->user()) &&
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
297
            ! request()->user()->can(config('laravel-tickets.permissions.all-ticket'))) {
298
            return abort(403);
299
        }
300
301
        $storagePath = storage_path('app/' . $ticketUpload->path);
302
        if (config('laravel-tickets.pdf-force-preview') && pathinfo($ticketUpload->path, PATHINFO_EXTENSION) === 'pdf') {
303
            return response()->file($storagePath);
0 ignored issues
show
Bug introduced by
The method file 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...
304
        }
305
306
        return response()->download($storagePath);
0 ignored issues
show
Bug introduced by
The method download 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...
307
    }
308
309
    /**
310
     * Handles the uploaded files for the @param $files array uploaded files
311
     *
312
     * @param TicketMessage $ticketMessage
313
     *
314
     * @link TicketMessage
315
     *
316
     */
317
    private function handleFiles($files, TicketMessage $ticketMessage)
318
    {
319
        if (! config('laravel-tickets.files') || $files === null) {
320
            return;
321
        }
322
        foreach ($files as $file) {
323
            $ticketMessage->uploads()->create([
324
                'path' => $file->storeAs(
325
                    config('laravel-tickets.file.path') . $ticketMessage->id,
326
                    $file->getClientOriginalName(),
327
                    config('laravel-tickets.file.driver')
328
                )
329
            ]);
330
        }
331
    }
332
333
}
334