Completed
Pull Request — master (#112)
by Christopher
09:33
created

InstallController::getInstallDatabase()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 57
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 38
c 1
b 1
f 0
nc 12
nop 3
dl 0
loc 57
rs 8.7433

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 TechWilk\Rota\Controller;
4
5
use Locale;
6
use Propel\Generator\Application;
7
use Propel\Runtime\Propel;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Symfony\Component\Console\Input\ArrayInput;
11
use Symfony\Component\Console\Output\BufferedOutput;
12
use TechWilk\Rota\Crypt;
13
use TechWilk\Rota\Settings;
14
use TechWilk\Rota\SettingsQuery;
15
use TechWilk\Rota\Site;
16
use TechWilk\Rota\User;
17
use TechWilk\Rota\UserQuery;
18
19
class InstallController extends BaseController
20
{
21
    public function getInstall(ServerRequestInterface $request, ResponseInterface $response, $args)
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...
Unused Code introduced by
The parameter $args 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...
22
    {
23
        $this->logger->info("Fetch install GET '/install'");
24
25
        $stage = 1;
26
27
        $configPath = __DIR__.'/../../../config';
28
        if (
29
            file_exists($configPath.'/auth.php')
30
            && file_exists($configPath.'/database.php')
31
            && file_exists($configPath.'/email.php')
32
            && file_exists($configPath.'/recording.php')
33
        ) {
34
            $stage = 2;
35
        }
36
37
        try {
38
            $existingUserCount = UserQuery::create()->count();
39
            if ($existingUserCount > 0) {
40
                return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('login'));
41
            }
42
            $stage = 3;
43
        } catch (\Propel\Runtime\Exception\PropelException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
44
        }
45
46
        return $this->view->render($response, 'install.twig', ['stage' => $stage]);
47
48
        //return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('install-database'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
49
    }
50
51
    public function getInstallDatabase(ServerRequestInterface $request, ResponseInterface $response, $args)
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...
Unused Code introduced by
The parameter $args 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...
52
    {
53
        $this->logger->info("Fetch database install GET '/install/database'");
54
55
        try {
56
            $existingUserCount = UserQuery::create()->count();
57
            if ($existingUserCount > 0) {
58
                return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('login'));
59
            }
60
        } catch (\Propel\Runtime\Exception\PropelException $e) {
61
            if ($e->getPrevious()->getCode() !== '42S02') {
62
                return $response;
63
            }
64
        }
65
66
        $site = new Site();
67
        $config = $site->getConfig();
0 ignored issues
show
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
68
69
        $propelGenerator = new Application('Propel', Propel::VERSION);
70
        $propelGenerator->setAutoExit(false);
71
        $propelGenerator->add(new \Propel\Generator\Command\SqlBuildCommand());
72
        $propelGenerator->add(new \Propel\Generator\Command\SqlInsertCommand());
73
74
        $output = new BufferedOutput();
75
76
        $input = new ArrayInput([
77
            'command'      => 'sql:build',
78
            '-vvv'         => true,
79
            '--overwrite'  => true,
80
            '--config-dir' => __DIR__.'/../../../generated-conf',
81
            '--schema-dir' => __DIR__.'/../../../',
82
            '--output-dir' => __DIR__.'/../../../build/sql',
83
        ]);
84
        $propelGenerator->run($input, $output);
85
86
        $input = new ArrayInput([
87
            'command'      => 'sql:insert',
88
            '-vvv'         => true,
89
            '--config-dir' => __DIR__.'/../../../generated-conf',
90
            '--sql-dir'    => __DIR__.'/../../../build/sql',
91
        ]);
92
        $propelGenerator->run($input, $output);
93
94
        $outputString = $output->fetch();
95
        $this->logger->info($outputString);
96
97
        // check it was a success
98
        try {
99
            $existingUserCount = UserQuery::create()->count();
0 ignored issues
show
Unused Code introduced by
$existingUserCount is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
100
        } catch (\Propel\Runtime\Exception\PropelException $e) {
101
            if ($e->getPrevious()->getCode() === '42S02') {
102
                return $response->getBody()->write('Error installing database:'."\n".$outputString);
103
            }
104
        }
105
106
        return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('install'));
107
    }
108
109
    public function getFirstUserForm(ServerRequestInterface $request, ResponseInterface $response, $args)
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...
Unused Code introduced by
The parameter $args 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...
110
    {
111
        $this->logger->info("Fetch first user form GET '/install/user'");
112
113
        // don't run if we're already installed
114
        $existingUserCount = UserQuery::create()->count();
115
        if ($existingUserCount > 0) {
116
            return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('login'));
117
        }
118
119
        return $this->view->render($response, 'login-sign-up.twig', [
120
            'message' => 'Your password will be auto-generated and displayed on the next screen.',
121
        ]);
122
    }
123
124
    public function postFirstUserForm(ServerRequestInterface $request, ResponseInterface $response, $args)
0 ignored issues
show
Unused Code introduced by
The parameter $args 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...
125
    {
126
        $this->logger->info("Create first user POST '/install/user'");
127
128
        // don't run if we're already installed
129
        $existingUserCount = UserQuery::create()->count();
130
        if ($existingUserCount > 0) {
131
            return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('login'));
132
        }
133
134
        $data = $request->getParsedBody();
135
136
        $user = new User();
137
138
        $user->setFirstName($data['firstName']);
139
        $user->setLastName($data['lastName']);
140
        $user->setEmail($data['email']);
141
142
        $user->setIsAdmin(true);
143
        $user->setIsOverviewRecipient(true);
144
        $user->setRecieveReminderEmails(true);
145
146
        $password = Crypt::generateToken(20);
147
        $user->setPassword($password);
148
149
        $user->save();
150
151
        $this->populateDefaultSettings();
152
153
        return $this->view->render($response, 'login-credentials.twig', [
154
            'username' => $user->getEmail(),
155
            'message'  => 'Your password is: '.$password.' Copy it somewhere safe as it will not be displayed again. You can change it once you\'ve logged in.',
156
        ]);
157
    }
158
159
    protected function populateDefaultSettings()
160
    {
161
        // don't run if we're already got settings
162
        $existingSettings = SettingsQuery::create()->count();
163
        if ($existingSettings > 0) {
164
            return;
165
        }
166
167
        $settings = new Settings();
168
169
        $site = new Site();
170
        $path = $this->router->pathFor('home');
171
        $url = $site->getUrl()['base'];
172
        $url .= $path === '/' ? '' : $path;
173
        $settings->setSiteUrl($url);
174
175
        $settings->setOwner('Rota');
176
177
        $settings->setTimeZone(date_default_timezone_get());
178
        $settings->setLangLocale(class_exists('Locale') ? Locale::getDefault() : 'en_GB');
179
180
        $settings->setTimeFormatLong('%A, %B %e @ %I:%M %p');
181
        $settings->setTimeFormatNormal('%d/%m/%y %I:%M %p');
182
        $settings->setTimeFormatShort('%a, <strong>%b %e</strong>, %I:%M %p');
183
        $settings->setTimeOnlyFormat('%l %M %p');
184
        $settings->setDateOnlyFormat('%A');
185
        $settings->setDayOnlyFormat('%A, %B %e');
186
187
        $settings->setNotificationEmail(<<<'EMAIL'
188
Dear [name]
189
190
This is an automatic reminder.
191
192
You have the roles: [rotaoutput]
193
During the service on [date] in [location].
194
[eventdetails]
195
196
If you have arranged a swap, please let us know.
197
198
Many thanks for your continued service!
199
EMAIL
200
);
201
202
        $settings->setToken(Crypt::generateToken(100));
203
        $settings->setSkin('skin-blue');
204
205
        // @todo remove unused legacy settings
206
        $settings->setDebugMode(false);
207
208
        $settings->save();
209
    }
210
}
211