Completed
Push — master ( 4bee84...d80c72 )
by Babak
07:42
created

BaseController::index()   B

Complexity

Conditions 9
Paths 92

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 92
nop 1
dl 0
loc 57
rs 7.3826
c 0
b 0
f 0

How to fix   Long Method   

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\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...
12
use Illuminate\Database\Eloquent\ModelNotFoundException;
13
use Illuminate\Database\QueryException;
14
use Illuminate\Http\Request;
15
use Illuminate\Support\MessageBag;
16
use Illuminate\Support\Facades\Validator;
17
18
19
class BaseController extends Controller
20
{
21
    /**
22
     * to use this class
23
     * create message list as messages in message file
24
     * override __constructor and define your model
25
     * define your rules for index,store and update
26
     */
27
28
    /**
29
     * @var array
30
     */
31
    protected $pivotFields = [];
32
33
    /**
34
     * @var array
35
     */
36
    protected $uniqueFields = [];
37
38
    /**
39
     * @var bool|string
40
     */
41
    protected $modelName;
42
43
    /**
44
     * @var string
45
     */
46
    protected $messagePrefix = 'messages.api.v1.';
47
48
    /**
49
     * this model
50
     */
51
    protected $model;
52
53
    /**
54
     * index request validator rules
55
     *
56
     * @var array
57
     */
58
    protected $indexValidateArray = [
59
        //
60
    ];
61
62
    /**
63
     * array of relationship for eager loading
64
     *
65
     * @var array
66
     */
67
    protected $indexLoad = [
68
        //
69
    ];
70
71
    /**
72
     * array of relationship for eager loading
73
     *
74
     * @var array
75
     */
76
    protected $editLoad = [
77
        //
78
    ];
79
80
    /**
81
     * array of relationship for eager loading
82
     *
83
     * @var array
84
     */
85
    protected $updateLoad = [
86
        //
87
    ];
88
89
    /**
90
     * store request validator rules
91
     *
92
     * @var array
93
     */
94
    protected $storeValidateArray = [
95
        //
96
    ];
97
98
    /**
99
     * update request validator rules
100
     *
101
     * @var array
102
     */
103
    protected $updateValidateArray = [
104
        //
105
    ];
106
107
    protected $middlewareParams = [];
108
109
    /**
110
     * defaultController constructor.
111
     */
112
    public function __construct()
113
    {
114
//        dd("I have closest relationship with all US celebrities");
115
        $this->model = new $this->modelName();
116
        $this->middleware($this->middlewareParams);
117
    }
118
119
    /**
120
     * Display a listing of the resource.
121
     *
122
     * @param Request $request
123
     * @return string
124
     */
125
    public function index(Request $request)
126
    {
127
        // create response model
128
        $response = new ResponseModel();
129
130
        //set default pagination
131
        if (is_null($request['page']['size'])) {
132
            $request['page'] = ['size' => config('json-api-paginate.default_results_per_page')];
133
        }
134
135
        //set default ordering
136
        if (is_null($request['order_by'])) {
137
            $request['order_by'] = "{\"field\":\"id\",\"operator\":\"Desc\"}";
138
        }
139
140
        $validationErrors = $this->checkRequestValidation($request, $this->indexValidateArray);
141
        if ($validationErrors != null) {
142
143
            // return response
144
            $response->setData(collect($validationErrors->toArray()));
145
            $response->setMessage("Validation Failed");
146
            $response->setStatus(false);
147
            $response->setError(99);
148
            return SmartResponse::response($response);
149
        }
150
        try {
151
            $data = $request->get('query') != null ?
152
                $this->model
153
                    ->whereKey(collect($this->model
154
                        ->search(($request->get('query')))
155
                        ->raw())->get('ids')) :
156
                $this->model;
157
            if (array_key_exists('file', $request->toArray())) {
158
                //TODO add relation on top if here and create a tree flatter array in array helper
159
                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...
160
                    'store_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
161
                    'download_format' => $request->get('file') == null ? 'xls' : $request->get('file'),
162
                ])->table($data->get()->toArray())->createExcelFile()->download();
163
            }
164
            $data = $data->with($this->indexLoad);
165
166
            $data = (new QueryHelper())->deepFilter($data, (new RequestHelper())->getCollectFromJson($request['filters']));
167
            $data = (new QueryHelper())->orderBy($data, (new RequestHelper())->getCollectFromJson($request['order_by']));
168
169
            // return response
170
            $response->setData(collect($data->jsonPaginate()));
171
            $response->setMessage("Successful");
172
            return SmartResponse::response($response);
173
174
        } catch (QueryException $exception) {
175
176
            // return response
177
            $response->setData(collect($exception->getMessage()));
178
            $response->setError($exception->getCode());
179
            $response->setMessage("Failed");
180
            $response->setStatus(false);
181
            return SmartResponse::response($response);
182
        }
183
    }
184
185
    public function checkRequestValidation(Request $request, $validationArray)
186
    {
187
        $requestParams = $request->toArray();
188
        $validator = Validator::make($request->all(), $validationArray);
189
        if ($validator->fails()) {
190
            return $validator->errors();
191
        }
192
        if (is_numeric(array_search($request->getMethod(), ["POST", "PUT", "PATCH"]))) {
193
            $errors = new MessageBag();
194
            foreach ($requestParams as $requestParamKey => $requestParamValue) {
195
                if (is_numeric(array_search($requestParamKey, $this->uniqueFields))) {
196
                    if ($this->checkExistUniqueRecord($requestParamKey, $requestParamValue)) {
197
                        $errors->add($requestParamKey, 'This ' . $requestParamKey . ' is exist try another.');
198
                    }
199
                }
200
            }
201
            if (collect($errors)->count() > 0) {
202
                return $errors;
203
            }
204
        }
205
        return null;
206
    }
207
208
    /**
209
     * @param $key
210
     * @param $value
211
     * @return bool
212
     */
213
    public function checkExistUniqueRecord($key, $value)
214
    {
215
        if ($this->model->where($key, $value)->count()) {
216
            return true;
217
        }
218
        return false;
219
    }
220
221
    /**
222
     * @param $status
223
     * @return mixed
224
     */
225
    public function message($status)
226
    {
227
        $key = $this->messagePrefix . $this->modelName . '.' . debug_backtrace()[1]['function'] . '.' . $status;
228
        return $this->getMessageFromFile($key);
229
    }
230
231
    /**
232
     * @param $key
233
     * @return mixed
234
     */
235
    public function getMessageFromFile($key)
236
    {
237
        return config($key);
238
    }
239
240
    /**
241
     * Show the form for creating a new resource.
242
     *
243
     * @return \Illuminate\Http\JsonResponse
244
     */
245
    public function create()
246
    {
247
        // Create Response Model
248
        $response = new ResponseModel();
249
250
        // return response
251
        $response->setData(collect($this->model->getFillable()));
252
        $response->setMessage("Successful");
253
        return SmartResponse::response($response);
254
    }
255
256
    /**
257
     * Store a newly created resource in storage.
258
     *
259
     * @param  \Illuminate\Http\Request $request
260
     * @return \Illuminate\Http\JsonResponse
261
     */
262
    public function store(Request $request)
263
    {
264
        // Create Response Model
265
        $response = new ResponseModel();
266
267
        // TODO must set access in middle ware
268
        //get user id
269
        $userId = auth()->id();
270
271
        //add author id into the request if doesn't exist
272
        if (isset($request['author_id'])) {
273
            if (is_null($request['author_id'])) {
274
                $request['author_id'] = $userId;
275
            }
276
        } else {
277
            $request['author_id'] = $userId;
278
        }
279
280
        //add user id into the request if doesn't exist
281
        if (isset($request['user_id'])) {
282
            if (is_null($request['user_id'])) {
283
                $request['user_id'] = $userId;
284
            }
285
        } else {
286
            $request['user_id'] = $userId;
287
        }
288
289
        $validationErrors = $this->checkRequestValidation($request, $this->storeValidateArray);
290
        if ($validationErrors != null) {
291
            if (env('APP_DEBUG', false)) {
292
                $response->setMessage(json_encode($validationErrors->getMessages()));
293
            }
294
            $response->setStatus(false);
295
            return SmartResponse::response($response);
296
        }
297
        try {
298
            // get result of model creation
299
            $result = $this->model->create($request->all());
300
            // sync many to many relation
301
            foreach ($this->pivotFields as $pivotField) {
302
                if (collect($request[$pivotField])->count()) {
303
                    $pivotField = (new StringHelper())->toCamel($pivotField);
304
                    $this->model->find($result['id'])->$pivotField()->sync(json_decode($request[$pivotField]));
305
                }
306
            }
307
            $response->setMessage('successful');
308
            $response->setData(collect($result->toArray()));
309
            $response->setStatus(true);
310
            return SmartResponse::response($response);
311
        } catch (QueryException $exception) {
312
            if (env('APP_DEBUG', false)) {
313
                $response->setMessage($exception->getMessage());
314
            }
315
            $response->setStatus(false);
316
            return SmartResponse::response($response);
317
        }
318
    }
319
320
    /**
321
     * Display the specdefaultied resource.
322
     *
323
     * @param  int $id
324
     * @return \Illuminate\Http\Response
325
     */
326
    public function show($id)
327
    {
328
        // Create Response Model
329
        $response = new ResponseModel();
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
330
331
        try {
332
333
            return SmartResponse::json(
334
                $this->message('successful'),
335
                true,
336
                200,
337
                $this->model->findOrFail($id)
338
            );
339
        } catch (ModelNotFoundException $exception) {
340
            return SmartResponse::json(
341
                $this->message('failed'),
342
                false,
343
                200,
344
                $exception->getMessage()
345
            );
346
        }
347
    }
348
349
    /**
350
     * Show the form for editing the specified resource.
351
     *
352
     * @param  int $id
353
     * @return \Illuminate\Http\JsonResponse
354
     */
355
    public function edit($id)
356
    {
357
        // Create Response Model
358
        $response = new ResponseModel();
359
360
        try {
361
            $response->setMessage('Successful');
362
            $response->setData($this->model
363
                ->where($this->model->getKeyName(), $id)
364
                ->with(collect($this->editLoad)->count() == 0 ? $this->indexLoad : $this->editLoad)
365
                ->get());
366
            return SmartResponse::response($response);
367
        } catch (ModelNotFoundException $exception) {
368
            $response->setData(collect($exception->getMessage()));
369
            $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

369
            $response->setError(/** @scrutinizer ignore-type */ $exception->getCode());
Loading history...
370
            $response->setMessage('Failed');
371
            $response->setStatus(false);
372
            return SmartResponse::response($response);
373
        }
374
    }
375
376
    /**
377
     * Update the specified resource in storage.
378
     *
379
     * @param  \Illuminate\Http\Request $request
380
     * @param  int $id
381
     * @return \Illuminate\Http\JsonResponse
382
     */
383
    public function update(Request $request, $id)
384
    {
385
        // Create Response Model
386
        $response = new ResponseModel();
387
388
        $validationErrors = $this->checkRequestValidation($request, $this->updateValidateArray);
389
        if ($validationErrors != null) {
390
391
            // return response
392
            $response->setData(collect($validationErrors->toArray()));
393
            $response->setMessage("Validation Failed");
394
            $response->setStatus(false);
395
            $response->setError(99);
396
            return SmartResponse::response($response);
397
        }
398
        try {
399
            // sync many to many relation
400
            foreach ($this->pivotFields as $pivotField) {
401
                if (collect($request[$pivotField])->count()) {
402
                    $pivotMethod = (new StringHelper())->toCamel($pivotField);
403
                    $this->model->findOrFail($id)->$pivotMethod()->sync(json_decode($request[$pivotField], true));
404
                }
405
            }
406
            //get result of update
407
            $result = $this->model->findOrFail($id)->update($request->all());
408
409
            // return response
410
            $response->setData(collect(env('APP_DEBUG') ? $this->model->find($id) : []));
411
            $response->setMessage('Successful to change '.$result.' record');
412
            return SmartResponse::response($response);
413
414
415
        } catch (ModelNotFoundException $exception) {
416
417
418
            // return response
419
            $response->setData(collect($exception->getMessage()));
420
            $response->setStatus(false);
421
            $response->setMessage('Not found record');
422
423
            return SmartResponse::response($response);
424
425
        } catch (QueryException $exception) {
426
            // return response
427
            $response->setData(collect($exception->getMessage()));
428
            $response->setStatus(false);
429
            $response->setMessage('Failed');
430
431
            return SmartResponse::response($response);
432
        }
433
    }
434
435
    /**
436
     * Remove the specified resource from storage.
437
     *
438
     * @param  int $id
439
     * @return \Illuminate\Http\JsonResponse
440
     */
441
    public function destroy($id)
442
    {
443
        // Create Response Model
444
        $response = new ResponseModel();
445
446
        try {
447
            // return response
448
            $response->setData(collect($this->model->findOrFail($id)->delete()));
449
            $response->setMessage('Successful');
450
451
            return SmartResponse::response($response);
452
453
        } catch (ModelNotFoundException $exception) {
454
            // return response
455
            $response->setData(collect($exception->getMessage()));
456
            $response->setMessage('Failed');
457
            $response->setStatus(false);
458
            $response->setStatusCode($exception->getCode());
459
460
            return SmartResponse::response($response);
461
        }
462
    }
463
}