Passed
Push — master ( 930fe0...265458 )
by Babak
02:08
created

BaseController::addFilter()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 4
dl 0
loc 12
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\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 $permissionType = 'admin';
39
40
    /**
41
     * permission types 'admin'|'branch'|'own'|'guest'
42
     *
43
     * @var string
44
     */
45
    protected $groupTitle = null;
46
47
    /**
48
     * @var string
49
     */
50
    protected $localPrefix = '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
        list($request,$filters) = $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);
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);
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
        $filters = [];
397
//        // handle permission
398
//        $filters = $this->handlePermission(__FUNCTION__);
399
400
        // Create Response Model
401
        $response = new ResponseModel();
402
403
        // try to get data
404
        try {
405
            $response->setMessage($this->getTrans('show', 'successful'));
406
407
            // add filter to get desired record
408
            array_push($filters,
409
                [$this->model->getKeyName(), '=', $id]
410
            );
411
            $data = $this->model
412
                ->where($filters)
413
                ->get();
414
            $response->setData($data);
415
416
            // catch exception
417
        } catch (Exception $exception) {
418
            $response->setError($exception->getCode());
419
            $response->setMessage($this->getTrans('show', 'failed'));
420
            $response->setStatus(false);
421
            if (env('APP_DEBUG', false)) {
422
                $response->setData(collect($exception->getMessage()));
423
            }
424
        }
425
        return SmartResponse::response($response);
426
    }
427
428
    /**
429
     * Show the form for editing the specified resource.
430
     *
431
     * @param  int $id
432
     * @return \Illuminate\Http\JsonResponse
433
     */
434
    public function edit($id)
435
    {
436
        $filters = [];
437
//        // handle permission
438
//        $filters = $this->handlePermission(__FUNCTION__);
439
440
        // Create Response Model
441
        $response = new ResponseModel();
442
443
        try {
444
            $response->setMessage($this->getTrans('edit', 'successful'));
445
446
            // add filter to get desired record
447
            array_push($filters,
448
                [$this->model->getKeyName(), '=', $id]
449
            );
450
            $data = $this->model
451
                ->where($filters)
452
                ->with(collect($this->editLoad)->count() == 0 ? $this->indexLoad : $this->editLoad)
453
                ->get();
454
            $response->setData($data);
455
456
        } catch (ModelNotFoundException $exception) {
457
            $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

457
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
458
            $response->setMessage($this->getTrans('edit', 'failed'));
459
            $response->setStatus(false);
460
            if (env('APP_DEBUG', false)) {
461
                $response->setData(collect($exception->getMessage()));
462
            }
463
464
        }
465
466
        return SmartResponse::response($response);
467
    }
468
469
    /**
470
     * Update the specified resource in storage.
471
     *
472
     * @param  \Illuminate\Http\Request $request
473
     * @param  int $id
474
     * @return \Illuminate\Http\JsonResponse
475
     */
476
    public function update(Request $request, $id)
477
    {
478
        // Handle permission
479
//        $request = $this->handlePermission(__FUNCTION__,$request);
480
//        if ($request->has('permission_filters')){
481
//            $filters = $request['permission_filters'];
482
//        }else{
483
        $filters = [];
484
//        }
485
486
        // Create Response Model
487
        $response = new ResponseModel();
488
489
        // Filters
490
        array_push($filters,
491
            [$this->model->getKeyName(), '=', $id]
492
        );
493
494
        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
495
        if ($validationErrors != null) {
496
            if (env('APP_DEBUG', false)) {
497
                $response->setData(collect($validationErrors->toArray()));
498
            }
499
            $response->setMessage($this->getTrans(__FUNCTION__, 'validation_failed'));
500
            $response->setStatus(false);
501
            $response->setError(99);
502
            return SmartResponse::response($response);
503
504
        }
505
506
        try {
507
            // sync many to many relation
508
            foreach ($this->pivotFields as $pivotField) {
509
                if (collect($request[$pivotField])->count()) {
510
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
511
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
512
                }
513
            }
514
            //get result of update
515
            $result = $this->model->where($filters)->firstOrFail()->update($request->all());
516
517
            // return response
518
            $response->setData($this->model
519
                ->where($filters)
520
                ->with(collect($this->updateLoad)->count() == 0 ? $this->indexLoad : $this->updateLoad)
521
                ->get());
522
            $response->setMessage(
523
                $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

523
                /** @scrutinizer ignore-type */ $this->getTrans(__FUNCTION__, 'successful1') .
Loading history...
524
                $result .
525
                $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

525
                /** @scrutinizer ignore-type */ $this->getTrans(__FUNCTION__, 'successful2')
Loading history...
526
            );
527
528
        } catch (ModelNotFoundException $exception) {
529
            $response->setStatus(false);
530
            $response->setMessage($this->getTrans(__FUNCTION__, 'model_not_found'));
531
            $response->setError($exception->getCode());
532
            if (env('APP_DEBUG', false)) {
533
                $response->setData(collect($exception->getMessage()));
534
            }
535
536
        } catch (QueryException $exception) {
537
            $response->setStatus(false);
538
            $response->setMessage($this->getTrans(__FUNCTION__, 'failed'));
539
            $response->setError($exception->getCode());
540
            if (env('APP_DEBUG', false)) {
541
                $response->setData(collect($exception->getMessage()));
542
            }
543
544
        }
545
546
        return SmartResponse::response($response);
547
    }
548
549
    /**
550
     * Remove the specified resource from storage.
551
     *
552
     * @param  int $id
553
     * @return \Illuminate\Http\JsonResponse
554
     */
555
    public function destroy($id)
556
    {
557
        // Create Response Model
558
        $response = new ResponseModel();
559
560
        try {
561
            $response->setData(collect($this->model->findOrFail($id)->delete()));
562
            $response->setMessage($this->getTrans('destroy', 'successful'));
563
564
        } catch (ModelNotFoundException $exception) {
565
            $response->setMessage($this->getTrans('destroy', 'successful'));
566
            $response->setStatus(false);
567
            $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

567
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
568
            if (env('APP_DEBUG', false)) {
569
                $response->setData(collect($exception->getMessage()));
570
            }
571
572
        }
573
574
        return SmartResponse::response($response);
575
    }
576
577
    /**
578
     * @param $method
579
     * @param $status
580
     * @return array|\Illuminate\Contracts\Translation\Translator|null|string
581
     */
582
    public function getTrans($method, $status)
583
    {
584
        return trans('laravel_smart_restful::' . $this->localPrefix . '.' . get_class($this->model) . '.' . $method . '.' . $status);
585
    }
586
587
    /**
588
     * set locale
589
     */
590
    public function setLocale()
591
    {
592
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
593
            app('translator')->setLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
594
        }
595
    }
596
597
    /**
598
     * @param $functionName
599
     * @param Request|null $request
600
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
601
     * @param array $params
602
     * @return mixed
603
     */
604
    public function handlePermission($functionName, Request $request = null, $id = null, $params = [])
605
    {
606
        $filters = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $filters is dead and can be removed.
Loading history...
607
608
        if (!is_null($request)) {
609
            if ($request->has('permission_type')) {
610
                $this->permissionType = $request['permission_type'];
611
            }
612
        }
613
614
        $methodName =
615
            'handle' .
616
            (new StringHelper())->upperFirstLetter($functionName) .
617
            (new StringHelper())->upperFirstLetter($this->permissionType) .
618
            'Permission';
619
620
        return $this->$methodName($request, $id);
621
    }
622
623
    /**
624
     * @param Request $request
625
     * @param $id
626
     * @return array
627
     */
628
    public function handleIndexAdminPermission(Request $request, $id)
629
    {
630
        return [$request, null];
631
    }
632
633
    /**
634
     * @param Request $request
635
     * @param $id
636
     * @return array
637
     */
638
    public function handleIndexBranchPermission(Request $request, $id)
639
    {
640
        if (isset($request['filters'])) {
641
            $filters = json_decode($request['filters'], true);
642
        } else {
643
            $filters = [];
644
        }
645
646
        $filters = $this->addFilter($filters, 'owner_id', '=', auth()->id());
647
648
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
649
            $filters = $this->addFilter($filters, 'group.title', '=', $this->groupTitle);
650
        }
651
652
        $request['filters'] = json_encode($filters);
653
        return [$request, $filters];
654
    }
655
656
    /**
657
     * @param Request $request
658
     * @param $id
659
     * @return array
660
     */
661
    public function handleIndexOwnPermission(Request $request, $id)
662
    {
663
        if (isset($request['filters'])) {
664
            $filters = json_decode($request['filters'], true);
665
        } else {
666
            $filters = [];
667
        }
668
669
        $filters = $this->addFilter($filters, 'owner_id', '=', auth()->id());
670
671
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
672
            $filters = $this->addFilter($filters, 'group.title', '=', $this->groupTitle);
673
        }
674
675
        $request['filters'] = json_encode($filters);
676
677
        return [$request, $filters];
678
    }
679
680
    /**
681
     * @param Request $request
682
     * @param $id
683
     * @return array
684
     */
685
    public function handleIndexGuestPermission(Request $request, $id)
686
    {
687
        if (isset($request['filters'])) {
688
            $filters = json_decode($request['filters'], true);
689
        } else {
690
            $filters = [];
691
        }
692
693
        $filters = $this->addFilter($filters, 'owner_id', '=', null);
694
695
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
696
            $filters = $this->addFilter($filters, 'group.title', '=', null);
697
        }
698
699
        $request['filters'] = json_encode($filters);
700
701
        return [$request, $filters];
702
    }
703
704
    /**
705
     * @param Request $request
706
     * @param $id
707
     * @return array
708
     */
709
    public function handleStoreAdminPermission(Request $request, $id)
710
    {
711
        $request['group_id'] = null;
712
713
        $request['owner_id'] = auth()->id();
714
715
        return [$request, null];
716
    }
717
718
    /**
719
     * @param Request $request
720
     * @param $id
721
     * @return array
722
     */
723
    public function handleStoreBranchPermission(Request $request, $id)
724
    {
725
        // check for group of user
726
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
727
            // get group model
728
            $group = new Group();
729
            $group = $group->where('title', $this->groupTitle)->first();
730
            $request['group_id'] = $group['id'];
731
        }
732
733
        $request['owner_id'] = auth()->id();
734
735
        return [$request, null];
736
    }
737
738
    /**
739
     * @param Request $request
740
     * @param $id
741
     * @return array
742
     */
743
    public function handleStoreOwnPermission(Request $request, $id)
744
    {
745
        // check for group of user
746
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
747
            // get group model
748
            $group = new Group();
749
            $group = $group->where('title', $this->groupTitle)->first();
750
            $request['group_id'] = $group['id'];
751
        }
752
753
        $request['owner_id'] = auth()->id();
754
755
        return [$request, null];
756
    }
757
758
    /**
759
     * @param Request $request
760
     * @param $id
761
     * @return array
762
     */
763
    public function handleStoreGuestPermission(Request $request, $id)
764
    {
765
        $request['owner_id'] = null;
766
767
        return [$request, null];
768
    }
769
770
    public function handleShowAdminPermission(Request $request,$id)
771
    {
772
        $filters = [];
773
774
        return [$request,$filters];
775
    }
776
777
    public function handleShowBranchPermission(Request $request,$id)
778
    {
779
        $filters = [];
780
        array_push($filters,
781
            ["owner_id", "=", auth()->id()]
782
        );
783
784
        // check for group of user
785
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
786
787
            // get group model
788
            $group = new Group();
789
            $group = $group->where('title', $this->groupTitle)->first();
790
791
            // put group_id filter
792
            array_push($filters,
793
                ['group_id', '=', $group['id']]);
794
        }
795
796
        return [$request,$filters];
797
    }
798
799
    public function handleShowOwnPermission(Request $request,$id)
800
    {
801
        $filters = [];
802
        array_push($filters,
803
            ["owner_id", "=", auth()->id()]
804
        );
805
806
        // check for group of user
807
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
808
809
            // get group model
810
            $group = new Group();
811
            $group = $group->where('title', $this->groupTitle)->first();
812
813
            // put group_id filter
814
            array_push($filters,
815
                ['group_id', '=', $group['id']]);
816
        }
817
818
        return [$request,$filters];
819
    }
820
821
    public function handleShowGuestPermission(Request $request,$id)
822
    {
823
        $filters = [];
824
        array_push($filters,
825
            ["owner_id", "=", auth()->id()]
826
        );
827
828
        // check for group of user
829
        if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
830
831
            // get group model
832
            $group = new Group();
833
            $group = $group->where('title', $this->groupTitle)->first();
834
835
            // put group_id filter
836
            array_push($filters,
837
                ['group_id', '=', $group['id']]);
838
        }
839
840
        return [$request,$filters];
841
    }
842
843
    public function handleOwnPermission($functionName, Request $request = null, $params)
844
    {
845
        switch ($functionName) {
846
            case 'index':
847
            case 'store':
848
            case 'show':
849
            case 'edit':
850
                $filters = [];
851
                array_push($filters,
852
                    ["owner_id", "=", auth()->id()]
853
                );
854
855
                // check gor group of user
856
                if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
857
                    // get group model
858
                    $group = new Group();
859
                    $group = $group->where('title', $this->groupTitle)->first();
860
861
                    // put group_id filter
862
                    array_push($filters,
863
                        ['group_id', '=', $group['id']]);
864
                }
865
866
                return $filters;
867
            case 'create':
868
            case 'update':
869
870
                $filters = [];
871
                // put to filter
872
                array_push($filters,
873
                    ["owner_id", "=", auth()->id()]
874
                );
875
876
                // put to request
877
                $request['owner_id'] = auth()->id();
878
879
                // check for group of user
880
                if (!is_null($this->groupTitle)) {
0 ignored issues
show
introduced by
The condition is_null($this->groupTitle) is always false.
Loading history...
881
                    // get group model
882
                    $group = new Group();
883
                    $group = $group->where('title', $this->groupTitle)->first();
884
885
                    // put group_id filter
886
                    array_push($filters,
887
                        ['group_id', '=', $group['id']]);
888
889
                    // put to request
890
                    $request['group_id'] = $group['id'];
891
                }
892
893
                $request['permission_filters'] = $filters;
894
                return $request;
895
            case 'destroy':
896
                $filters = [];
897
                array_push($filters,
898
                    ["owner_id", "=", auth()->id()],
899
                    ["group_id", "=", $this->groupTitle]
900
                );
901
                return $filters;
902
            default:
903
                return $params;
904
        }
905
    }
906
907
//    public function handleGuestPermission($functionName, Request $request = null, $params)
908
//    {
909
//        return [];
910
//        switch ($functionName) {
911
//            case 'index':
912
//            case 'store':
913
//            case 'show':
914
//            case 'edit':
915
//            case 'create':
916
//            case 'update':
917
//            case 'destroy':
918
//            default:
919
//                return $params;
920
//        }
921
//    }
922
923
//    /**
924
//     * @param $functionName
925
//     * @param Request|null $request
926
//     * @param array $params
927
//     * @return array
928
//     */
929
//    public function handleAdminPermission($functionName, Request $request = null, $params = [])
930
//    {
931
//        return [];
932
//        switch ($functionName) {
933
//            case 'index':
934
//            case 'store':
935
//            case 'show':
936
//            case 'edit':
937
//            case 'create':
938
//            case 'update':
939
//            case 'destroy':
940
//            default:
941
//                return $params;
942
//        }
943
//    }
944
945
//    public function handleBranchPermission($functionName, Request $request = null, $params)
946
//    {
947
//        return [];
948
//        switch ($functionName) {
949
//            case 'index':
950
//            case 'store':
951
//            case 'show':
952
//            case 'edit':
953
//            case 'create':
954
//            case 'update':
955
//            case 'destroy':
956
//            default:
957
//                return $params;
958
//        }
959
//    }
960
961
    /**
962
     * @param array $filters
963
     * @param $key
964
     * @param $operator
965
     * @param $value
966
     * @return array
967
     */
968
    public function addFilter(array $filters, $key, $operator, $value)
969
    {
970
        if (count(explode('.', $key)) == 1 && $this->filedExist($key)) {
971
            array_push($filters,
972
                [
973
                    'key' => $key,
974
                    'operator' => $operator,
975
                    'value' => $value,
976
                ]
977
            );
978
        }
979
        return $filters;
980
    }
981
982
    /**
983
     * @param $key
984
     * @return bool
985
     */
986
    public function filedExist($key)
987
    {
988
        return in_array($key, $this->model->getFillable());
989
    }
990
991
    /**
992
     * @return string
993
     */
994
    public function getLocalPrefix(): string
995
    {
996
        return $this->localPrefix;
997
    }
998
999
    /**
1000
     * @param string $localPrefix
1001
     */
1002
    public function setLocalPrefix(string $localPrefix)
1003
    {
1004
        $this->localPrefix = $localPrefix;
1005
    }
1006
}