Completed
Push — master ( 3b8016...7c79e5 )
by Arjay
01:07
created

DataTablesEditor::getUploadedFilename()   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 2
1
<?php
2
3
namespace Yajra\DataTables;
4
5
use Exception;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\JsonResponse;
8
use Illuminate\Http\UploadedFile;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\QueryException;
11
use Illuminate\Support\Facades\Storage;
12
use Illuminate\Database\Eloquent\SoftDeletes;
13
use Illuminate\Contracts\Validation\Validator;
14
use Illuminate\Validation\ValidationException;
15
use Illuminate\Foundation\Validation\ValidatesRequests;
16
17
abstract class DataTablesEditor
18
{
19
    use ValidatesRequests;
20
21
    /**
22
     * Allowed dataTables editor actions.
23
     *
24
     * @var array
25
     */
26
    protected $actions = [
27
        'create',
28
        'edit',
29
        'remove',
30
        'upload',
31
        'forceDelete',
32
        'restore',
33
    ];
34
35
    /**
36
     * @var \Illuminate\Database\Eloquent\Model
37
     */
38
    protected $model = null;
39
40
    /**
41
     * Indicates if all mass assignment is enabled on model.
42
     *
43
     * @var bool
44
     */
45
    protected $unguarded = false;
46
47
    /**
48
     * Upload directory relative to storage path.
49
     *
50
     * @var string
51
     */
52
    protected $uploadDir = 'editor';
53
54
    /**
55
     * Flag to force delete a model.
56
     *
57
     * @var bool
58
     */
59
    protected $forceDeleting = false;
60
61
    /**
62
     * Flag to restore a model from deleted state.
63
     *
64
     * @var bool
65
     */
66
    protected $restoring = false;
67
68
    /**
69
     * Filesystem disk config to use for upload.
70
     *
71
     * @var string
72
     */
73
    protected $disk = 'public';
74
75
    /**
76
     * Current request data that is being processed.
77
     *
78
     * @var array
79
     */
80
    protected $currentData = [];
81
82
    /**
83
     * Process dataTables editor action request.
84
     *
85
     * @param Request $request
86
     * @return JsonResponse|mixed
87
     * @throws DataTablesEditorException
88
     */
89
    public function process(Request $request)
90
    {
91
        $action = $request->get('action');
92
93
        if (! in_array($action, $this->actions)) {
94
            throw new DataTablesEditorException('Requested action not supported!');
95
        }
96
97
        try {
98
            return $this->{$action}($request);
99
        } catch (Exception $exception) {
100
            $error = config('app.debug')
101
                ? '<strong>Server Error:</strong> ' . $exception->getMessage()
102
                : $this->getUseFriendlyErrorMessage();
103
104
            app('log')->error($exception);
105
106
            return $this->toJson([], [], $error);
107
        }
108
    }
109
110
    /**
111
     * @return string
112
     */
113
    protected function getUseFriendlyErrorMessage()
114
    {
115
        return 'An error occurs while processing your request.';
116
    }
117
118
    /**
119
     * Display success data in dataTables editor format.
120
     *
121
     * @param array $data
122
     * @param array $errors
123
     * @param string $error
124
     * @return JsonResponse
125
     */
126
    protected function toJson(array $data, array $errors = [], $error = '')
127
    {
128
        $response = ['data' => $data];
129
130
        if ($error) {
131
            $response['error'] = $error;
132
        }
133
134
        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...
135
            $response['fieldErrors'] = $errors;
136
        }
137
138
        return new JsonResponse($response, 200);
139
    }
140
141
    /**
142
     * Process create action request.
143
     *
144
     * @param Request $request
145
     * @return JsonResponse
146
     * @throws \Exception
147
     */
148
    public function create(Request $request)
149
    {
150
        $model      = $this->resolveModel();
151
        $connection = $model->getConnection();
152
        $affected   = [];
153
        $errors     = [];
154
155
        $connection->beginTransaction();
156
        foreach ($request->get('data') as $data) {
157
            $this->currentData = $data;
158
159
            $instance  = $model->newInstance();
160
            $validator = $this->getValidationFactory()
161
                              ->make(
162
                                  $data,
163
                                  $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...
164
                                  $this->attributes()
165
                              );
166
            if ($validator->fails()) {
167
                foreach ($this->formatErrors($validator) as $error) {
168
                    $errors[] = $error;
169
                }
170
171
                continue;
172
            }
173
174
            if (method_exists($this, 'creating')) {
175
                $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...
176
            }
177
178
            if (method_exists($this, 'saving')) {
179
                $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...
180
            }
181
182
            $instance->fill($data)->save();
183
184
            if (method_exists($this, 'created')) {
185
                $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...
186
            }
187
188
            if (method_exists($this, 'saved')) {
189
                $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...
190
            }
191
192
            $instance->setAttribute('DT_RowId', $instance->getKey());
193
            $affected[] = $instance;
194
        }
195
196
        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...
197
            $connection->commit();
198
        } else {
199
            $connection->rollBack();
200
        }
201
202
        return $this->toJson($affected, $errors);
203
    }
204
205
    /**
206
     * Resolve model to used.
207
     *
208
     * @return Model|\Illuminate\Database\Eloquent\SoftDeletes
209
     */
210
    protected function resolveModel()
211
    {
212
        if (! $this->model instanceof Model) {
213
            $this->model = new $this->model;
214
        }
215
216
        $this->model->unguard($this->unguarded);
217
218
        return $this->model;
219
    }
220
221
    /**
222
     * Get create action validation rules.
223
     *
224
     * @return array
225
     */
226
    abstract public function createRules();
227
228
    /**
229
     * Get validation messages.
230
     *
231
     * @return array
232
     */
233
    protected function messages()
234
    {
235
        return [];
236
    }
237
238
    /**
239
     * Get create validation messages.
240
     *
241
     * @return array
242
     * @deprecated deprecated since v1.12.0, please use messages() instead.
243
     */
244
    protected function createMessages()
245
    {
246
        return [];
247
    }
248
249
    /**
250
     * Get custom attributes for validator errors.
251
     *
252
     * @return array
253
     */
254
    public function attributes()
255
    {
256
        return [];
257
    }
258
259
    /**
260
     * @param Validator $validator
261
     * @return array
262
     */
263
    protected function formatErrors(Validator $validator)
264
    {
265
        $errors = [];
266
267
        collect($validator->errors())->each(function ($error, $key) use (&$errors) {
268
            $errors[] = [
269
                'name'   => $key,
270
                'status' => $error[0],
271
            ];
272
        });
273
274
        return $errors;
275
    }
276
277
    /**
278
     * Process restore action request.
279
     *
280
     * @param \Illuminate\Http\Request $request
281
     * @return \Illuminate\Http\JsonResponse
282
     */
283
    public function restore(Request $request)
284
    {
285
        $this->restoring = true;
286
287
        return $this->edit($request);
288
    }
289
290
    /**
291
     * Process edit action request.
292
     *
293
     * @param Request $request
294
     * @return JsonResponse
295
     */
296
    public function edit(Request $request)
297
    {
298
        $connection = $this->getBuilder()->getConnection();
299
        $affected   = [];
300
        $errors     = [];
301
302
        $connection->beginTransaction();
303
        foreach ($request->get('data') as $key => $data) {
304
            $this->currentData = $data;
305
306
            $model     = $this->getBuilder()->findOrFail($key);
307
            $validator = $this->getValidationFactory()
308
                              ->make(
309
                                  $data,
310
                                  $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...
311
                                  $this->attributes()
312
                              );
313
            if ($validator->fails()) {
314
                foreach ($this->formatErrors($validator) as $error) {
315
                    $errors[] = $error;
316
                }
317
318
                continue;
319
            }
320
321
            if (method_exists($this, 'updating')) {
322
                $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...
323
            }
324
325
            if (method_exists($this, 'saving')) {
326
                $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...
327
            }
328
329
            $this->restoring ? $model->restore() : $model->fill($data)->save();
330
331
            if (method_exists($this, 'updated')) {
332
                $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...
333
            }
334
335
            if (method_exists($this, 'saved')) {
336
                $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...
337
            }
338
339
            $model->setAttribute('DT_RowId', $model->getKey());
340
            $affected[] = $model;
341
        }
342
343
        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...
344
            $connection->commit();
345
        } else {
346
            $connection->rollBack();
347
        }
348
349
        return $this->toJson($affected, $errors);
350
    }
351
352
    /**
353
     * Get elqouent builder of the model.
354
     *
355
     * @return \Illuminate\Database\Eloquent\Builder
356
     */
357
    protected function getBuilder()
358
    {
359
        $model = $this->resolveModel();
360
361
        if (in_array(SoftDeletes::class, class_uses($model))) {
362
            return $model->newQuery()->withTrashed();
363
        }
364
365
        return $model->newQuery();
366
    }
367
368
    /**
369
     * Get edit action validation rules.
370
     *
371
     * @param Model $model
372
     * @return array
373
     */
374
    abstract public function editRules(Model $model);
375
376
    /**
377
     * Get edit validation messages.
378
     *
379
     * @return array
380
     * @deprecated deprecated since v1.12.0, please use messages() instead.
381
     */
382
    protected function editMessages()
383
    {
384
        return [];
385
    }
386
387
    /**
388
     * Process force delete action request.
389
     *
390
     * @param \Illuminate\Http\Request $request
391
     * @return \Illuminate\Http\JsonResponse
392
     * @throws \Exception
393
     */
394
    public function forceDelete(Request $request)
395
    {
396
        $this->forceDeleting = true;
397
398
        return $this->remove($request);
399
    }
400
401
    /**
402
     * Process remove action request.
403
     *
404
     * @param Request $request
405
     * @return JsonResponse
406
     * @throws \Exception
407
     */
408
    public function remove(Request $request)
409
    {
410
        $connection = $this->getBuilder()->getConnection();
411
        $affected   = [];
412
        $errors     = [];
413
414
        $connection->beginTransaction();
415
        foreach ($request->get('data') as $key => $data) {
416
            $this->currentData = $data;
417
418
            $model     = $this->getBuilder()->findOrFail($key);
419
            $validator = $this->getValidationFactory()
420
                              ->make(
421
                                  $data,
422
                                  $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...
423
                                  $this->attributes()
424
                              );
425
            if ($validator->fails()) {
426
                foreach ($this->formatErrors($validator) as $error) {
427
                    $errors[] = $error['status'];
428
                }
429
430
                continue;
431
            }
432
433
            try {
434
                $deleted = clone $model;
435
                if (method_exists($this, 'deleting')) {
436
                    $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...
437
                }
438
439
                $this->forceDeleting ? $model->forceDelete() : $model->delete();
440
441
                if (method_exists($this, 'deleted')) {
442
                    $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...
443
                }
444
            } catch (QueryException $exception) {
445
                $error = config('app.debug')
446
                    ? $exception->getMessage()
447
                    : $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...
448
449
                $errors[] = $error;
450
            }
451
452
            $affected[] = $deleted;
453
        }
454
455
        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...
456
            $connection->commit();
457
        } else {
458
            $connection->rollBack();
459
        }
460
461
        $response = ['data' => $affected];
462
        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...
463
            $response['error'] = implode("\n", $errors);
464
        }
465
466
        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...
467
    }
468
469
    /**
470
     * Get remove action validation rules.
471
     *
472
     * @param Model $model
473
     * @return array
474
     */
475
    abstract public function removeRules(Model $model);
476
477
    /**
478
     * Get remove validation messages.
479
     *
480
     * @return array
481
     * @deprecated deprecated since v1.12.0, please use messages() instead.
482
     */
483
    protected function removeMessages()
484
    {
485
        return [];
486
    }
487
488
    /**
489
     * Get remove query exception message.
490
     *
491
     * @param QueryException $exception
492
     * @param Model $model
493
     * @return string
494
     */
495
    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...
496
    {
497
        return "Record {$model->getKey()} is protected and cannot be deleted!";
498
    }
499
500
    /**
501
     * Get dataTables model.
502
     *
503
     * @return Model
504
     */
505
    public function getModel()
506
    {
507
        return $this->model;
508
    }
509
510
    /**
511
     * Set the dataTables model on runtime.
512
     *
513
     * @param Model|string $model
514
     * @return DataTablesEditor
515
     */
516
    public function setModel($model)
517
    {
518
        $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...
519
520
        return $this;
521
    }
522
523
    /**
524
     * Set model unguard state.
525
     *
526
     * @param bool $state
527
     * @return $this
528
     */
529
    public function unguard($state = true)
530
    {
531
        $this->unguarded = $state;
532
533
        return $this;
534
    }
535
536
    /**
537
     * Handle uploading of file.
538
     *
539
     * @param \Illuminate\Http\Request $request
540
     * @return \Illuminate\Http\JsonResponse
541
     */
542
    public function upload(Request $request)
543
    {
544
        $field   = $request->input('uploadField');
545
        $storage = Storage::disk($this->disk);
546
547
        try {
548
            $rules      = $this->uploadRules();
549
            $fieldRules = ['upload' => data_get($rules, $field, [])];
550
551
            $this->validate($request, $fieldRules, $this->messages(), $this->attributes());
552
553
            $uploadedFile = $request->file('upload');
554
            $filename     = $this->getUploadedFilename($field, $uploadedFile);
0 ignored issues
show
Bug introduced by
It seems like $uploadedFile defined by $request->file('upload') on line 553 can also be of type array or null; however, Yajra\DataTables\DataTab...::getUploadedFilename() does only seem to accept object<Illuminate\Http\UploadedFile>, 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...
555
            $id           = $storage->putFileAs($this->uploadDir, $uploadedFile, $filename);
556
557
            if (method_exists($this, 'uploaded')) {
558
                $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...
559
            }
560
561
            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...
562
                'data'   => [],
563
                'files'  => [
564
                    'files' => [
565
                        $id => [
566
                            'filename'      => $id,
567
                            'original_name' => $uploadedFile->getClientOriginalName(),
568
                            'size'          => $uploadedFile->getSize(),
569
                            'directory'     => $this->uploadDir,
570
                            'disk'          => $this->disk,
571
                            'url'           => $storage->url($id),
572
                        ],
573
                    ],
574
                ],
575
                'upload' => [
576
                    'id' => $id,
577
                ],
578
            ]);
579
        } catch (ValidationException $exception) {
580
            return response()->json([
581
                'data'        => [],
582
                'fieldErrors' => [
583
                    [
584
                        'name'   => $field,
585
                        'status' => str_replace('upload', $field, $exception->errors()['upload'][0]),
586
                    ],
587
                ],
588
            ]);
589
        }
590
    }
591
592
    /**
593
     * Upload validation rules.
594
     *
595
     * @return array
596
     */
597
    public function uploadRules()
598
    {
599
        return [];
600
    }
601
602
    /**
603
     * @param string $field
604
     * @param UploadedFile $uploadedFile
605
     * @return string
606
     */
607
    protected function getUploadedFilename($field, UploadedFile $uploadedFile)
0 ignored issues
show
Unused Code introduced by
The parameter $field 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...
608
    {
609
        return date('Ymd_His') . '_' . $uploadedFile->getClientOriginalName();
610
    }
611
}
612