Completed
Push — master ( 8a6666...9e6d24 )
by Babak
03:06
created

BaseController::handleOwnPermission()   C

Complexity

Conditions 14
Paths 16

Size

Total Lines 113
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 66
nc 16
nop 3
dl 0
loc 113
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Alive2212\LaravelSmartRestful;
4
5
use Alive2212\ExcelHelper\ExcelHelper;
6
use Alive2212\LaravelQueryHelper\QueryHelper;
0 ignored issues
show
Bug introduced by
The type Alive2212\LaravelQueryHelper\QueryHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Alive2212\LaravelRequestHelper\RequestHelper;
0 ignored issues
show
Bug introduced by
The type Alive2212\LaravelRequestHelper\RequestHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Alive2212\LaravelSmartResponse\ResponseModel;
9
use Alive2212\LaravelSmartResponse\SmartResponse\SmartResponse;
0 ignored issues
show
Bug introduced by
The type Alive2212\LaravelSmartRe...tResponse\SmartResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Alive2212\LaravelStringHelper\StringHelper;
0 ignored issues
show
Bug introduced by
The type Alive2212\LaravelStringHelper\StringHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use App\Car;
0 ignored issues
show
Bug introduced by
The type App\Car was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use App\Group;
0 ignored issues
show
Bug introduced by
The type App\Group was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use App\Http\Controllers\Controller;
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use App\Location;
0 ignored issues
show
Bug introduced by
The type App\Location was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Illuminate\Database\Eloquent\ModelNotFoundException;
16
use Illuminate\Database\QueryException;
17
use Illuminate\Http\Request;
18
use Illuminate\Support\Facades\DB;
19
use Illuminate\Support\MessageBag;
20
use Illuminate\Support\Facades\Validator;
21
use Mockery\Exception;
0 ignored issues
show
Bug introduced by
The type Mockery\Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
23
24
abstract class BaseController extends Controller
25
{
26
    /**
27
     * to use this class
28
     * create message list as messages in message file
29
     * override __constructor and define your model
30
     * define your rules for index,store and update
31
     */
32
33
    /**
34
     * permission types 'admin'|'branch'|'own'|'guest'
35
     *
36
     * @var string
37
     */
38
    protected $DEFAULT_PERMISSION_TYPE = 'admin';
39
40
    /**
41
     * permission types 'admin'|'branch'|'own'|'guest'
42
     *
43
     * @var string
44
     */
45
    protected $DEFAULT_GROUP_TITLE = null;
46
47
    /**
48
     * @var string
49
     */
50
    protected $LOCALE_PREFIX = 'controller';
51
52
    /**
53
     * @var int
54
     */
55
    protected $DEFAULT_RESULT_PER_PAGE = 15;
56
57
    /**
58
     * @var int
59
     */
60
    protected $DEFAULT_PAGE_NUMBER = 1;
61
62
    /**
63
     * @var array
64
     */
65
    protected $pivotFields = [];
66
67
    /**
68
     * @var array
69
     */
70
    protected $uniqueFields = [];
71
72
    /**
73
     * @var bool|string
74
     */
75
    protected $modelName;
76
77
    /**
78
     * @var string
79
     */
80
    protected $messagePrefix = 'messages.api.v1.';
81
82
    /**
83
     * this model
84
     */
85
    protected $model;
86
87
    /**
88
     * index request validator rules
89
     *
90
     * @var array
91
     */
92
    protected $indexValidateArray = [
93
        //
94
    ];
95
96
    /**
97
     * array of relationship for eager loading
98
     *
99
     * @var array
100
     */
101
    protected $indexLoad = [
102
        //
103
    ];
104
105
    /**
106
     * array of relationship for eager loading
107
     *
108
     * @var array
109
     */
110
    protected $editLoad = [
111
        //
112
    ];
113
114
    /**
115
     * array of relationship for eager loading
116
     *
117
     * @var array
118
     */
119
    protected $updateLoad = [
120
        //
121
    ];
122
123
    /**
124
     * array of relationship for eager loading
125
     *
126
     * @var array
127
     */
128
    protected $storeLoad = [
129
        //
130
    ];
131
132
    /**
133
     * store request validator rules
134
     *
135
     * @var array
136
     */
137
    protected $storeValidateArray = [
138
        //
139
    ];
140
141
    /**
142
     * update request validator rules
143
     *
144
     * @var array
145
     */
146
    protected $updateValidateArray = [
147
        //
148
    ];
149
150
    protected $middlewareParams = [];
151
152
    /**
153
     * defaultController constructor.
154
     */
155
    public function __construct()
156
    {
157
//        dd("I have closest relationship with all US & UK celebrities");
158
        // init controller
159
        $this->initController();
160
161
        // set local language
162
        $this->setLocale();
163
    }
164
165
    abstract public function initController();
166
167
    /**
168
     * Display a listing of the resource.
169
     *
170
     * @param Request $request
171
     * @return string
172
     */
173
    public function index(Request $request)
174
    {
175
        // handle permission
176
        $request = $this->handlePermission(__FUNCTION__, $request);
177
178
        // create response model
179
        $response = new ResponseModel();
180
181
        $pageSize = $this->DEFAULT_RESULT_PER_PAGE;
0 ignored issues
show
Unused Code introduced by
The assignment to $pageSize is dead and can be removed.
Loading history...
182
183
        $pageNumber = 1;
184
185
        //set default pagination
186
187
        //set page size
188
        if (!isset($request->toArray()['page']['size'])) {
189
            $pageSize = $this->DEFAULT_RESULT_PER_PAGE;
190
        } elseif (($request->get('page')['size']) == 0) {
191
            $pageSize = $this->DEFAULT_RESULT_PER_PAGE;
192
        } else {
193
            $pageSize = $request->get('page')['size'];
194
        }
195
196
        //set page number
197
        if (!isset($request->get('page')['number'])) {
198
            $pageNumber = $this->DEFAULT_PAGE_NUMBER;
199
        } elseif (($request->get('page')['number']) == 0) {
200
            $pageNumber = $this->DEFAULT_PAGE_NUMBER;
201
        } else {
202
            $pageNumber = $request->get('page')['number'];
203
        }
204
        $request['page'] = $pageNumber;
205
206
207
        //set default ordering
208
        if (isset($request->toArray()['order_by'])) {
209
            if (is_null($request['order_by'])) {
210
                $request['order_by'] = "{\"field\":\"id\",\"operator\":\"Desc\"}";
211
            }
212
        }
213
214
        $validationErrors = $this->checkRequestValidation($request, $this->indexValidateArray);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type array; however, parameter $request of Alive2212\LaravelSmartRe...heckRequestValidation() does only seem to accept Illuminate\Http\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

214
        $validationErrors = $this->checkRequestValidation(/** @scrutinizer ignore-type */ $request, $this->indexValidateArray);
Loading history...
215
        if ($validationErrors != null) {
216
            if (env('APP_DEBUG', false)) {
217
                $response->setData(collect($validationErrors->toArray()));
218
            }
219
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
220
            $response->setStatus(false);
221
            $response->setError(99);
222
            return SmartResponse::response($response);
223
        }
224
225
        try {
226
            $data = $request->get('query') != null ?
227
                $this->model
228
                    ->whereKey(collect($this->model
229
                        ->search(($request->get('query')))
230
                        ->raw())->get('ids')) :
231
                $this->model;
232
233
            if (array_key_exists('file', $request->toArray())) {
234
                //TODO add relation on top if here and create a tree flatter array in array helper
235
                return (new ExcelHelper())->setOptions([
0 ignored issues
show
Bug introduced by
Are you sure the usage of new Alive2212\ExcelHelpe...ExcelFile()->download() targeting Alive2212\ExcelHelper\ExcelHelper::download() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
236
                    'store_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
237
                    'download_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
238
                ])->table($data->get()->toArray())->createExcelFile()->download();
239
            }
240
241
            // load relations
242
            if (count($this->indexLoad) > 0) {
243
                $data = $data->with($this->indexLoad);
244
            }
245
246
            // filters by
247
            if (!is_null($request->get('filters'))) {
248
                $data = (new QueryHelper())->deepFilter($data, (new RequestHelper())->getCollectFromJson($request['filters']));
249
            }
250
251
            // order by
252
            if (!is_null($request->get('order_by'))) {
253
                $data = (new QueryHelper())->orderBy($data, (new RequestHelper())->getCollectFromJson($request['order_by']));
254
            }
255
256
            // return response
257
            $response->setData(collect($data->paginate($pageSize)));
258
            $response->setMessage($this->getTrans('index', 'successful'));
259
            return SmartResponse::response($response);
260
261
        } catch (QueryException $exception) {
262
263
            // return response
264
            $response->setData(collect($exception->getMessage()));
265
            $response->setError($exception->getCode());
266
            $response->setMessage($this->getTrans('index', 'failed'));
267
            $response->setStatus(false);
268
            return SmartResponse::response($response);
269
        }
270
    }
271
272
    public function checkRequestValidation(Request $request, $validationArray)
273
    {
274
        $requestParams = $request->toArray();
0 ignored issues
show
Unused Code introduced by
The assignment to $requestParams is dead and can be removed.
Loading history...
275
        $validator = Validator::make($request->all(), $validationArray);
276
        if ($validator->fails()) {
277
            return $validator->errors();
278
        }
279
        return null;
280
    }
281
282
    /**
283
     * @param $status
284
     * @return mixed
285
     */
286
    public function message($status)
287
    {
288
        $key = $this->messagePrefix . $this->modelName . '.' . debug_backtrace()[1]['function'] . '.' . $status;
289
        return $this->getMessageFromFile($key);
290
    }
291
292
    /**
293
     * @param $key
294
     * @return mixed
295
     */
296
    public function getMessageFromFile($key)
297
    {
298
        return config($key);
299
    }
300
301
    /**
302
     * Show the form for creating a new resource.
303
     *
304
     * @return \Illuminate\Http\JsonResponse
305
     */
306
    public function create()
307
    {
308
        // Create Response Model
309
        $response = new ResponseModel();
310
311
        // return response
312
        $response->setData(collect($this->model->getFillable()));
313
        $response->setMessage($this->getTrans('create', 'successful'));
314
        return SmartResponse::response($response);
315
    }
316
317
    /**
318
     * Store a newly created resource in storage.
319
     *
320
     * @param  \Illuminate\Http\Request $request
321
     * @return \Illuminate\Http\JsonResponse
322
     */
323
    public function store(Request $request)
324
    {
325
        // handle permission
326
        $request = $this->handlePermission(__FUNCTION__, $request);
327
328
        // Create Response Model
329
        $response = new ResponseModel();
330
331
        if (!isset($userId)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $userId seems to never exist and therefore isset should always be false.
Loading history...
332
            $userId = 1;
333
        }
334
335
        //add author id into the request if doesn't exist
336
        if (is_null($request->get('author_id'))) {
337
            $request['author_id'] = $userId;
338
        }
339
340
        //add user id into the request if doesn't exist
341
        if (is_null($request->get('user_id'))) {
342
            $request['user_id'] = $userId;
343
        }
344
345
        $validationErrors = $this->checkRequestValidation($request, $this->storeValidateArray);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type array; however, parameter $request of Alive2212\LaravelSmartRe...heckRequestValidation() does only seem to accept Illuminate\Http\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

345
        $validationErrors = $this->checkRequestValidation(/** @scrutinizer ignore-type */ $request, $this->storeValidateArray);
Loading history...
346
347
        if ($validationErrors != null) {
348
            if (env('APP_DEBUG', false)) {
349
                $response->setData(collect($validationErrors->toArray()));
350
            }
351
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
352
            $response->setStatus(false);
353
            $response->setError(99);
354
            return SmartResponse::response($response);
355
356
        }
357
358
        try {
359
            // get result of model creation
360
            $result = $this->model->create($request->all());
361
            // sync many to many relation
362
            foreach ($this->pivotFields as $pivotField) {
363
                if (collect($request[$pivotField])->count()) {
364
                    $pivotField = (new StringHelper())->toCamel($pivotField);
365
                    $this->model->find($result['id'])->$pivotField()->sync(json_decode($request[$pivotField]));
366
                }
367
            }
368
            $response->setMessage($this->getTrans('store', 'successful'));
369
370
371
            $response->setData($this->model
372
                ->where($this->model->getKeyName(), $result['id'])
373
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
374
                ->get());
375
376
            $response->setStatus(true);
377
        } catch (QueryException $exception) {
378
            $response->setError($exception->getCode());
379
            $response->setMessage($this->getTrans('store', 'failed'));
380
            $response->setStatus(false);
381
            if (env('APP_DEBUG', false)) {
382
                $response->setData(collect($exception->getMessage()));
383
            }
384
        }
385
        return SmartResponse::response($response);
386
    }
387
388
    /**
389
     * Display the specdefaultied resource.
390
     *
391
     * @param  int $id
392
     * @return \Illuminate\Http\JsonResponse
393
     */
394
    public function show($id)
395
    {
396
        // handle permission
397
        $filters = $this->handlePermission(__FUNCTION__);
398
399
        // Create Response Model
400
        $response = new ResponseModel();
401
402
        // try to get data
403
        try {
404
            $response->setMessage($this->getTrans('show', 'successful'));
405
406
            // add filter to get desired record
407
            array_push($filters,
408
                [$this->model->getKeyName(), '=', $id]
409
            );
410
            $data = $this->model
411
                ->where($filters)
412
                ->get();
413
            $response->setData($data);
414
415
            // catch exception
416
        } catch (Exception $exception) {
417
            $response->setError($exception->getCode());
418
            $response->setMessage($this->getTrans('show', 'failed'));
419
            $response->setStatus(false);
420
            if (env('APP_DEBUG', false)) {
421
                $response->setData(collect($exception->getMessage()));
422
            }
423
        }
424
        return SmartResponse::response($response);
425
    }
426
427
    /**
428
     * Show the form for editing the specified resource.
429
     *
430
     * @param  int $id
431
     * @return \Illuminate\Http\JsonResponse
432
     */
433
    public function edit($id)
434
    {
435
        // handle permission
436
        $filters = $this->handlePermission(__FUNCTION__);
437
438
        // Create Response Model
439
        $response = new ResponseModel();
440
441
        try {
442
            $response->setMessage($this->getTrans('edit', 'successful'));
443
444
            // add filter to get desired record
445
            array_push($filters,
446
                [$this->model->getKeyName(), '=', $id]
447
            );
448
            $data = $this->model
449
                ->where($filters)
450
                ->with(collect($this->editLoad)->count() == 0 ? $this->indexLoad : $this->editLoad)
451
                ->get();
452
            $response->setData($data);
453
454
        } catch (ModelNotFoundException $exception) {
455
            $response->setError($exception->getCode());
0 ignored issues
show
Bug introduced by
It seems like $exception->getCode() can also be of type integer; however, parameter $error of Alive2212\LaravelSmartRe...sponseModel::setError() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

455
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
456
            $response->setMessage($this->getTrans('edit', 'failed'));
457
            $response->setStatus(false);
458
            if (env('APP_DEBUG', false)) {
459
                $response->setData(collect($exception->getMessage()));
460
            }
461
462
        }
463
464
        return SmartResponse::response($response);
465
    }
466
467
    /**
468
     * Update the specified resource in storage.
469
     *
470
     * @param  \Illuminate\Http\Request $request
471
     * @param  int $id
472
     * @return \Illuminate\Http\JsonResponse
473
     */
474
    public function update(Request $request, $id)
475
    {
476
        // Handle permission
477
        $request = $this->handlePermission(__FUNCTION__,$request);
478
        $filters = $request['permission_filters'];
479
480
        // Create Response Model
481
        $response = new ResponseModel();
482
483
        // Filters
484
        array_push($filters,
485
            [$this->model->getKeyName(), '=', $id]
486
        );
487
488
        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type array; however, parameter $request of Alive2212\LaravelSmartRe...heckRequestValidation() does only seem to accept Illuminate\Http\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

488
        $validationErrors = $this->checkRequestValidation(/** @scrutinizer ignore-type */ $request, $this->updateValidateArray);
Loading history...
489
        if ($validationErrors != null) {
490
            if (env('APP_DEBUG', false)) {
491
                $response->setData(collect($validationErrors->toArray()));
492
            }
493
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
494
            $response->setStatus(false);
495
            $response->setError(99);
496
            return SmartResponse::response($response);
497
498
        }
499
500
        try {
501
            // sync many to many relation
502
            foreach ($this->pivotFields as $pivotField) {
503
                if (collect($request[$pivotField])->count()) {
504
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
505
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
506
                }
507
            }
508
            //get result of update
509
            $result = $this->model->where($filters)->firstOrFail()->update($request->all());
510
511
            // return response
512
            $response->setData($this->model
513
                ->where($filters)
514
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
515
                ->get());
516
            $response->setMessage(
517
                $this->getTrans(__FUNCTION__, 'successful1') .
0 ignored issues
show
Bug introduced by
Are you sure $this->getTrans(__FUNCTION__, 'successful1') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

517
                /** @scrutinizer ignore-type */ $this->getTrans(__FUNCTION__, 'successful1') .
Loading history...
518
                $result .
519
                $this->getTrans(__FUNCTION__, 'successful2')
0 ignored issues
show
Bug introduced by
Are you sure $this->getTrans(__FUNCTION__, 'successful2') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

519
                /** @scrutinizer ignore-type */ $this->getTrans(__FUNCTION__, 'successful2')
Loading history...
520
            );
521
522
        } catch (ModelNotFoundException $exception) {
523
            $response->setStatus(false);
524
            $response->setMessage($this->getTrans(__FUNCTION__, 'model_not_found'));
525
            $response->setError($exception->getCode());
526
            if (env('APP_DEBUG', false)) {
527
                $response->setData(collect($exception->getMessage()));
528
            }
529
530
        } catch (QueryException $exception) {
531
            $response->setStatus(false);
532
            $response->setMessage($this->getTrans(__FUNCTION__, 'failed'));
533
            $response->setError($exception->getCode());
534
            if (env('APP_DEBUG', false)) {
535
                $response->setData(collect($exception->getMessage()));
536
            }
537
538
        }
539
540
        return SmartResponse::response($response);
541
    }
542
543
    /**
544
     * Remove the specified resource from storage.
545
     *
546
     * @param  int $id
547
     * @return \Illuminate\Http\JsonResponse
548
     */
549
    public function destroy($id)
550
    {
551
        // Create Response Model
552
        $response = new ResponseModel();
553
554
        try {
555
            $response->setData(collect($this->model->findOrFail($id)->delete()));
556
            $response->setMessage($this->getTrans('destroy', 'successful'));
557
558
        } catch (ModelNotFoundException $exception) {
559
            $response->setMessage($this->getTrans('destroy', 'successful'));
560
            $response->setStatus(false);
561
            $response->setError($exception->getCode());
0 ignored issues
show
Bug introduced by
It seems like $exception->getCode() can also be of type integer; however, parameter $error of Alive2212\LaravelSmartRe...sponseModel::setError() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

561
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
562
            if (env('APP_DEBUG', false)) {
563
                $response->setData(collect($exception->getMessage()));
564
            }
565
566
        }
567
568
        return SmartResponse::response($response);
569
    }
570
571
    /**
572
     * @param $method
573
     * @param $status
574
     * @return array|\Illuminate\Contracts\Translation\Translator|null|string
575
     */
576
    public function getTrans($method, $status)
577
    {
578
        return trans('laravel_smart_restful::' . $this->LOCALE_PREFIX . '.' . get_class($this->model) . '.' . $method . '.' . $status);
579
    }
580
581
    /**
582
     * set local
583
     */
584
    public function setLocale()
585
    {
586
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
587
            app('translator')->setLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
588
        }
589
    }
590
591
    public function handlePermission($functionName, Request $request = null, $params = [])
592
    {
593
        if (!is_null($request)) {
594
            if ($request->has('permission_type')) {
595
                $this->DEFAULT_PERMISSION_TYPE = $request['permission_type'];
596
            }
597
        }
598
        switch ($this->DEFAULT_PERMISSION_TYPE) {
599
            case 'admin':
600
                return $this->handleAdminPermission($functionName, $request, $params);
601
            case 'branch':
602
                return $this->handleBranchPermission($functionName, $request, $params);
603
            case 'own':
604
                return $this->handleOwnPermission($functionName, $request, $params);
605
            case 'guest':
606
                return $this->handleGuestPermission($functionName, $request, $params);
607
            default:
608
                return $params;
609
        }
610
    }
611
612
    public function handleAdminPermission($functionName, Request $request = null, $params = [])
613
    {
614
        return $request;
615
        switch ($functionName) {
0 ignored issues
show
Unused Code introduced by
SwitchNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
616
            case 'index':
617
            case 'store':
618
            case 'show':
619
            case 'edit':
620
            case 'create':
621
            case 'update':
622
            case 'destroy':
623
            default:
624
                return $params;
625
        }
626
    }
627
628
    public function handleBranchPermission($functionName, Request $request = null, $params)
629
    {
630
        switch ($functionName) {
631
            case 'index':
632
            case 'store':
633
            case 'show':
634
            case 'edit':
635
            case 'create':
636
            case 'update':
637
            case 'destroy':
638
            default:
639
                return $params;
640
        }
641
    }
642
643
    public function handleOwnPermission($functionName, Request $request = null, $params)
644
    {
645
        switch ($functionName) {
646
            case 'index':
647
                if (isset($request['filters'])) {
648
                    $filters = json_decode($request['filters'], true);
649
                } else {
650
                    $filters = [];
651
                }
652
                array_push($filters,
653
                    [
654
                        'key' => 'owner_id',
655
                        'operator' => '=',
656
                        'value' => auth()->id()
657
                    ]
658
                );
659
                if (!is_null($this->DEFAULT_GROUP_TITLE)) {
0 ignored issues
show
introduced by
The condition is_null($this->DEFAULT_GROUP_TITLE) is always false.
Loading history...
660
                    array_push($filters,
661
                        [
662
                            'key' => 'group.title',
663
                            'operator' => '=',
664
                            'value' => $this->DEFAULT_GROUP_TITLE
665
                        ]
666
                    );
667
                }
668
                $request['filters'] = json_encode($filters);
669
                return $request;
670
            case 'store':
671
                // check for group of user
672
                if (!is_null($this->DEFAULT_GROUP_TITLE)) {
0 ignored issues
show
introduced by
The condition is_null($this->DEFAULT_GROUP_TITLE) is always false.
Loading history...
673
                    // get group model
674
                    $group = new Group();
675
                    $group = $group->where('title', $this->DEFAULT_GROUP_TITLE)->first();
676
                    $request['group_id'] = $group['id'];
677
                }
678
679
                $request['owner_id'] = auth()->id();
680
                return $request;
681
682
            case 'show':
683
                $filters = [];
684
                array_push($filters,
685
                    ["owner_id", "=", auth()->id()]
686
                );
687
688
                // check for group of user
689
                if (!is_null($this->DEFAULT_GROUP_TITLE)) {
0 ignored issues
show
introduced by
The condition is_null($this->DEFAULT_GROUP_TITLE) is always false.
Loading history...
690
691
                    // get group model
692
                    $group = new Group();
693
                    $group = $group->where('title', $this->DEFAULT_GROUP_TITLE)->first();
694
695
                    // put group_id filter
696
                    array_push($filters,
697
                        ['group_id', '=', $group['id']]);
698
                }
699
700
                return $filters;
701
            case 'edit':
702
                $filters = [];
703
                array_push($filters,
704
                    ["owner_id", "=", auth()->id()]
705
                );
706
707
                // check gor group of user
708
                if (!is_null($this->DEFAULT_GROUP_TITLE)) {
0 ignored issues
show
introduced by
The condition is_null($this->DEFAULT_GROUP_TITLE) is always false.
Loading history...
709
                    // get group model
710
                    $group = new Group();
711
                    $group = $group->where('title', $this->DEFAULT_GROUP_TITLE)->first();
712
713
                    // put group_id filter
714
                    array_push($filters,
715
                        ['group_id', '=', $group['id']]);
716
                }
717
718
                return $filters;
719
            case 'create':
720
            case 'update':
721
722
                $filters = [];
723
                // put to filter
724
                array_push($filters,
725
                    ["owner_id", "=", auth()->id()]
726
                );
727
728
                // put to request
729
                $request['owner_id'] = auth()->id();
730
731
                // check for group of user
732
                if (!is_null($this->DEFAULT_GROUP_TITLE)) {
0 ignored issues
show
introduced by
The condition is_null($this->DEFAULT_GROUP_TITLE) is always false.
Loading history...
733
                    // get group model
734
                    $group = new Group();
735
                    $group = $group->where('title', $this->DEFAULT_GROUP_TITLE)->first();
736
737
                    // put group_id filter
738
                    array_push($filters,
739
                        ['group_id', '=', $group['id']]);
740
741
                    // put to request
742
                    $request['group_id'] = $group['id'];
743
                }
744
745
                $request['permission_filters'] = $filters;
746
                return $request;
747
            case 'destroy':
748
                $filters = [];
749
                array_push($filters,
750
                    ["owner_id", "=", auth()->id()],
751
                    ["group_id", "=", $this->DEFAULT_GROUP_TITLE]
752
                );
753
                return $filters;
754
            default:
755
                return $params;
756
        }
757
    }
758
759
    public function handleGuestPermission($functionName, Request $request = null, $params)
760
    {
761
        switch ($functionName) {
762
            case 'index':
763
            case 'store':
764
            case 'show':
765
            case 'edit':
766
            case 'create':
767
            case 'update':
768
            case 'destroy':
769
            default:
770
                return $params;
771
        }
772
    }
773
774
}