Passed
Push — master ( 7b42a8...29affb )
by Babak
02:25
created

BaseController::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
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\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...
13
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...
14
use Illuminate\Database\Eloquent\ModelNotFoundException;
15
use Illuminate\Database\QueryException;
16
use Illuminate\Http\Request;
17
use Illuminate\Support\Facades\DB;
18
use Illuminate\Support\MessageBag;
19
use Illuminate\Support\Facades\Validator;
20
21
22
abstract class BaseController extends Controller
23
{
24
    /**
25
     * to use this class
26
     * create message list as messages in message file
27
     * override __constructor and define your model
28
     * define your rules for index,store and update
29
     */
30
31
    /**
32
     * permission types 'admin'|'branch'|'own'|'guest'
33
     *
34
     * @var string
35
     */
36
    protected $DEFAULT_PERMISSION_TYPE = 'admin';
37
38
    /**
39
     * @var string
40
     */
41
    protected $LOCALE_PREFIX = 'controller';
42
43
    /**
44
     * @var int
45
     */
46
    protected $DEFAULT_RESULT_PER_PAGE = 15;
47
48
    /**
49
     * @var int
50
     */
51
    protected $DEFAULT_PAGE_NUMBER = 1;
52
53
    /**
54
     * @var array
55
     */
56
    protected $pivotFields = [];
57
58
    /**
59
     * @var array
60
     */
61
    protected $uniqueFields = [];
62
63
    /**
64
     * @var bool|string
65
     */
66
    protected $modelName;
67
68
    /**
69
     * @var string
70
     */
71
    protected $messagePrefix = 'messages.api.v1.';
72
73
    /**
74
     * this model
75
     */
76
    protected $model;
77
78
    /**
79
     * index request validator rules
80
     *
81
     * @var array
82
     */
83
    protected $indexValidateArray = [
84
        //
85
    ];
86
87
    /**
88
     * array of relationship for eager loading
89
     *
90
     * @var array
91
     */
92
    protected $indexLoad = [
93
        //
94
    ];
95
96
    /**
97
     * array of relationship for eager loading
98
     *
99
     * @var array
100
     */
101
    protected $editLoad = [
102
        //
103
    ];
104
105
    /**
106
     * array of relationship for eager loading
107
     *
108
     * @var array
109
     */
110
    protected $updateLoad = [
111
        //
112
    ];
113
114
    /**
115
     * array of relationship for eager loading
116
     *
117
     * @var array
118
     */
119
    protected $storeLoad = [
120
        //
121
    ];
122
123
    /**
124
     * store request validator rules
125
     *
126
     * @var array
127
     */
128
    protected $storeValidateArray = [
129
        //
130
    ];
131
132
    /**
133
     * update request validator rules
134
     *
135
     * @var array
136
     */
137
    protected $updateValidateArray = [
138
        //
139
    ];
140
141
    protected $middlewareParams = [];
142
143
    /**
144
     * defaultController constructor.
145
     */
146
    public function __construct()
147
    {
148
//        dd("I have closest relationship with all US & UK celebrities");
149
        // init controller
150
        $this->initController();
151
152
        // set local language
153
        $this->setLocale();
154
    }
155
156
    abstract public function initController();
157
158
    /**
159
     * Display a listing of the resource.
160
     *
161
     * @param Request $request
162
     * @return string
163
     */
164
    public function index(Request $request)
165
    {
166
        // handle permission
167
        $request = $this->handlePermission($request, __FUNCTION__);
168
169
        // create response model
170
        $response = new ResponseModel();
171
172
        $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...
173
174
        $pageNumber = 1;
175
176
        //set default pagination
177
178
        //set page size
179
        if (!isset($request->toArray()['page']['size'])) {
180
            $pageSize = $this->DEFAULT_RESULT_PER_PAGE;
181
        } elseif (($request->get('page')['size']) == 0) {
182
            $pageSize = $this->DEFAULT_RESULT_PER_PAGE;
183
        } else {
184
            $pageSize = $request->get('page')['size'];
185
        }
186
187
        //set page number
188
        if (!isset($request->get('page')['number'])) {
189
            $pageNumber = $this->DEFAULT_PAGE_NUMBER;
190
        } elseif (($request->get('page')['number']) == 0) {
191
            $pageNumber = $this->DEFAULT_PAGE_NUMBER;
192
        } else {
193
            $pageNumber = $request->get('page')['number'];
194
        }
195
        $request['page'] = $pageNumber;
196
197
198
        //set default ordering
199
        if (isset($request->toArray()['order_by'])) {
200
            if (is_null($request['order_by'])) {
201
                $request['order_by'] = "{\"field\":\"id\",\"operator\":\"Desc\"}";
202
            }
203
        }
204
205
        $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

205
        $validationErrors = $this->checkRequestValidation(/** @scrutinizer ignore-type */ $request, $this->indexValidateArray);
Loading history...
206
        if ($validationErrors != null) {
207
            if (env('APP_DEBUG', false)) {
208
                $response->setData(collect($validationErrors->toArray()));
209
            }
210
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
211
            $response->setStatus(false);
212
            $response->setError(99);
213
            return SmartResponse::response($response);
214
        }
215
216
        try {
217
            $data = $request->get('query') != null ?
218
                $this->model
219
                    ->whereKey(collect($this->model
220
                        ->search(($request->get('query')))
221
                        ->raw())->get('ids')) :
222
                $this->model;
223
224
            if (array_key_exists('file', $request->toArray())) {
225
                //TODO add relation on top if here and create a tree flatter array in array helper
226
                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...
227
                    'store_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
228
                    'download_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
229
                ])->table($data->get()->toArray())->createExcelFile()->download();
230
            }
231
232
            // load relations
233
            if (count($this->indexLoad) > 0) {
234
                $data = $data->with($this->indexLoad);
235
            }
236
237
            // filters by
238
            if (isset($request->toArray()['filters'])) {
239
                $data = (new QueryHelper())->deepFilter($data, (new RequestHelper())->getCollectFromJson($request['filters']));
240
            }
241
242
            // order by
243
            if (isset($request->toArray()['order_by'])) {
244
                $data = (new QueryHelper())->orderBy($data, (new RequestHelper())->getCollectFromJson($request['order_by']));
245
            }
246
247
            // return response
248
            $response->setData(collect($data->paginate($pageSize)));
249
            $response->setMessage($this->getTrans('index', 'successful'));
250
            return SmartResponse::response($response);
251
252
        } catch (QueryException $exception) {
253
254
            // return response
255
            $response->setData(collect($exception->getMessage()));
256
            $response->setError($exception->getCode());
257
            $response->setMessage($this->getTrans('index', 'failed'));
258
            $response->setStatus(false);
259
            return SmartResponse::response($response);
260
        }
261
    }
262
263
    public function checkRequestValidation(Request $request, $validationArray)
264
    {
265
        $requestParams = $request->toArray();
0 ignored issues
show
Unused Code introduced by
The assignment to $requestParams is dead and can be removed.
Loading history...
266
        $validator = Validator::make($request->all(), $validationArray);
267
        if ($validator->fails()) {
268
            return $validator->errors();
269
        }
270
        return null;
271
    }
272
273
    /**
274
     * @param $status
275
     * @return mixed
276
     */
277
    public function message($status)
278
    {
279
        $key = $this->messagePrefix . $this->modelName . '.' . debug_backtrace()[1]['function'] . '.' . $status;
280
        return $this->getMessageFromFile($key);
281
    }
282
283
    /**
284
     * @param $key
285
     * @return mixed
286
     */
287
    public function getMessageFromFile($key)
288
    {
289
        return config($key);
290
    }
291
292
    /**
293
     * Show the form for creating a new resource.
294
     *
295
     * @return \Illuminate\Http\JsonResponse
296
     */
297
    public function create()
298
    {
299
        // Create Response Model
300
        $response = new ResponseModel();
301
302
        // return response
303
        $response->setData(collect($this->model->getFillable()));
304
        $response->setMessage($this->getTrans('create', 'successful'));
305
        return SmartResponse::response($response);
306
    }
307
308
    /**
309
     * Store a newly created resource in storage.
310
     *
311
     * @param  \Illuminate\Http\Request $request
312
     * @return \Illuminate\Http\JsonResponse
313
     */
314
    public function store(Request $request)
315
    {
316
        // handle permission
317
        $request = $this->handlePermission($request, __FUNCTION__);
318
319
        // Create Response Model
320
        $response = new ResponseModel();
321
322
        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...
323
            $userId = 1;
324
        }
325
326
        //add author id into the request if doesn't exist
327
        if (is_null($request->get('author_id'))) {
328
            $request['author_id'] = $userId;
329
        }
330
331
        //add user id into the request if doesn't exist
332
        if (is_null($request->get('user_id'))) {
333
            $request['user_id'] = $userId;
334
        }
335
336
        $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

336
        $validationErrors = $this->checkRequestValidation(/** @scrutinizer ignore-type */ $request, $this->storeValidateArray);
Loading history...
337
338
        if ($validationErrors != null) {
339
            if (env('APP_DEBUG', false)) {
340
                $response->setData(collect($validationErrors->toArray()));
341
            }
342
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
343
            $response->setStatus(false);
344
            $response->setError(99);
345
            return SmartResponse::response($response);
346
347
        }
348
349
        try {
350
            // get result of model creation
351
            $result = $this->model->create($request->all());
352
            // sync many to many relation
353
            foreach ($this->pivotFields as $pivotField) {
354
                if (collect($request[$pivotField])->count()) {
355
                    $pivotField = (new StringHelper())->toCamel($pivotField);
356
                    $this->model->find($result['id'])->$pivotField()->sync(json_decode($request[$pivotField]));
357
                }
358
            }
359
            $response->setMessage($this->getTrans('store', 'successful'));
360
361
362
            $response->setData($this->model
363
                ->where($this->model->getKeyName(), $result['id'])
364
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
365
                ->get());
366
367
            $response->setStatus(true);
368
        } catch (QueryException $exception) {
369
            $response->setError($exception->getCode());
370
            $response->setMessage($this->getTrans('store', 'failed'));
371
            $response->setStatus(false);
372
            if (env('APP_DEBUG', false)) {
373
                $response->setData(collect($exception->getMessage()));
374
            }
375
        }
376
        return SmartResponse::response($response);
377
    }
378
379
    /**
380
     * Display the specdefaultied resource.
381
     *
382
     * @param  int $id
383
     * @return \Illuminate\Http\JsonResponse
384
     */
385
    public function show($id)
386
    {
387
        // Create Response Model
388
        $response = new ResponseModel();
389
390
        // try to get data
391
        try {
392
            $response->setMessage($this->getTrans('show', 'successful'));
393
            $response->setData(collect($this->model->findOrFail($id)));
394
395
            // catch exception
396
        } catch (ModelNotFoundException $exception) {
397
            $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

397
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
398
            $response->setMessage($this->getTrans('show', 'failed'));
399
            $response->setStatus(false);
400
            if (env('APP_DEBUG', false)) {
401
                $response->setData(collect($exception->getMessage()));
402
            }
403
        }
404
        return SmartResponse::response($response);
405
    }
406
407
    /**
408
     * Show the form for editing the specified resource.
409
     *
410
     * @param  int $id
411
     * @return \Illuminate\Http\JsonResponse
412
     */
413
    public function edit($id)
414
    {
415
        // Create Response Model
416
        $response = new ResponseModel();
417
418
        try {
419
            $response->setMessage($this->getTrans('edit', 'successful'));
420
            $response->setData($this->model
421
                ->where($this->model->getKeyName(), $id)
422
                ->with(collect($this->editLoad)->count() == 0 ? $this->indexLoad : $this->editLoad)
423
                ->get());
424
425
        } catch (ModelNotFoundException $exception) {
426
            $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

426
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
427
            $response->setMessage($this->getTrans('edit', 'failed'));
428
            $response->setStatus(false);
429
            if (env('APP_DEBUG', false)) {
430
                $response->setData(collect($exception->getMessage()));
431
            }
432
433
        }
434
435
        return SmartResponse::response($response);
436
    }
437
438
    /**
439
     * Update the specified resource in storage.
440
     *
441
     * @param  \Illuminate\Http\Request $request
442
     * @param  int $id
443
     * @return \Illuminate\Http\JsonResponse
444
     */
445
    public function update(Request $request, $id)
446
    {
447
448
449
        // Create Response Model
450
        $response = new ResponseModel();
451
452
        $modelFilter = [
453
            [$this->model->getKeyName(), '=', $id],
454
        ];
455
456
        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
457
        if ($validationErrors != null) {
458
            if (env('APP_DEBUG', false)) {
459
                $response->setData(collect($validationErrors->toArray()));
460
            }
461
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
462
            $response->setStatus(false);
463
            $response->setError(99);
464
            return SmartResponse::response($response);
465
466
        }
467
468
        try {
469
            // sync many to many relation
470
            foreach ($this->pivotFields as $pivotField) {
471
                if (collect($request[$pivotField])->count()) {
472
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
473
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
474
                }
475
            }
476
            //get result of update
477
            $result = $this->model->findOrFail($id)->update($request->all());
478
479
            // return response
480
            $response->setData($this->model
481
                ->where($modelFilter)
482
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
483
                ->get());
484
            $response->setMessage(
485
                $this->getTrans('update', 'successful1') .
0 ignored issues
show
Bug introduced by
Are you sure $this->getTrans('update', '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

485
                /** @scrutinizer ignore-type */ $this->getTrans('update', 'successful1') .
Loading history...
486
                $result .
487
                $this->getTrans('update', 'successful2')
0 ignored issues
show
Bug introduced by
Are you sure $this->getTrans('update', '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

487
                /** @scrutinizer ignore-type */ $this->getTrans('update', 'successful2')
Loading history...
488
            );
489
490
        } catch (ModelNotFoundException $exception) {
491
            $response->setStatus(false);
492
            $response->setMessage($this->getTrans('update', 'model_not_found'));
493
            $response->setError($exception->getCode());
494
            if (env('APP_DEBUG', false)) {
495
                $response->setData(collect($exception->getMessage()));
496
            }
497
498
        } catch (QueryException $exception) {
499
            $response->setStatus(false);
500
            $response->setMessage($this->getTrans('update', 'failed'));
501
            $response->setError($exception->getCode());
502
            if (env('APP_DEBUG', false)) {
503
                $response->setData(collect($exception->getMessage()));
504
            }
505
506
        }
507
508
        return SmartResponse::response($response);
509
    }
510
511
    /**
512
     * Remove the specified resource from storage.
513
     *
514
     * @param  int $id
515
     * @return \Illuminate\Http\JsonResponse
516
     */
517
    public function destroy($id)
518
    {
519
        // Create Response Model
520
        $response = new ResponseModel();
521
522
        try {
523
            $response->setData(collect($this->model->findOrFail($id)->delete()));
524
            $response->setMessage($this->getTrans('destroy', 'successful'));
525
526
        } catch (ModelNotFoundException $exception) {
527
            $response->setMessage($this->getTrans('destroy', 'successful'));
528
            $response->setStatus(false);
529
            $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

529
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
530
            if (env('APP_DEBUG', false)) {
531
                $response->setData(collect($exception->getMessage()));
532
            }
533
534
        }
535
536
        return SmartResponse::response($response);
537
    }
538
539
    /**
540
     * @param $method
541
     * @param $status
542
     * @return array|\Illuminate\Contracts\Translation\Translator|null|string
543
     */
544
    public function getTrans($method, $status)
545
    {
546
        return trans('laravel_smart_restful::' . $this->LOCALE_PREFIX . '.' . get_class($this->model) . '.' . $method . '.' . $status);
547
    }
548
549
    /**
550
     * set local
551
     */
552
    public function setLocale()
553
    {
554
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
555
            \App::setLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
556
        }
557
    }
558
559
    public function handlePermission(Request $request, $functionName, $params = [])
560
    {
561
        if (!isset($request['permission_type'])) {
562
            $request['permission_type'] = $this->DEFAULT_PERMISSION_TYPE;
563
        }
564
        switch ($request['permission_type']) {
565
            case 'admin':
566
                return $this->handleAdminPermission($request, $functionName, $params);
567
            case 'branch':
568
                return $this->handleBranchPermission($request, $functionName, $params);
569
            case 'own':
570
                return $this->handleOwnPermission($request, $functionName, $params);
571
            case 'guest':
572
                return $this->handleGuestPermission($request, $functionName, $params);
573
            default:
574
                return $params;
575
        }
576
    }
577
578
    public function handleAdminPermission(Request $request, $functionName, $params = [])
579
    {
580
        switch ($functionName) {
581
            case 'index':
582
            case 'store':
583
            case 'show':
584
            case 'edit':
585
            case 'create':
586
            case 'update':
587
            case 'destroy':
588
            default:
589
                return $params;
590
        }
591
    }
592
593
    public function handleBranchPermission(Request $request, $functionName, $params)
594
    {
595
        switch ($functionName) {
596
            case 'index':
597
            case 'store':
598
            case 'show':
599
            case 'edit':
600
            case 'create':
601
            case 'update':
602
            case 'destroy':
603
            default:
604
                return $params;
605
        }
606
    }
607
608
    public function handleOwnPermission(Request $request, $functionName, $params)
609
    {
610
        switch ($functionName) {
611
            case 'index':
612
                if (isset($request['filters'])) {
613
                    $filters = json_decode($request['filters'], true);
614
                } else {
615
                    $filters = [];
616
                }
617
                array_push($filters, [
618
                    "key" => "owner_id",
619
                    "operator" => "=",
620
                    "value" => auth()->id(),
621
                ]);
622
                $request['filters'] = json_encode($filters);
623
                return $request;
624
            case 'store':
625
                $request['owner_id'] = auth()->id();
626
                return $request;
627
            case 'show':
628
                $filters = [];
629
                array_push($filters, [
630
                    "key" => "owner_id",
631
                    "operator" => "=",
632
                    "value" => auth()->id(),
633
                ]);
634
                $request['permission_filters'] = json_encode($filters);
635
                return $request;
636
            case 'edit':
637
                $filters = [];
638
                array_push($filters, [
639
                    "key" => "owner_id",
640
                    "operator" => "=",
641
                    "value" => auth()->id(),
642
                ]);
643
                $request['permission_filters'] = json_encode($filters);
644
                return $request;
645
            case 'create':
646
            case 'update':
647
                $filters = [];
648
                array_push($filters, [
649
                    "key" => "owner_id",
650
                    "operator" => "=",
651
                    "value" => auth()->id(),
652
                ]);
653
                $request['permission_filters'] = json_encode($filters);
654
                return $request;
655
            case 'destroy':
656
                $filters = [];
657
                array_push($filters, [
658
                    "key" => "owner_id",
659
                    "operator" => "=",
660
                    "value" => auth()->id(),
661
                ]);
662
                $request['permission_filters'] = json_encode($filters);
663
                return $request;
664
            default:
665
                return $params;
666
        }
667
    }
668
669
    public function handleGuestPermission(Request $request, $functionName, $params)
670
    {
671
        switch ($functionName) {
672
            case 'index':
673
            case 'store':
674
            case 'show':
675
            case 'edit':
676
            case 'create':
677
            case 'update':
678
            case 'destroy':
679
            default:
680
                return $params;
681
        }
682
    }
683
684
}