SettingsController   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 472
Duplicated Lines 0 %

Importance

Changes 3
Bugs 3 Features 0
Metric Value
wmc 47
eloc 287
dl 0
loc 472
rs 8.64
c 3
b 3
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A settingsMail() 0 6 2
A settingsEmail() 0 8 2
A settingsError() 0 8 2
A settings() 0 8 2
A getMails() 0 55 2
A settingsSystem() 0 17 2
A postSettingsError() 0 9 2
A getActivity() 0 73 3
B checkPaymentGateway() 0 30 7
A postSettingsSystem() 0 43 5
A settingsActivity() 0 26 3
A postSettingsTemplate() 0 9 2
A getKeys() 0 36 2
A settingsTemplate() 0 9 2
A plugins() 0 3 1
A postKeys() 0 9 2
A destroy() 0 46 5

How to fix   Complexity   

Complex Class

Complex classes like SettingsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SettingsController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Common;
4
5
use App\ApiKey;
6
use App\Model\Common\Mailchimp\MailchimpSetting;
7
use App\Model\Common\Setting;
8
use App\Model\Common\StatusSetting;
9
use App\Model\Common\Template;
10
use App\Model\Mailjob\QueueService;
11
use App\Model\Payment\Currency;
12
use App\Model\Plugin;
13
use App\User;
14
use Bugsnag;
15
use GrahamCampbell\Markdown\Facades\Markdown;
16
use Illuminate\Http\Request;
17
use Spatie\Activitylog\Models\Activity;
18
19
class SettingsController extends BaseSettingsController
20
{
21
    public $apikey;
22
    public $statusSetting;
23
24
    public function __construct()
25
    {
26
        $this->middleware('auth', ['except' => 'checkPaymentGateway']);
27
        $this->middleware('admin', ['except' => 'checkPaymentGateway']);
28
29
        $apikey = new ApiKey();
30
        $this->apikey = $apikey;
31
32
        $status = new StatusSetting();
33
        $this->statusSetting = $status;
34
    }
35
36
    public function settings(Setting $settings)
37
    {
38
        if (! $settings->where('id', '1')->first()) {
39
            $settings->create(['company' => '']);
40
        }
41
        $isRedisConfigured = QueueService::where('short_name', 'redis')->value('status');
42
43
        return view('themes.default1.common.admin-settings', compact('isRedisConfigured'));
44
        //return view('themes.default1.common.settings', compact('setting', 'template'));
45
    }
46
47
    public function plugins()
48
    {
49
        return view('themes.default1.common.plugins');
50
    }
51
52
    /**
53
     * Get the Status and Api Keys for Settings Module.
54
     *
55
     * @param ApiKey $apikeys
56
     */
57
    public function getKeys(ApiKey $apikeys)
58
    {
59
        try {
60
            $licenseSecret = $apikeys->pluck('license_api_secret')->first();
61
            $licenseUrl = $apikeys->pluck('license_api_url')->first();
62
            $status = StatusSetting::pluck('license_status')->first();
63
            $captchaStatus = StatusSetting::pluck('recaptcha_status')->first();
64
            $updateStatus = StatusSetting::pluck('update_settings')->first();
65
            $mobileStatus = StatusSetting::pluck('msg91_status')->first();
66
            $siteKey = $apikeys->pluck('nocaptcha_sitekey')->first();
67
            $secretKey = $apikeys->pluck('captcha_secretCheck')->first();
68
            $updateSecret = $apikeys->pluck('update_api_secret')->first();
69
            $mobileauthkey = $apikeys->pluck('msg91_auth_key')->first();
70
            $msg91Sender = $apikeys->pluck('msg91_sender')->first();
71
            $updateUrl = $apikeys->pluck('update_api_url')->first();
72
            $emailStatus = StatusSetting::pluck('emailverification_status')->first();
73
            $twitterKeys = $apikeys->select('twitter_consumer_key','twitter_consumer_secret',
74
                'twitter_access_token', 'access_tooken_secret')->first();
75
            $twitterStatus = $this->statusSetting->pluck('twitter_status')->first();
76
            $zohoStatus = $this->statusSetting->pluck('zoho_status')->first();
77
            $zohoKey = $apikeys->pluck('zoho_api_key')->first();
78
            $rzpStatus = $this->statusSetting->pluck('rzp_status')->first();
79
            $rzpKeys = $apikeys->select('rzp_key', 'rzp_secret', 'apilayer_key')->first();
80
            $mailchimpSetting = StatusSetting::pluck('mailchimp_status')->first();
81
            $mailchimpKey = MailchimpSetting::pluck('api_key')->first();
82
            $termsStatus = StatusSetting::pluck('terms')->first();
83
            $termsUrl = $apikeys->pluck('terms_url')->first();
84
            $pipedriveKey = $apikeys->pluck('pipedrive_api_key')->first();
85
            $pipedriveStatus = StatusSetting::pluck('pipedrive_status')->first();
86
            $domainCheckStatus = StatusSetting::pluck('domain_check')->first();
87
            $mailSendingStatus = Setting::value('sending_status');
88
            $model = $apikeys->find(1);
89
90
            return view('themes.default1.common.apikey', compact('model', 'status', 'licenseSecret', 'licenseUrl', 'siteKey', 'secretKey', 'captchaStatus', 'updateStatus', 'updateSecret', 'updateUrl', 'mobileStatus', 'mobileauthkey', 'msg91Sender', 'emailStatus', 'twitterStatus', 'twitterKeys', 'zohoStatus', 'zohoKey', 'rzpStatus', 'rzpKeys', 'mailchimpSetting', 'mailchimpKey', 'termsStatus', 'termsUrl', 'pipedriveKey', 'pipedriveStatus', 'domainCheckStatus', 'mailSendingStatus'));
91
        } catch (\Exception $ex) {
92
            return redirect('/')->with('fails', $ex->getMessage());
93
        }
94
    }
95
96
    public function postKeys(ApiKey $apikeys, Request $request)
97
    {
98
        try {
99
            $keys = $apikeys->find(1);
100
            $keys->fill($request->input())->save();
101
102
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
103
        } catch (\Exception $ex) {
104
            return redirect()->back()->with('fails', $ex->getMessage());
105
        }
106
    }
107
108
    /**
109
     * PAyment Gateway that is shown on the basis of currency.
110
     *
111
     * @param string $currency The currency of the Product Selected
112
     *
113
     * @return string Name of the Payment Gateway
114
     */
115
    public static function checkPaymentGateway($currency)
116
    {
117
        try {
118
            $plugins = new Plugin();
119
            $models = [];
120
            $gateways = '';
121
            $name = '';
122
            $allAcivePluginName = [];
123
            $active_plugins = $plugins->where('status', 1)->get(); //get the plugins that are active
124
            if ($active_plugins) {
0 ignored issues
show
introduced by
$active_plugins is of type Illuminate\Database\Eloquent\Collection, thus it always evaluated to true.
Loading history...
125
                foreach ($active_plugins as $plugin) {
126
                    $models[] = \DB::table(strtolower($plugin->name))->first(); //get the table of the active plugin
127
                    $allCurrencies[] = \DB::table(strtolower($plugin->name))->pluck('currencies')->toArray(); //get the table of the active plugin
128
                    $pluginName[] = $plugin->name; //get the name of active plugin
129
                }
130
                if ($models) {//If more than 1 plugin is active it will check the currencies allowed for that plugin.If the currencies allowed matches the passed arguement(currency),that plugin name is returned
131
                    for ($i = 0; $i < count($pluginName); $i++) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pluginName seems to be defined by a foreach iteration on line 125. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
132
                        $curr = implode(',', $allCurrencies[$i]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $allCurrencies seems to be defined by a foreach iteration on line 125. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
133
                        $currencies = explode(',', $curr);
134
                        if (in_array($currency, $currencies)) {
135
                            $name = $pluginName[$i];
136
                            $allAcivePluginName[] = $name;
137
                        }
138
                    }
139
                }
140
            }
141
142
            return $allAcivePluginName;
143
        } catch (\Exception $ex) {
144
            return redirect()->back()->with('fails', $ex->getMessage());
145
        }
146
    }
147
148
    public function settingsSystem(Setting $settings)
149
    {
150
        try {
151
            $set = $settings->find(1);
152
            $state = getStateByCode($set->state);
153
            $selectedCountry = \DB::table('countries')->where('country_code_char2', $set->country)
154
            ->pluck('nicename', 'country_code_char2')->toArray();
155
            $selectedCurrency = \DB::table('currencies')->where('code', $set->default_currency)
156
            ->pluck('name', 'symbol')->toArray();
157
            $states = findStateByRegionId($set->country);
158
159
            return view(
160
                'themes.default1.common.setting.system',
161
                compact('set', 'selectedCountry', 'state', 'states', 'selectedCurrency')
162
            );
163
        } catch (\Exception $ex) {
164
            return redirect()->back()->with('fails', $ex->getMessage());
165
        }
166
    }
167
168
    public function postSettingsSystem(Setting $settings, Request $request)
169
    {
170
        $this->validate($request, [
171
            'company'         => 'required|max:50',
172
            'company_email'   => 'required|email',
173
            'website'         => 'required',
174
            'phone'           => 'required',
175
            'address'         => 'required',
176
            'state'           => 'required',
177
            'country'         => 'required',
178
            'default_currency'=> 'required',
179
            'admin-logo'      => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
180
            'fav-icon'        => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
181
            'logo'            => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
182
        ]);
183
184
        try {
185
            $setting = $settings->find(1);
186
            if ($request->hasFile('logo')) {
187
                $name = $request->file('logo')->getClientOriginalName();
188
                $destinationPath = public_path('common/images');
189
                $request->file('logo')->move($destinationPath, $name);
190
                $setting->logo = $name;
191
            }
192
            if ($request->hasFile('admin-logo')) {
193
                $logoName = $request->file('admin-logo')->getClientOriginalName();
194
                $destinationPath = public_path('admin/images');
195
                $request->file('admin-logo')->move($destinationPath, $logoName);
196
                $setting->admin_logo = $logoName;
197
            }
198
            if ($request->hasFile('fav-icon')) {
199
                $iconName = $request->file('fav-icon')->getClientOriginalName();
200
                $destinationPath = public_path('common/images');
201
                $request->file('fav-icon')->move($destinationPath, $iconName);
202
                $setting->fav_icon = $iconName;
203
            }
204
            $setting->default_symbol = Currency::where('code', $request->input('default_currency'))
205
            ->pluck('symbol')->first();
206
            $setting->fill($request->except('password', 'logo', 'admin-logo', 'fav-icon'))->save();
207
208
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
209
        } catch (\Exception $ex) {
210
            return redirect()->back()->with('fails', $ex->getMessage());
211
        }
212
    }
213
214
    public function settingsEmail(Setting $settings)
215
    {
216
        try {
217
            $set = $settings->find(1);
218
219
            return view('themes.default1.common.setting.email', compact('set'));
220
        } catch (\Exception $ex) {
221
            return redirect()->back()->with('fails', $ex->getMessage());
222
        }
223
    }
224
225
    public function settingsTemplate(Setting $settings)
226
    {
227
        try {
228
            $set = $settings->find(1);
229
            $template = new Template();
230
            //$templates = $template->lists('name', 'id')->toArray();
231
            return view('themes.default1.common.setting.template', compact('set', 'template'));
232
        } catch (\Exception $ex) {
233
            return redirect()->back()->with('fails', $ex->getMessage());
234
        }
235
    }
236
237
    public function postSettingsTemplate(Setting $settings, Request $request)
238
    {
239
        try {
240
            $setting = $settings->find(1);
241
            $setting->fill($request->input())->save();
242
243
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
244
        } catch (\Exception $ex) {
245
            return redirect()->back()->with('fails', $ex->getMessage());
246
        }
247
    }
248
249
    public function settingsError(Setting $settings)
250
    {
251
        try {
252
            $set = $settings->find(1);
253
254
            return view('themes.default1.common.setting.error-log', compact('set'));
255
        } catch (\Exception $ex) {
256
            return redirect()->back()->with('fails', $ex->getMessage());
257
        }
258
    }
259
260
    public function settingsActivity(Request $request, Activity $activities)
261
    {
262
        $validator = \Validator::make($request->all(), [
263
            'from'     => 'nullable',
264
            'till'     => 'nullable|after:from',
265
            'delFrom'  => 'nullable',
266
            'delTill'  => 'nullable|after:delFrom',
267
        ]);
268
        if ($validator->fails()) {
269
            $request->from = '';
0 ignored issues
show
Bug introduced by
The property from does not seem to exist on Illuminate\Http\Request.
Loading history...
270
            $request->till = '';
0 ignored issues
show
Bug introduced by
The property till does not seem to exist on Illuminate\Http\Request.
Loading history...
271
            $request->delFrom = '';
0 ignored issues
show
Bug introduced by
The property delFrom does not seem to exist on Illuminate\Http\Request.
Loading history...
272
            $request->delTill = '';
0 ignored issues
show
Bug introduced by
The property delTill does not seem to exist on Illuminate\Http\Request.
Loading history...
273
274
            return redirect('settings/activitylog')->with('fails', 'Start date should be before end date');
275
        }
276
        try {
277
            $activity = $activities->all();
278
            $from = $request->input('from');
279
            $till = $request->input('till');
280
            $delFrom = $request->input('delFrom');
281
            $delTill = $request->input('delTill');
282
283
            return view('themes.default1.common.Activity-Log', compact('activity', 'from', 'till', 'delFrom', 'delTill'));
284
        } catch (\Exception $ex) {
285
            return redirect()->back()->with('fails', $ex->getMessage());
286
        }
287
    }
288
289
    public function settingsMail()
290
    {
291
        try {
292
            return view('themes.default1.common.email-log');
293
        } catch (\Exception $ex) {
294
            return redirect()->back()->with('fails', $ex->getMessage());
295
        }
296
    }
297
298
    public function getActivity(Request $request)
299
    {
300
        try {
301
            $from = $request->input('log_from');
302
            $till = $request->input('log_till');
303
            $delFrom = $request->input('delFrom');
304
            $delTill = $request->input('delTill');
305
            $query = $this->advanceSearch($from, $till, $delFrom, $delTill);
306
307
            return \DataTables::of($query->take(50))
308
             ->setTotalRecords($query->count())
309
             ->addColumn('checkbox', function ($model) {
310
                 return "<input type='checkbox' class='activity' value=".$model->id.' name=select[] id=check>';
311
             })
312
                           ->addColumn('name', function ($model) {
313
                               return ucfirst($model->log_name);
314
                           })
315
                             ->addColumn('description', function ($model) {
316
                                 return ucfirst($model->description);
317
                             })
318
                          ->addColumn('username', function ($model) {
319
                              $causer_id = $model->causer_id;
320
                              $names = User::where('id', $causer_id)->pluck('last_name', 'first_name');
321
                              foreach ($names as $key => $value) {
322
                                  $fullName = $key.' '.$value;
323
324
                                  return $fullName;
325
                              }
326
                          })
327
                              ->addColumn('role', function ($model) {
328
                                  $causer_id = $model->causer_id;
329
                                  $role = User::where('id', $causer_id)->pluck('role');
330
331
                                  return json_decode($role);
332
                              })
333
                               ->addColumn('new', function ($model) {
334
                                   $properties = ($model->properties);
335
                                   $newEntry = $this->getNewEntry($properties, $model);
336
337
                                   return $newEntry;
338
                               })
339
                                ->addColumn('old', function ($model) {
340
                                    $data = ($model->properties);
341
                                    $oldEntry = $this->getOldEntry($data, $model);
342
343
                                    return $oldEntry;
344
                                })
345
                                ->addColumn('created_at', function ($model) {
346
                                    return getDateHtml($model->created_at);
347
                                })
348
349
                                    ->filterColumn('log_name', function ($query, $keyword) {
350
                                        $sql = 'log_name like ?';
351
                                        $query->whereRaw($sql, ["%{$keyword}%"]);
352
                                    })
353
354
                                ->filterColumn('description', function ($query, $keyword) {
355
                                    $sql = 'description like ?';
356
                                    $query->whereRaw($sql, ["%{$keyword}%"]);
357
                                })
358
359
                            ->filterColumn('causer_id', function ($query, $keyword) {
360
                                $sql = 'first_name like ?';
361
                                $query->whereRaw($sql, ["%{$keyword}%"]);
362
                            })
363
364
                            ->rawColumns(['checkbox', 'name', 'description',
365
                                'username', 'role', 'new', 'old', 'created_at', ])
366
                            ->make(true);
367
        } catch (\Exception $e) {
368
            Bugsnag::notifyException($e);
369
370
            return redirect()->back()->with('fails', $e->getMessage());
371
        }
372
    }
373
374
    public function getMails()
375
    {
376
        try {
377
            $email_log = \DB::table('email_log')->orderBy('date', 'desc')->take(50);
378
379
            return\ DataTables::of($email_log)
380
            ->setTotalRecords($email_log->count())
381
             ->addColumn('checkbox', function ($model) {
382
                 return "<input type='checkbox' class='email' value=".$model->id.' name=select[] id=check>';
383
             })
384
                           ->addColumn('date', function ($model) {
385
                               $date = $model->date;
386
387
                               return getDateHtml($date);
388
                           })
389
                             ->addColumn('from', function ($model) {
390
                                 $from = Markdown::convertToHtml($model->from);
391
392
                                 return $from;
393
                             })
394
                              ->addColumn('to', function ($model) {
395
                                  $to = Markdown::convertToHtml($model->to);
396
397
                                  return $to;
398
                              })
399
400
                               ->addColumn('subject', function ($model) {
401
                                   return ucfirst($model->subject);
402
                               })
403
                              ->addColumn('status', function ($model) {
404
                                  return ucfirst($model->status);
405
                              })
406
                               ->filterColumn('from', function ($query, $keyword) {
407
                                   $sql = '`from` like ?';
408
                                   $query->whereRaw($sql, ["%{$keyword}%"]);
409
                               })
410
                               ->filterColumn('to', function ($query, $keyword) {
411
                                   $sql = '`to` like ?';
412
                                   $query->whereRaw($sql, ["%{$keyword}%"]);
413
                               })
414
                               ->filterColumn('subject', function ($query, $keyword) {
415
                                   $sql = '`subject` like ?';
416
                                   $query->whereRaw($sql, ["%{$keyword}%"]);
417
                               })
418
                               ->filterColumn('status', function ($query, $keyword) {
419
                                   $sql = '`status` like ?';
420
                                   $query->whereRaw($sql, ["%{$keyword}%"]);
421
                               })
422
                              ->rawColumns(['checkbox', 'date', 'from', 'to',
423
                                  'bcc', 'subject',  'status', ])
424
                            ->make(true);
425
        } catch (\Exception $e) {
426
            Bugsnag::notifyException($e);
427
428
            return redirect()->back()->with('fails', $e->getMessage());
429
        }
430
    }
431
432
    public function destroy(Request $request)
433
    {
434
        try {
435
            $ids = $request->input('select');
436
            if (! empty($ids)) {
437
                foreach ($ids as $id) {
438
                    $activity = Activity::where('id', $id)->first();
439
                    if ($activity) {
440
                        $activity->delete();
441
                    } else {
442
                        echo "<div class='alert alert-danger alert-dismissable'>
443
                        <i class='fa fa-ban'></i>
444
445
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
446
                        /* @scrutinizer ignore-type */     \Lang::get('message.failed').'
447
448
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
449
                            './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
450
                    </div>';
451
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
452
                    }
453
                }
454
                echo "<div class='alert alert-success alert-dismissable'>
455
                        <i class='fa fa-ban'></i>
456
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
457
                        ./* @scrutinizer ignore-type */\Lang::get('message.success').'
458
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
459
                            './* @scrutinizer ignore-type */ \Lang::get('message.deleted-successfully').'
460
                    </div>';
461
            } else {
462
                echo "<div class='alert alert-danger alert-dismissable'>
463
                        <i class='fa fa-ban'></i>
464
                        <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').
465
                        '!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
466
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
467
                            './* @scrutinizer ignore-type */ \Lang::get('message.select-a-row').'
468
                    </div>';
469
                //echo \Lang::get('message.select-a-row');
470
            }
471
        } catch (\Exception $e) {
472
            echo "<div class='alert alert-danger alert-dismissable'>
473
                        <i class='fa fa-ban'></i>
474
                        <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
475
                        /* @scrutinizer ignore-type */\Lang::get('message.failed').'
476
                        <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
477
                            '.$e->getMessage().'
478
                    </div>';
479
        }
480
    }
481
482
    public function postSettingsError(Setting $settings, Request $request)
483
    {
484
        try {
485
            $setting = $settings->find(1);
486
            $setting->fill($request->input())->save();
487
488
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
489
        } catch (\Exception $ex) {
490
            return redirect()->back()->with('fails', $ex->getMessage());
491
        }
492
    }
493
}
494