InstallController   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 201
Duplicated Lines 3.98 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 20
c 2
b 0
f 1
lcom 1
cbo 3
dl 8
loc 201
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B getIndex() 8 25 4
A postStep1() 0 15 2
A postStep2() 0 19 2
B postStep3() 0 60 6
A writeEnv() 0 11 4
A keyGenerate() 0 12 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of Gitamin.
5
 *
6
 * Copyright (C) 2015-2016 The Gitamin Team
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 Gitamin\Http\Controllers;
13
14
use Gitamin\Models\Setting;
15
use Gitamin\Models\User;
16
use Illuminate\Support\Facades\Auth;
17
use Illuminate\Support\Facades\Config;
18
use Illuminate\Support\Facades\Redirect;
19
use Illuminate\Support\Facades\Request;
20
use Illuminate\Support\Facades\Response;
21
use Illuminate\Support\Facades\Session;
22
use Illuminate\Support\Facades\Validator;
23
use Illuminate\Support\Facades\View;
24
25
class InstallController extends Controller
26
{
27
    /**
28
     * Array of cache drivers.
29
     *
30
     * @var string[]
31
     */
32
    protected $cacheDrivers = [
33
        'file' => 'File',
34
        'memcached' => 'Memcached',
35
        'redis' => 'Redis',
36
        'apc' => 'APC(u)',
37
        'array' => 'Array',
38
        'database' => 'Database',
39
    ];
40
41
    /**
42
     * Create a new install controller instance.
43
     */
44
    public function __construct()
45
    {
46
        $this->beforeFilter('csrf', ['only' => ['postGitamin']]);
0 ignored issues
show
Deprecated Code introduced by
The method Illuminate\Routing\Controller::beforeFilter() has been deprecated with message: since version 5.1.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
47
    }
48
49
    /**
50
     * Returns the install page.
51
     *
52
     * @return \Illuminate\View\View
53
     */
54
    public function getIndex()
55
    {
56
        // If we've copied the .env.example file, then we should try and reset it.
57
        if (strlen(Config::get('app.key')) !== 32) {
58
            $this->keyGenerate();
59
        }
60
61
        $supportedLanguages = Request::getLanguages();
62
        $userLanguage = Config::get('app.locale');
63
64 View Code Duplication
        foreach ($supportedLanguages as $language) {
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...
65
            $language = str_replace('_', '-', $language);
66
67
            if (isset($this->langs[$language])) {
0 ignored issues
show
Bug introduced by
The property langs 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...
68
                $userLanguage = $language;
69
                break;
70
            }
71
        }
72
73
        return View::make('install')
74
            ->withPageTitle(trans('install.install'))
75
            ->withCacheDrivers($this->cacheDrivers)
76
            ->withUserLanguage($userLanguage)
77
            ->withAppUrl(Request::root());
78
    }
79
80
    /**
81
     * Handles validation on step one of the install form.
82
     *
83
     * @return \Illuminate\Http\Response
84
     */
85
    public function postStep1()
86
    {
87
        $postData = Request::all();
88
89
        $v = Validator::make($postData, [
90
            'env.cache_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
91
            'env.session_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
92
        ]);
93
94
        if ($v->passes()) {
95
            return Response::json(['status' => 1]);
96
        }
97
98
        return Response::json(['errors' => $v->getMessageBag()], 400);
99
    }
100
101
    /**
102
     * Handles validation on step two of the install form.
103
     *
104
     * @return \Illuminate\Http\Response
105
     */
106
    public function postStep2()
107
    {
108
        $postData = Request::all();
109
110
        $v = Validator::make($postData, [
111
            'env.cache_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
112
            'env.session_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
113
            'settings.app_name' => 'required',
114
            'settings.app_domain' => 'required',
115
            'settings.app_timezone' => 'required',
116
            'settings.app_locale' => 'required',
117
        ]);
118
119
        if ($v->passes()) {
120
            return Response::json(['status' => 1]);
121
        }
122
123
        return Response::json(['errors' => $v->getMessageBag()], 400);
124
    }
125
126
    /**
127
     * Handles the actual app install, including user, settings and env.
128
     *
129
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
130
     */
131
    public function postStep3()
132
    {
133
        $postData = Request::all();
134
135
        $v = Validator::make($postData, [
136
            'env.cache_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
137
            'env.session_driver' => 'required|in:'.implode(',', array_keys($this->cacheDrivers)),
138
            'settings.app_name' => 'required',
139
            'settings.app_domain' => 'required',
140
            'settings.app_timezone' => 'required',
141
            'settings.app_locale' => 'required',
142
            'user.username' => ['required', 'regex:/\A(?!.*[:;]-\))[ -~]+\z/'],
143
            'user.email' => 'email|required',
144
            'user.password' => 'required',
145
        ]);
146
147
        if ($v->passes()) {
148
            // Pull the user details out.
149
            $userDetails = array_pull($postData, 'user');
150
151
            $user = User::create([
152
                'username' => $userDetails['username'],
153
                'email' => $userDetails['email'],
154
                'password' => $userDetails['password'],
155
                'level' => 1,
156
            ]);
157
158
            Auth::login($user);
159
160
            $settings = array_pull($postData, 'settings');
161
162
            foreach ($settings as $settingName => $settingValue) {
163
                Setting::create([
164
                    'name' => $settingName,
165
                    'value' => $settingValue,
166
                ]);
167
            }
168
169
            $envData = array_pull($postData, 'env');
170
171
            // Write the env to the .env file.
172
            foreach ($envData as $envKey => $envValue) {
173
                $this->writeEnv($envKey, $envValue);
174
            }
175
176
            Session::flash('install.done', true);
177
178
            if (Request::ajax()) {
179
                return Response::json(['status' => 1]);
180
            }
181
182
            return Redirect::to('dashboard');
183
        }
184
185
        if (Request::ajax()) {
186
            return Response::json(['errors' => $v->getMessageBag()], 400);
187
        }
188
189
        return Redirect::route('install.index')->withInput()->withErrors($v->getMessageBag());
190
    }
191
192
    /**
193
     * Writes to the .env file with given parameters.
194
     *
195
     * @param string $key
196
     * @param mixed  $value
197
     */
198
    protected function writeEnv($key, $value)
199
    {
200
        static $path = null;
201
202
        if ($path === null || ($path !== null && file_exists($path))) {
203
            $path = base_path('.env');
204
            file_put_contents($path, str_replace(
205
                env(strtoupper($key)), $value, file_get_contents($path)
206
            ));
207
        }
208
    }
209
210
    /**
211
     * Generate the app.key value.
212
     */
213
    protected function keyGenerate()
214
    {
215
        $key = str_random(42);
216
217
        $path = base_path('.env');
218
219
        file_put_contents($path, str_replace(
220
            Config::get('app.key'), $key, file_get_contents($path)
221
        ));
222
223
        Config::set('app.key', $key);
224
    }
225
}
226