SettingsController::postSettings()   F
last analyzed

Complexity

Conditions 14
Paths 1944

Size

Total Lines 69

Duplication

Lines 21
Ratio 30.43 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
cc 14
nc 1944
nop 0
dl 21
loc 69
ccs 0
cts 31
cp 0
crap 210
rs 2.3563
c 0
b 0
f 0

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
/*
4
 * This file is part of Cachet.
5
 *
6
 * (c) Alt Three Services Limited
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CachetHQ\Cachet\Http\Controllers\Dashboard;
13
14
use CachetHQ\Cachet\Bus\Commands\System\Config\UpdateConfigCommand;
15
use CachetHQ\Cachet\Integrations\Contracts\Credits;
16
use CachetHQ\Cachet\Models\User;
17
use CachetHQ\Cachet\Notifications\System\SystemTestNotification;
18
use CachetHQ\Cachet\Settings\Repository;
19
use Exception;
20
use GrahamCampbell\Binput\Facades\Binput;
21
use Illuminate\Routing\Controller;
22
use Illuminate\Support\Facades\Artisan;
23
use Illuminate\Support\Facades\Auth;
24
use Illuminate\Support\Facades\Config;
25
use Illuminate\Support\Facades\Lang;
26
use Illuminate\Support\Facades\Log;
27
use Illuminate\Support\Facades\Redirect;
28
use Illuminate\Support\Facades\Session;
29
use Illuminate\Support\Facades\View;
30
use Illuminate\Support\Str;
31
use Monolog\Handler\SyslogHandler;
32
33
class SettingsController extends Controller
34
{
35
    /**
36
     * Array of sub-menu items.
37
     *
38
     * @var array
39
     */
40
    protected $subMenu = [];
41
42
    /**
43
     * Creates a new settings controller instance.
44
     *
45
     * @return void
46
     */
47
    public function __construct()
48
    {
49
        $this->subMenu = [
50
            'setup' => [
51
                'title'  => trans('dashboard.settings.app-setup.app-setup'),
52
                'url'    => cachet_route('dashboard.settings.setup'),
53
                'icon'   => 'ion-gear-b',
54
                'active' => false,
55
            ],
56
            'theme' => [
57
                'title'  => trans('dashboard.settings.theme.theme'),
58
                'url'    => cachet_route('dashboard.settings.theme'),
59
                'icon'   => 'ion-paintbrush',
60
                'active' => false,
61
            ],
62
            'stylesheet' => [
63
                'title'  => trans('dashboard.settings.stylesheet.stylesheet'),
64
                'url'    => cachet_route('dashboard.settings.stylesheet'),
65
                'icon'   => 'ion-paintbucket',
66
                'active' => false,
67
            ],
68
            'customization' => [
69
                'title'  => trans('dashboard.settings.customization.customization'),
70
                'url'    => cachet_route('dashboard.settings.customization'),
71
                'icon'   => 'ion-wand',
72
                'active' => false,
73
            ],
74
            'localization' => [
75
                'title'  => trans('dashboard.settings.localization.localization'),
76
                'url'    => cachet_route('dashboard.settings.localization'),
77
                'icon'   => 'ion-earth',
78
                'active' => false,
79
            ],
80
            'security' => [
81
                'title'  => trans('dashboard.settings.security.security'),
82
                'url'    => cachet_route('dashboard.settings.security'),
83
                'icon'   => 'ion-lock-combination',
84
                'active' => false,
85
            ],
86
            'analytics' => [
87
                'title'  => trans('dashboard.settings.analytics.analytics'),
88
                'url'    => cachet_route('dashboard.settings.analytics'),
89
                'icon'   => 'ion-stats-bars',
90
                'active' => false,
91
            ],
92
            'log' => [
93
                'title'  => trans('dashboard.settings.log.log'),
94
                'url'    => cachet_route('dashboard.settings.log'),
95
                'icon'   => 'ion-document-text',
96
                'active' => false,
97
            ],
98
            'credits' => [
99
                'title'  => trans('dashboard.settings.credits.credits'),
100
                'url'    => cachet_route('dashboard.settings.credits'),
101
                'icon'   => 'ion-ios-list',
102
                'active' => false,
103
            ],
104
            'mail' => [
105
                'title'  => trans('dashboard.settings.mail.mail'),
106
                'url'    => cachet_route('dashboard.settings.mail'),
107
                'icon'   => 'ion-paper-airplane',
108
                'active' => false,
109
            ],
110
            'about' => [
111
                'title'  => CACHET_VERSION,
112
                'url'    => 'javascript: void(0);',
113
                'icon'   => 'ion-flag',
114
                'active' => false,
115
            ],
116
        ];
117
118
        View::share([
119
            'subTitle' => trans('dashboard.settings.settings'),
120
            'subMenu'  => $this->subMenu,
121
        ]);
122
    }
123
124
    /**
125
     * Shows the settings setup view.
126
     *
127
     * @return \Illuminate\View\View
128
     */
129 View Code Duplication
    public function showSetupView()
130
    {
131
        $this->subMenu['setup']['active'] = true;
132
133
        Session::flash('redirect_to', $this->subMenu['setup']['url']);
134
135
        return View::make('dashboard.settings.app-setup')
136
            ->withPageTitle(trans('dashboard.settings.app-setup.app-setup').' - '.trans('dashboard.dashboard'))
137
            ->withSubMenu($this->subMenu)
138
            ->withRawAppAbout(Config::get('setting.app_about'));
139
    }
140
141
    /**
142
     * Shows the settings analytics view.
143
     *
144
     * @return \Illuminate\View\View
145
     */
146 View Code Duplication
    public function showAnalyticsView()
147
    {
148
        $this->subMenu['analytics']['active'] = true;
149
150
        Session::flash('redirect_to', $this->subMenu['analytics']['url']);
151
152
        return View::make('dashboard.settings.analytics')
153
            ->withPageTitle(trans('dashboard.settings.analytics.analytics').' - '.trans('dashboard.dashboard'))
154
            ->withSubMenu($this->subMenu);
155
    }
156
157
    /**
158
     * Shows the settings localization view.
159
     *
160
     * @return \Illuminate\View\View
161
     */
162 View Code Duplication
    public function showLocalizationView()
163
    {
164
        $this->subMenu['localization']['active'] = true;
165
166
        Session::flash('redirect_to', $this->subMenu['localization']['url']);
167
168
        return View::make('dashboard.settings.localization')
169
            ->withPageTitle(trans('dashboard.settings.localization.localization').' - '.trans('dashboard.dashboard'))
170
            ->withSubMenu($this->subMenu);
171
    }
172
173
    /**
174
     * Shows the settings customization view.
175
     *
176
     * @return \Illuminate\View\View
177
     */
178 View Code Duplication
    public function showCustomizationView()
179
    {
180
        $this->subMenu['customization']['active'] = true;
181
182
        Session::flash('redirect_to', $this->subMenu['customization']['url']);
183
184
        return View::make('dashboard.settings.customization')
185
            ->withPageTitle(trans('dashboard.settings.customization.customization').' - '.trans('dashboard.dashboard'))
186
            ->withSubMenu($this->subMenu);
187
    }
188
189
    /**
190
     * Shows the settings theme view.
191
     *
192
     * @return \Illuminate\View\View
193
     */
194 View Code Duplication
    public function showThemeView()
195
    {
196
        $this->subMenu['theme']['active'] = true;
197
198
        Session::flash('redirect_to', $this->subMenu['theme']['url']);
199
200
        return View::make('dashboard.settings.theme')
201
            ->withPageTitle(trans('dashboard.settings.theme.theme').' - '.trans('dashboard.dashboard'))
202
            ->withSubMenu($this->subMenu);
203
    }
204
205
    /**
206
     * Shows the settings security view.
207
     *
208
     * @return \Illuminate\View\View
209
     */
210
    public function showSecurityView()
211
    {
212
        $this->subMenu['security']['active'] = true;
213
214
        $unsecureUsers = User::whereNull('google_2fa_secret')->orWhere('google_2fa_secret', '=', '')->get();
215
216
        Session::flash('redirect_to', $this->subMenu['security']['url']);
217
218
        return View::make('dashboard.settings.security')
219
            ->withPageTitle(trans('dashboard.settings.security.security').' - '.trans('dashboard.dashboard'))
220
            ->withSubMenu($this->subMenu)
221
            ->withUnsecureUsers($unsecureUsers);
222
    }
223
224
    /**
225
     * Shows the settings stylesheet view.
226
     *
227
     * @return \Illuminate\View\View
228
     */
229 View Code Duplication
    public function showStylesheetView()
230
    {
231
        $this->subMenu['stylesheet']['active'] = true;
232
233
        Session::flash('redirect_to', $this->subMenu['stylesheet']['url']);
234
235
        return View::make('dashboard.settings.stylesheet')
236
            ->withPageTitle(trans('dashboard.settings.stylesheet.stylesheet').' - '.trans('dashboard.dashboard'))
237
            ->withSubMenu($this->subMenu);
238
    }
239
240
    /**
241
     * Show the credits view.
242
     *
243
     * @return \Illuminate\View\View
244
     */
245
    public function showCreditsView()
246
    {
247
        $this->subMenu['credits']['active'] = true;
248
249
        $credits = app(Credits::class)->latest();
250
251
        $backers = $credits['backers'];
252
        $contributors = $credits['contributors'];
253
254
        shuffle($backers);
255
        shuffle($contributors);
256
257
        return View::make('dashboard.settings.credits')
258
            ->withPageTitle(trans('dashboard.settings.credits.credits').' - '.trans('dashboard.dashboard'))
259
            ->withBackers($backers)
260
            ->withContributors($contributors)
261
            ->withSubMenu($this->subMenu);
262
    }
263
264
    /**
265
     * Show the most recent log.
266
     *
267
     * @return \Illuminate\View\View
268
     */
269
    public function showLogView()
270
    {
271
        $this->subMenu['log']['active'] = true;
272
273
        $log = Log::getLogger();
274
275
        $logContents = '';
276
277
        collect($log->getHandlers())->reject(function ($handler) {
278
            return $handler instanceof SyslogHandler;
279
        })->each(function ($handler) use (&$logContents, $log) {
0 ignored issues
show
Unused Code introduced by James Brooks
The parameter $handler 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...
280
            if (file_exists($path = $log->getHandlers()[0]->getUrl())) {
281
                $logContents = file_get_contents($path);
282
            }
283
        });
284
285
        return View::make('dashboard.settings.log')->withLog($logContents)->withSubMenu($this->subMenu);
286
    }
287
288
    /**
289
     * Show the mail settings view.
290
     *
291
     * @return \Illuminate\View\View
292
     */
293
    public function showMailView()
294
    {
295
        $this->subMenu['mail']['active'] = true;
296
297
        return View::make('dashboard.settings.mail')->withConfig(Config::get('mail'));
298
    }
299
300
    /**
301
     * Test the mail config.
302
     *
303
     * @return \Illuminate\Http\RedirectResponse
304
     */
305
    public function testMail()
306
    {
307
        Auth::user()->notify(new SystemTestNotification());
0 ignored issues
show
Bug introduced by James Brooks
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method notify() does only exist in the following implementations of said interface: CachetHQ\Cachet\Models\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
308
309
        return cachet_redirect('dashboard.settings.mail')
310
            ->withSuccess(trans('dashboard.notifications.awesome'));
311
    }
312
313
    /**
314
     * Handle updating of the settings.
315
     *
316
     * @return \Illuminate\Http\RedirectResponse
317
     */
318
    public function postMail()
319
    {
320
        $config = Binput::get('config');
321
322
        execute(new UpdateConfigCommand($config));
323
324
        return cachet_redirect('dashboard.settings.mail')
325
            ->withInput(Binput::all())
326
            ->withSuccess(trans('dashboard.notifications.awesome'));
327
    }
328
329
    /**
330
     * Updates the status page settings.
331
     *
332
     * @return \Illuminate\View\View
333
     */
334
    public function postSettings()
335
    {
336
        $setting = app(Repository::class);
337
338
        if (Binput::get('remove_banner') === '1') {
339
            $setting->set('app_banner', null);
340
        }
341
342
        $parameters = Binput::all();
343
344 View Code Duplication
        if (isset($parameters['header'])) {
0 ignored issues
show
Duplication introduced by James Brooks
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...
345
            if ($header = Binput::get('header', null, false, false)) {
346
                $setting->set('header', $header);
347
            } else {
348
                $setting->delete('header');
349
            }
350
        }
351
352 View Code Duplication
        if (isset($parameters['footer'])) {
0 ignored issues
show
Duplication introduced by James Brooks
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...
353
            if ($footer = Binput::get('footer', null, false, false)) {
354
                $setting->set('footer', $footer);
355
            } else {
356
                $setting->delete('footer');
357
            }
358
        }
359
360 View Code Duplication
        if (isset($parameters['stylesheet'])) {
0 ignored issues
show
Duplication introduced by Henning Surmeier
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...
361
            if ($stylesheet = Binput::get('stylesheet', null, false, false)) {
362
                $setting->set('stylesheet', $stylesheet);
363
            } else {
364
                $setting->delete('stylesheet');
365
            }
366
        }
367
368
        if (Binput::hasFile('app_banner')) {
369
            $this->handleUpdateBanner($setting);
370
        }
371
372
        $excludedParams = [
373
            '_token',
374
            'app_banner',
375
            'remove_banner',
376
            'header',
377
            'footer',
378
            'stylesheet',
379
        ];
380
381
        try {
382
            foreach (Binput::except($excludedParams) as $settingName => $settingValue) {
383
                if ($settingName === 'app_analytics_pi_url') {
384
                    $settingValue = rtrim($settingValue, '/');
385
                }
386
387
                $setting->set($settingName, $settingValue);
388
            }
389
        } catch (Exception $e) {
390
            return Redirect::back()->withErrors(trans('dashboard.settings.edit.failure'));
0 ignored issues
show
Bug Best Practice introduced by James Brooks
The return type of return \Illuminate\Suppo...ttings.edit.failure')); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by CachetHQ\Cachet\Http\Con...ontroller::postSettings of type Illuminate\View\View.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
391
        }
392
393
        if (Binput::has('app_locale')) {
394
            Lang::setLocale(Binput::get('app_locale'));
395
        }
396
397
        if (Binput::has('always_authenticate')) {
398
            Artisan::call('route:clear');
399
        }
400
401
        return Redirect::back()->withSuccess(trans('dashboard.settings.edit.success'));
402
    }
403
404
    /**
405
     * Handle updating of the banner image.
406
     *
407
     * @param \CachetHQ\Cachet\Settings\Repository $setting
408
     *
409
     * @return void
0 ignored issues
show
Documentation introduced by James Brooks
Should the return type not be \Illuminate\Http\RedirectResponse|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
410
     */
411
    protected function handleUpdateBanner(Repository $setting)
412
    {
413
        $file = Binput::file('app_banner');
414
        $redirectUrl = $this->subMenu['theme']['url'];
415
416
        // Image Validation.
417
        // Image size in bytes.
418
        $maxSize = $file->getMaxFilesize();
419
420
        if ($file->getSize() > $maxSize) {
421
            return Redirect::to($redirectUrl)->withErrors(trans('dashboard.settings.app-setup.too-big', ['size' => $maxSize]));
422
        }
423
424
        if (!$file->isValid() || $file->getError()) {
425
            return Redirect::to($redirectUrl)->withErrors($file->getErrorMessage());
426
        }
427
428
        if (!Str::startsWith($file->getMimeType(), 'image/')) {
429
            return Redirect::to($redirectUrl)->withErrors(trans('dashboard.settings.app-setup.images-only'));
430
        }
431
432
        // Store the banner.
433
        $setting->set('app_banner', base64_encode(file_get_contents($file->getRealPath())));
434
435
        // Store the banner type.
436
        $setting->set('app_banner_type', $file->getMimeType());
437
    }
438
}
439