Completed
Push — master ( 20f323...6ae55b )
by Jan
05:32
created

AdminModuleController::update()   D

Complexity

Conditions 13
Paths 39

Size

Total Lines 125
Code Lines 33

Duplication

Lines 10
Ratio 8 %

Importance

Changes 0
Metric Value
dl 10
loc 125
rs 4.9922
c 0
b 0
f 0
cc 13
eloc 33
nc 39
nop 2

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Admin module controller
4
 * 
5
 * Basic parent controller for admin functions
6
 * 
7
 * @category Controller
8
 * @subpackage Admin
9
 * @package Olapus
10
 * @author Jan Drda <[email protected]>
11
 * @copyright Jan Drda
12
 * @license https://opensource.org/licenses/MIT MIT
13
 */
14
15
namespace App\Http\Controllers\Admin;
16
17
use App\Helpers;
18
use Illuminate\Http\Request;
19
use Illuminate\Support\Facades\Auth;
20
use Illuminate\Support\Facades\View;
21
use App\Http\Controllers\Controller;
22
use Illuminate\Database\Eloquent\Builder;
23
use Illuminate\Support\Facades\DB;
24
use Carbon\Carbon;
25
use App\Transaction;
26
use App\User;
27
28
class AdminModuleController extends Controller{
29
30
    /**
31
     * Module name
32
     * 
33
     * @var string 
34
     */
35
    protected $moduleName;
36
37
    /**
38
     * Module basic path
39
     * 
40
     * @var string
41
     */
42
    protected $moduleBasicRoute;
43
44
    /**
45
     * View basic path
46
     * 
47
     * @var string
48
     */
49
    protected $moduleBasicTemplatePath;
50
51
    /**
52
     * Model Class
53
     * 
54
     * @var string
55
     */
56
    protected $modelClass;
57
58
    /**
59
     * Rows to paginate
60
     * 
61
     * @var integer 
62
     */
63
    protected $paginateRows = NULL;
64
    
65
    /**
66
     * View variables to inject
67
     * 
68
     * @var array
69
     */
70
    protected $viewVariables = array();
71
    
72
    /**
73
     * Hidden fields for action
74
     * 
75
     * @var array 
76
     */
77
    protected $hiddenFieldsOnAction = array();
78
    
79
   /**
80
    * Binary fields to exclude from update
81
    * 
82
    * @var array 
83
    */
84
    protected $binaryFields = array();
85
86
    /**
87
     * Binary fields to exclude from update
88
     *
89
     * @var array
90
     */
91
    protected $dateTimeLocalFields = array();
92
    
93
    /**
94
     * Custom view
95
     * 
96
     * @var string 
97
     */
98
    protected $customView = NULL;
99
100
    /**
101
     * Constructor
102
     */
103
    public function __construct() {
104
105
        /**
106
         * Check if user is active
107
         */
108
       /* print_r(Auth::user());
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
109
        die;*/
110
111
        /**
112
         * Pagination handle
113
         */
114
        if ($this->paginateRows == NULL) {
115
116
            $this->paginateRows = env('ADMIN_PAGINATE', 10);
117
        }
118
119
        /**
120
         * Get module name
121
         */
122
        $temp = explode("\\", str_replace('Controller', '', get_called_class()));
123
        $this->moduleName = trim(last($temp));
124
        
125
        /**
126
         * Get model full name
127
         */
128
        $this->modelClass = '\\App\\' . $this->moduleName;
129
130
        /**
131
         * Set basic variables
132
         */
133
        $this->moduleBasicRoute = 'admin.' . lcfirst($this->moduleName);
134
        $this->moduleBasicTemplatePath = 'admin.modules.' . strtolower($this->moduleName);
135
136
        /**
137
         * Global template variables
138
         */
139
        View::share('moduleBasicRoute', $this->moduleBasicRoute);
140
        View::share('moduleBasicTemplatePath', $this->moduleBasicTemplatePath);
141
        View::share('moduleName', $this->moduleName);
142
143
        /**
144
         * Module name for blade
145
         */
146
        $temp = explode('.', $this->moduleBasicRoute);
147
        View::share('moduleNameBlade', strtolower($temp[0] . "_module_" . $temp[1]));
148
149
    }
150
151
    /**
152
     * Save transaction
153
     *
154
     * @param int $typeId
0 ignored issues
show
Bug introduced by
There is no parameter named $typeId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
155
     * @param string $text
0 ignored issues
show
Bug introduced by
There is no parameter named $text. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
156
     * @param $userId
157
     * @param $amount
158
     */
159 View Code Duplication
    protected function _saveTransation($status_id = 1, $user_id, $amount,
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
                                       $campaign_id = null, $payment_id = null, $recommendation_id = null){
161
162
        /**
163
         * Save transaction
164
         */
165
        $transaction = new Transaction();
166
        $transaction->transactionstatus_id = $status_id;
167
        $transaction->user_id = $user_id;
168
        $transaction->amount = $amount;
169
        $transaction->campaign_id = $campaign_id;
170
        $transaction->payment_id = $payment_id;
171
        $transaction->recommendation_id = $recommendation_id;
172
        $transaction->save();
173
174
        /**
175
         * Update user wallet
176
         */
177
        $user = User::find($user_id);
178
        $user->wallet = $user->wallet + $amount;
179
        $user->save();
180
    }
181
    
182
    /**
183
     * Save media to storage
184
     * 
185
     * @param object $object
186
     * @param Request $request
187
     * @param boolean $update
188
     * @return boolean
189
     */
190
    public function saveMediaToStorage($object, $request, $update = FALSE){
191
        
192
        return FALSE;
193
    }
194
    
195
    /**
196
     * Get number of pagination rows
197
     * 
198
     * @return integer
199
     */
200
    public function getRowsToPaginate() {
201
202
        if ($this->paginateRows == NULL) {
203
204
            return env('ADMIN_PAGINATE', 10);
205
        }
206
        else{
207
208
            return $this->paginateRows;
209
        }
210
    }
211
    
212
    /**
213
     * Associate relationships to other table
214
     * 
215
     * @param object $object
216
     * @param Request $request
217
     */
218
    public function associateRelationships($object, Request $request){
219
        
220
    }
221
    
222
    /**
223
     * Associate relationships to other table, where ID if object must be present
224
     * 
225
     * @param object $object
226
     * @param Request $request
227
     */
228
    public function associateRelationshipsWithID($object, Request $request){
229
        
230
    }
231
232
    /**
233
     * Reset cache 
234
     * 
235
     * @param object $object
236
     */
237
    public function resetCache($object){
238
        
239
    }
240
241
    /**
242
     * Change ar result if necessary
243
     *
244
     * @param $arResult
245
     * @return mixed
246
     */
247
    public function changeEditResultField($arResult){
248
        return $arResult;
249
    }
250
251
    /**
252
     * Display a listing of the resource
253
     * 
254
     * @param Request $request
255
     * @return Response
256
     */
257
    public function index(Request $request) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
258
        
259
260
        /**
261
         * Handle saved settings
262
         */
263
        $redirectRoute = Helpers::resetSaveIndexParameters($this->moduleBasicRoute);
264
        if ($redirectRoute !== FALSE) {
265
266
            return redirect($redirectRoute);
267
        }
268
269
        /**
270
         * Get the rows
271
         */
272
        $modelClass = $this->modelClass;
273
        $arResults = $modelClass::where(function(Builder $query) {
274
                    $query->fulltextAllColumns();
275
                })->relationships()->orderByColumns()->excludeFromIndex()
276
                        ->externalTablesFilter()->paginate($this->getRowsToPaginate());
277
                
278
        /**
279
         * Choose the view
280
         */
281 View Code Duplication
        if(empty($this->customView['index']) == TRUE){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
282
            $view = $this->moduleBasicTemplatePath . '.index';
283
        }
284
        else{
285
            $view = $this->customView;
286
        }
287
288
289
        /**
290
         * Return page
291
         */
292
        return view($view, ['results' => $arResults]);
293
    }
294
295
    /**
296
     * Show the form for creating a new resource.
297
     *
298
     * @return Response
299
     */
300
    public function create() {
301
        
302
        /**
303
         * Choose the view
304
         */
305 View Code Duplication
        if(empty($this->customView['index']) == TRUE){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
306
            $view = $this->moduleBasicTemplatePath . '.create_edit';
307
        }
308
        else{
309
            $view = $this->customView;
310
        }
311
        
312
        /**
313
         * Return page
314
         */
315
        return view($view);
316
    }
317
318
    /**
319
     * Store a newly created resource in storage.
320
     *
321
     * @param  Request  $request
322
     * @return Response
323
     */
324
    public function store(Request $request) {
325
326
        /**
327
         * Change the validation array
328
         */
329 View Code Duplication
        foreach ($this->arValidationArray as $name => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
            if(strpos($this->arValidationArray[$name], 'unique') > 0){
331
                $this->arValidationArray[$name] = $value . ',NULL,id,deleted_at,NULL';
0 ignored issues
show
Bug introduced by
The property arValidationArray does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
332
            }
333
        }
334
335
        /**
336
         * Validate input
337
         */
338
        $this->validate($request, $this->arValidationArray);
339
        
340
        /**
341
         * Create new object
342
         */
343
        $modelClass = $this->modelClass;
344
        $object = new $modelClass();
345
346
        /**
347
         * Create row
348
         */
349
        foreach ($this->arValidationArray as $name => $value) {
350
351
            /**
352
             * Datetime
353
             */
354
            if(in_array($name, $this->dateTimeLocalFields)){
355
356
                $object->{$name} = str_replace('T', ' ', $request->input($name)). ':00';
357
            }
358
            else {
359
360
                /**
361
                 * Change to null if needed
362
                 */
363
                if(strlen($request->$name) < 1){
364
                    $object->{$name} = null;
365
                }
366
                else {
367
                    $object->{$name} = $request->input($name);
368
                }
369
            }
370
371
372
        }
373
374
        /**
375
         * Associate relationships
376
         */
377
        $this->associateRelationships($object, $request);
378
        
379
        /**
380
         * Save main object
381
         */
382
        $object->save();
383
        
384
        /**
385
         * Save media to storage
386
         */
387
        $this->saveMediaToStorage($object, $request);
388
        
389
        /**
390
         * Associate relatinships with ID
391
         */
392
        $this->associateRelationshipsWithID($object, $request);
393
        
394
        /**
395
         * Redirect to index
396
         */
397
        return redirect(route($this->moduleBasicRoute . '.index'));
398
    }
399
400
    /**
401
     * Show the form for editing the specified resource.
402
     *
403
     * @param  int  $id
404
     * @return Response
405
     */
406
    public function edit($id) {
407
        
408
        $modelClass = $this->modelClass;
409
410
        /**
411
         * Get the row
412
         */
413
        $arResults = $modelClass::where('id', $id)->relationships()->excludeFromFind()->get();
414
        $arResults = $arResults[0];
415
    
416
        /**
417
         * Row does not exist - redirect
418
         */
419 View Code Duplication
        if (count($arResults) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
420
421
            return redirect(route($this->moduleBasicRoute . '.index'))->withInput()->withErrors(['edit' => trans('validation.row_not_exist')]);
422
        }
423
424
        /**
425
         * Set the put method for update
426
         */
427
        $arResults['_method'] = 'PUT';
428
        
429
        /**
430
         * Choose the view
431
         */
432 View Code Duplication
        if(empty($this->customView['index']) == TRUE){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
433
            $view = $this->moduleBasicTemplatePath . '.create_edit';
434
        }
435
        else{
436
            $view = $this->customView;
437
        }
438
439
        $arResults = $this->changeEditResultField($arResults);
440
    
441
        /**
442
         * Return page
443
         */
444
        return view($view, ['results' => $arResults]);
445
    }
446
447
    /**
448
     * Display the specified resource.
449
     *
450
     * @param  int  $id
451
     * @return Response
452
     */
453
    public function show($id) {
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
454
       
455
    }
456
457
    /**
458
     * Update the specified resource in storage.
459
     *
460
     * @param  Request  $request
461
     * @param  int  $id
462
     * @return Response
463
     */
464
    public function update(Request $request, $id) {
465
466
467
468
        /**
469
         * Change the validation array
470
         */
471 View Code Duplication
        foreach ($this->arValidationArray as $name => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
472
            
473
            if(strpos($this->arValidationArray[$name], 'unique') > 0){
474
                $this->arValidationArray[$name] = $value . ','.$id.',id,deleted_at,NULL';
475
            }
476
        }
477
478
        /**
479
         * Validate input
480
         */
481
        $this->validate($request, $this->arValidationArray);
482
        
483
        /**
484
         * Get the row
485
         */
486
        $modelClass = $this->modelClass;
487
        $arResults = $modelClass::find($id);
488
489
        /**
490
         * Row does not exist - redirect
491
         */
492 View Code Duplication
        if ($arResults == FALSE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
493
494
            return redirect(route($this->moduleBasicRoute . '.index'))->withInput()->withErrors(['edit' => trans('validation.row_not_exist')]);
495
        }
496
        
497
        /**
498
         * Reset cache
499
         */
500
        $this->resetCache($arResults);
501
502
        /**
503
         * Set updated values
504
         */
505
        foreach ($this->arValidationArray as $name => $value) {
506
            
507
            /**
508
             * Binary fields will not be updated if empty
509
             *
510
             */
511
            if(in_array($name, $this->binaryFields)){
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
512
513
            }
514
            else{
515
                
516
               /**
517
                * Empty exception
518
                */
519
               if (empty($request->input($name)) == FALSE) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
520
521
                   /**
522
                    * Datetime
523
                    */
524
                   if(in_array($name, $this->dateTimeLocalFields)){
525
526
                       $arResults->$name = str_replace('T', ' ', $request->input($name)). ':00';
527
                   }
528
                   else {
529
                       $arResults->$name = $request->input($name);
530
                   }
531
               }
532
               
533
               else{
534
                   
535
                   /**
536
                    * Numeric zero ?
537
                    */
538
                   if(isset($request->name) && is_numeric($request->input($name)) == TRUE){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
539
                       
540
                      $arResults->$name = $request->input($name);
541
                   }
542
                   
543
                   else{
544
                    $arResults->$name = NULL;
545
                   }
546
               }
547
            }
548
549
            
550
        }
551
        
552
        /**
553
         * Associate relationships
554
         */
555
        $this->associateRelationships($arResults, $request);
556
        
557
        /**
558
         * Save media to storage
559
         */
560
        if($this->saveMediaToStorage($arResults, $request, TRUE) == TRUE){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
561
            
562
            // Update binary fields
563
            foreach ($this->binaryFields as $name => $value) {
564
                
565
                if (empty($request->$value) == FALSE) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
566
                   $arResults->$value = $request->$value;
567
                }
568
                else{
569
                    $arResults->$value = NULL;
570
                }
571
            }
572
        }
573
574
        /**
575
         * Save the changes
576
         */
577
        $arResults->save();
578
        
579
        /**
580
         * Associate relatinships with ID
581
         */
582
        $this->associateRelationshipsWithID($arResults, $request);
583
584
        /**
585
         * Return to index
586
         */
587
        return redirect(route($this->moduleBasicRoute . '.index'));
588
    }
589
590
    /**
591
     * Remove the specified resource from storage.
592
     *
593
     * @param  int  $id
594
     * @return Response
595
     */
596
597
    public function destroy($id) {
598
        /**
599
         * Delete the setting
600
         */
601
        $modelClass = $this->modelClass;
602
        $modelClass::destroy($id);
603
604
        /**
605
         * Redirect to index
606
         */
607
        return redirect(route($this->moduleBasicRoute . '.index'));
608
    }
609
610
}
611