Completed
Push — master ( 8cbb7e...825638 )
by Arjay
01:15
created

DataTablesEditor::getUseFriendlyErrorMessage()   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
namespace Yajra\DataTables;
4
5
use Exception;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\JsonResponse;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Database\QueryException;
10
use Illuminate\Support\Facades\Storage;
11
use Illuminate\Database\Eloquent\SoftDeletes;
12
use Illuminate\Contracts\Validation\Validator;
13
use Illuminate\Validation\ValidationException;
14
use Illuminate\Foundation\Validation\ValidatesRequests;
15
16
abstract class DataTablesEditor
17
{
18
    use ValidatesRequests;
19
20
    /**
21
     * Allowed dataTables editor actions.
22
     *
23
     * @var array
24
     */
25
    protected $actions = [
26
        'create',
27
        'edit',
28
        'remove',
29
        'upload',
30
        'forceDelete',
31
        'restore',
32
    ];
33
34
    /**
35
     * @var \Illuminate\Database\Eloquent\Model
36
     */
37
    protected $model = null;
38
39
    /**
40
     * Indicates if all mass assignment is enabled on model.
41
     *
42
     * @var bool
43
     */
44
    protected $unguarded = false;
45
46
    /**
47
     * Upload directory relative to storage path.
48
     *
49
     * @var string
50
     */
51
    protected $uploadDir = 'editor';
52
53
    /**
54
     * Flag to force delete a model.
55
     *
56
     * @var bool
57
     */
58
    protected $forceDeleting = false;
59
60
    /**
61
     * Flag to restore a model from deleted state.
62
     *
63
     * @var bool
64
     */
65
    protected $restoring = false;
66
67
    /**
68
     * Filesystem disk config to use for upload.
69
     *
70
     * @var string
71
     */
72
    protected $disk = 'public';
73
74
    /**
75
     * Current request data that is being processed.
76
     *
77
     * @var array
78
     */
79
    protected $currentData = [];
80
81
    /**
82
     * Process dataTables editor action request.
83
     *
84
     * @param Request $request
85
     * @return JsonResponse|mixed
86
     * @throws DataTablesEditorException
87
     */
88
    public function process(Request $request)
89
    {
90
        $action = $request->get('action');
91
92
        if (! in_array($action, $this->actions)) {
93
            throw new DataTablesEditorException('Requested action not supported!');
94
        }
95
96
        try {
97
            return $this->{$action}($request);
98
        } catch (Exception $exception) {
99
            $error = config('app.debug')
100
                ? '<strong>Server Error:</strong> ' . $exception->getMessage()
101
                : $this->getUseFriendlyErrorMessage();
102
103
            return $this->toJson([], [], $error);
104
        }
105
    }
106
107
    /**
108
     * @return string
109
     */
110
    protected function getUseFriendlyErrorMessage()
111
    {
112
        return 'An error occurs while processing your request.';
113
    }
114
115
    /**
116
     * Display success data in dataTables editor format.
117
     *
118
     * @param array $data
119
     * @param array $errors
120
     * @param string $error
121
     * @return JsonResponse
122
     */
123
    protected function toJson(array $data, array $errors = [], $error = '')
124
    {
125
        $response = ['data' => $data];
126
127
        if ($error) {
128
            $response['error'] = $error;
129
        }
130
131
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
132
            $response['fieldErrors'] = $errors;
133
        }
134
135
        return new JsonResponse($response, 200);
136
    }
137
138
    /**
139
     * Process create action request.
140
     *
141
     * @param Request $request
142
     * @return JsonResponse
143
     * @throws \Exception
144
     */
145
    public function create(Request $request)
146
    {
147
        $model      = $this->resolveModel();
148
        $connection = $model->getConnection();
149
        $affected   = [];
150
        $errors     = [];
151
152
        $connection->beginTransaction();
153
        foreach ($request->get('data') as $data) {
154
            $this->currentData = $data;
155
156
            $instance  = $model->newInstance();
157
            $validator = $this->getValidationFactory()
158
                              ->make(
159
                                  $data,
160
                                  $this->createRules(), $this->messages() + $this->createMessages(),
0 ignored issues
show
Deprecated Code introduced by
The method Yajra\DataTables\DataTab...ditor::createMessages() has been deprecated with message: deprecated since v1.12.0, please use messages() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
161
                                  $this->attributes()
162
                              );
163
            if ($validator->fails()) {
164
                foreach ($this->formatErrors($validator) as $error) {
165
                    $errors[] = $error;
166
                }
167
168
                continue;
169
            }
170
171
            if (method_exists($this, 'creating')) {
172
                $data = $this->creating($instance, $data);
0 ignored issues
show
Bug introduced by
The method creating() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
173
            }
174
175
            if (method_exists($this, 'saving')) {
176
                $data = $this->saving($instance, $data);
0 ignored issues
show
Bug introduced by
The method saving() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
177
            }
178
179
            $instance->fill($data)->save();
180
181
            if (method_exists($this, 'created')) {
182
                $instance = $this->created($instance, $data);
0 ignored issues
show
Bug introduced by
The method created() does not exist on Yajra\DataTables\DataTablesEditor. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
183
            }
184
185
            if (method_exists($this, 'saved')) {
186
                $instance = $this->saved($instance, $data);
0 ignored issues
show
Bug introduced by
The method saved() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
187
            }
188
189
            $instance->setAttribute('DT_RowId', $instance->getKey());
190
            $affected[] = $instance;
191
        }
192
193
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
194
            $connection->commit();
195
        } else {
196
            $connection->rollBack();
197
        }
198
199
        return $this->toJson($affected, $errors);
200
    }
201
202
    /**
203
     * Resolve model to used.
204
     *
205
     * @return Model|\Illuminate\Database\Eloquent\SoftDeletes
206
     */
207
    protected function resolveModel()
208
    {
209
        if (! $this->model instanceof Model) {
210
            $this->model = new $this->model;
211
        }
212
213
        $this->model->unguard($this->unguarded);
214
215
        return $this->model;
216
    }
217
218
    /**
219
     * Get create action validation rules.
220
     *
221
     * @return array
222
     */
223
    abstract public function createRules();
224
225
    /**
226
     * Get validation messages.
227
     *
228
     * @return array
229
     */
230
    protected function messages()
231
    {
232
        return [];
233
    }
234
235
    /**
236
     * Get create validation messages.
237
     *
238
     * @return array
239
     * @deprecated deprecated since v1.12.0, please use messages() instead.
240
     */
241
    protected function createMessages()
242
    {
243
        return [];
244
    }
245
246
    /**
247
     * Get custom attributes for validator errors.
248
     *
249
     * @return array
250
     */
251
    public function attributes()
252
    {
253
        return [];
254
    }
255
256
    /**
257
     * @param Validator $validator
258
     * @return array
259
     */
260
    protected function formatErrors(Validator $validator)
261
    {
262
        $errors = [];
263
264
        collect($validator->errors())->each(function ($error, $key) use (&$errors) {
265
            $errors[] = [
266
                'name'   => $key,
267
                'status' => $error[0],
268
            ];
269
        });
270
271
        return $errors;
272
    }
273
274
    /**
275
     * Process restore action request.
276
     *
277
     * @param \Illuminate\Http\Request $request
278
     * @return \Illuminate\Http\JsonResponse
279
     */
280
    public function restore(Request $request)
281
    {
282
        $this->restoring = true;
283
284
        return $this->edit($request);
285
    }
286
287
    /**
288
     * Process edit action request.
289
     *
290
     * @param Request $request
291
     * @return JsonResponse
292
     */
293
    public function edit(Request $request)
294
    {
295
        $connection = $this->getBuilder()->getConnection();
296
        $affected   = [];
297
        $errors     = [];
298
299
        $connection->beginTransaction();
300
        foreach ($request->get('data') as $key => $data) {
301
            $this->currentData = $data;
302
303
            $model     = $this->getBuilder()->findOrFail($key);
304
            $validator = $this->getValidationFactory()
305
                              ->make(
306
                                  $data,
307
                                  $this->editRules($model), $this->messages() + $this->editMessages(),
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Yajra\DataTables\DataTablesEditor::editMessages() has been deprecated with message: deprecated since v1.12.0, please use messages() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
308
                                  $this->attributes()
309
                              );
310
            if ($validator->fails()) {
311
                foreach ($this->formatErrors($validator) as $error) {
312
                    $errors[] = $error;
313
                }
314
315
                continue;
316
            }
317
318
            if (method_exists($this, 'updating')) {
319
                $data = $this->updating($model, $data);
0 ignored issues
show
Bug introduced by
The method updating() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
320
            }
321
322
            if (method_exists($this, 'saving')) {
323
                $data = $this->saving($model, $data);
0 ignored issues
show
Bug introduced by
The method saving() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
324
            }
325
326
            $this->restoring ? $model->restore() : $model->fill($data)->save();
327
328
            if (method_exists($this, 'updated')) {
329
                $model = $this->updated($model, $data);
0 ignored issues
show
Bug introduced by
The method updated() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
330
            }
331
332
            if (method_exists($this, 'saved')) {
333
                $model = $this->saved($model, $data);
0 ignored issues
show
Bug introduced by
The method saved() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
334
            }
335
336
            $model->setAttribute('DT_RowId', $model->getKey());
337
            $affected[] = $model;
338
        }
339
340
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
341
            $connection->commit();
342
        } else {
343
            $connection->rollBack();
344
        }
345
346
        return $this->toJson($affected, $errors);
347
    }
348
349
    /**
350
     * Get elqouent builder of the model.
351
     *
352
     * @return \Illuminate\Database\Eloquent\Builder
353
     */
354
    protected function getBuilder()
355
    {
356
        $model = $this->resolveModel();
357
358
        if (in_array(SoftDeletes::class, class_uses($model))) {
359
            return $model->newQuery()->withTrashed();
360
        }
361
362
        return $model->newQuery();
363
    }
364
365
    /**
366
     * Get edit action validation rules.
367
     *
368
     * @param Model $model
369
     * @return array
370
     */
371
    abstract public function editRules(Model $model);
372
373
    /**
374
     * Get edit validation messages.
375
     *
376
     * @return array
377
     * @deprecated deprecated since v1.12.0, please use messages() instead.
378
     */
379
    protected function editMessages()
380
    {
381
        return [];
382
    }
383
384
    /**
385
     * Process force delete action request.
386
     *
387
     * @param \Illuminate\Http\Request $request
388
     * @return \Illuminate\Http\JsonResponse
389
     * @throws \Exception
390
     */
391
    public function forceDelete(Request $request)
392
    {
393
        $this->forceDeleting = true;
394
395
        return $this->remove($request);
396
    }
397
398
    /**
399
     * Process remove action request.
400
     *
401
     * @param Request $request
402
     * @return JsonResponse
403
     * @throws \Exception
404
     */
405
    public function remove(Request $request)
406
    {
407
        $connection = $this->getBuilder()->getConnection();
408
        $affected   = [];
409
        $errors     = [];
410
411
        $connection->beginTransaction();
412
        foreach ($request->get('data') as $key => $data) {
413
            $this->currentData = $data;
414
415
            $model     = $this->getBuilder()->findOrFail($key);
416
            $validator = $this->getValidationFactory()
417
                              ->make(
418
                                  $data,
419
                                  $this->removeRules($model), $this->messages() + $this->removeMessages(),
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Yajra\DataTables\DataTab...ditor::removeMessages() has been deprecated with message: deprecated since v1.12.0, please use messages() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
420
                                  $this->attributes()
421
                              );
422
            if ($validator->fails()) {
423
                foreach ($this->formatErrors($validator) as $error) {
424
                    $errors[] = $error['status'];
425
                }
426
427
                continue;
428
            }
429
430
            try {
431
                $deleted = clone $model;
432
                if (method_exists($this, 'deleting')) {
433
                    $this->deleting($model, $data);
0 ignored issues
show
Bug introduced by
The method deleting() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
434
                }
435
436
                $this->forceDeleting ? $model->forceDelete() : $model->delete();
437
438
                if (method_exists($this, 'deleted')) {
439
                    $this->deleted($deleted, $data);
0 ignored issues
show
Bug introduced by
The method deleted() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
440
                }
441
            } catch (QueryException $exception) {
442
443
                $error = config('app.debug')
444
                    ? $exception->getMessage()
445
                    : $this->removeExceptionMessage($exception, $model);
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
446
447
                $errors[] = $error;
448
            }
449
450
            $affected[] = $deleted;
451
        }
452
453
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
454
            $connection->commit();
455
        } else {
456
            $connection->rollBack();
457
        }
458
459
        $response = ['data' => $affected];
460
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
461
            $response['error'] = implode("\n", $errors);
462
        }
463
464
        return $this->toJson($affected, [], $errors ?? '');
0 ignored issues
show
Bug introduced by
It seems like $errors ?? '' can also be of type array; however, Yajra\DataTables\DataTablesEditor::toJson() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
465
    }
466
467
    /**
468
     * Get remove action validation rules.
469
     *
470
     * @param Model $model
471
     * @return array
472
     */
473
    abstract public function removeRules(Model $model);
474
475
    /**
476
     * Get remove validation messages.
477
     *
478
     * @return array
479
     * @deprecated deprecated since v1.12.0, please use messages() instead.
480
     */
481
    protected function removeMessages()
482
    {
483
        return [];
484
    }
485
486
    /**
487
     * Get remove query exception message.
488
     *
489
     * @param QueryException $exception
490
     * @param Model $model
491
     * @return string
492
     */
493
    protected function removeExceptionMessage(QueryException $exception, Model $model)
0 ignored issues
show
Unused Code introduced by
The parameter $exception is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
494
    {
495
        return "Record {$model->getKey()} is protected and cannot be deleted!";
496
    }
497
498
    /**
499
     * Get dataTables model.
500
     *
501
     * @return Model
502
     */
503
    public function getModel()
504
    {
505
        return $this->model;
506
    }
507
508
    /**
509
     * Set the dataTables model on runtime.
510
     *
511
     * @param Model|string $model
512
     * @return DataTablesEditor
513
     */
514
    public function setModel($model)
515
    {
516
        $this->model = $model;
0 ignored issues
show
Documentation Bug introduced by
It seems like $model can also be of type string. However, the property $model is declared as type object<Illuminate\Database\Eloquent\Model>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
517
518
        return $this;
519
    }
520
521
    /**
522
     * Set model unguard state.
523
     *
524
     * @param bool $state
525
     * @return $this
526
     */
527
    public function unguard($state = true)
528
    {
529
        $this->unguarded = $state;
530
531
        return $this;
532
    }
533
534
    /**
535
     * Handle uploading of file.
536
     *
537
     * @param \Illuminate\Http\Request $request
538
     * @return \Illuminate\Http\JsonResponse
539
     */
540
    public function upload(Request $request)
541
    {
542
        $field   = $request->input('uploadField');
543
        $storage = Storage::disk($this->disk);
544
545
        try {
546
            $rules      = $this->uploadRules();
547
            $fieldRules = ['upload' => data_get($rules, $field, [])];
0 ignored issues
show
Bug introduced by
It seems like $field defined by $request->input('uploadField') on line 542 can also be of type null; however, data_get() does only seem to accept string|array|integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
548
549
            $this->validate($request, $fieldRules, $this->messages(), $this->attributes());
550
551
            $id = $storage->putFile($this->uploadDir, $request->file('upload'));
552
553
            if (method_exists($this, 'uploaded')) {
554
                $id = $this->uploaded($id);
0 ignored issues
show
Bug introduced by
The method uploaded() does not exist on Yajra\DataTables\DataTablesEditor. Did you maybe mean upload()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
555
            }
556
557
            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...
558
                'data'   => [],
559
                'files'  => [
560
                    'files' => [
561
                        $id => [
562
                            'filename'  => $id,
563
                            'size'      => $request->file('upload')->getSize(),
564
                            'directory' => $this->uploadDir,
565
                            'disk'      => $this->disk,
566
                            'url'       => $storage->url($id),
567
                        ],
568
                    ],
569
                ],
570
                'upload' => [
571
                    'id' => $id,
572
                ],
573
            ]);
574
        } catch (ValidationException $exception) {
575
            return response()->json([
576
                'data'        => [],
577
                'fieldErrors' => [
578
                    [
579
                        'name'   => $field,
580
                        'status' => str_replace('upload', $field, $exception->errors()['upload'][0]),
581
                    ],
582
                ],
583
            ]);
584
        }
585
    }
586
587
    /**
588
     * Upload validation rules.
589
     *
590
     * @return array
591
     */
592
    public function uploadRules()
593
    {
594
        return [];
595
    }
596
}
597