Completed
Pull Request — master (#178)
by Fèvre
02:56
created

Installer   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 271
Duplicated Lines 22.14 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 2
dl 60
loc 271
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B postInstall() 0 38 5
A createAppConfig() 9 9 2
A createWritableDirectories() 0 21 3
A createRecaptchaConfig() 9 9 2
B setFolderPermissions() 0 37 5
A setDatabaseName() 20 20 3
A setSecuritySalt() 22 22 3
B setAccountPassword() 0 41 4

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
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link      http://cakephp.org CakePHP(tm) Project
12
 * @since     3.0.0
13
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
namespace App\Console;
16
17
use Cake\Auth\DefaultPasswordHasher;
18
use Cake\Utility\Security;
19
use Composer\Script\Event;
20
use Exception;
21
22
/**
23
 * Provides installation hooks for when this application is installed via
24
 * composer. Customize this class to suit your needs.
25
 */
26
class Installer
27
{
28
29
    /**
30
     * Does some routine installation tasks so people don't have to.
31
     *
32
     * @param \Composer\Script\Event $event The composer event object.
33
     *
34
     * @return void
35
     */
36
    public static function postInstall(Event $event)
37
    {
38
        $io = $event->getIO();
39
40
        $rootDir = dirname(dirname(__DIR__));
41
        static::createAppConfig($rootDir, $io);
42
        static::createRecaptchaConfig($rootDir, $io);
43
        static::setDatabaseName($rootDir, $io);
44
45
        // ask if the permissions should be changed
46
        if ($io->isInteractive()) {
47
            $validator = function ($arg) {
48
                if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
49
                    return $arg;
50
                }
51
                throw new Exception('This is not a valid answer. Please choose Y or n.');
52
            };
53
            $setFolderPermissions = $io->askAndValidate(
54
                '<info>Set Folder Permissions ? (Default to Y)</info> [<comment>Y,n</comment>]? ',
55
                $validator,
56
                10,
57
                'Y'
58
            );
59
60
            if (in_array($setFolderPermissions, ['Y', 'y'])) {
61
                static::setFolderPermissions($rootDir, $io);
62
            }
63
        } else {
64
            static::setFolderPermissions($rootDir, $io);
65
        }
66
67
        $newKey = static::setSecuritySalt($rootDir, $io);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $newKey is correct as static::setSecuritySalt($rootDir, $io) (which targets App\Console\Installer::setSecuritySalt()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
68
        static::setAccountPassword($rootDir, $io, $newKey);
69
70
        if (class_exists('\Cake\Codeception\Console\Installer')) {
71
            \Cake\Codeception\Console\Installer::customizeCodeceptionBinary($event);
72
        }
73
    }
74
75
    /**
76
     * Create the config/app.php file if it does not exist.
77
     *
78
     * @param string $dir The application's root directory.
79
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
80
     *
81
     * @return void
82
     */
83 View Code Duplication
    public static function createAppConfig($dir, $io)
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...
84
    {
85
        $appConfig = $dir . '/config/app.php';
86
        $defaultConfig = $dir . '/config/app.default.php';
87
        if (!file_exists($appConfig)) {
88
            copy($defaultConfig, $appConfig);
89
            $io->write('Created `config/app.php` file');
90
        }
91
    }
92
93
    /**
94
     * Create the `logs` and `tmp` directories.
95
     *
96
     * @param string $dir The application's root directory.
97
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
98
     * @return void
99
     */
100
    public static function createWritableDirectories($dir, $io)
101
    {
102
        $paths = [
103
            'logs',
104
            'tmp',
105
            'tmp/cache',
106
            'tmp/cache/models',
107
            'tmp/cache/persistent',
108
            'tmp/cache/views',
109
            'tmp/sessions',
110
            'tmp/tests'
111
        ];
112
113
        foreach ($paths as $path) {
114
            $path = $dir . '/' . $path;
115
            if (!file_exists($path)) {
116
                mkdir($path);
117
                $io->write('Created `' . $path . '` directory');
118
            }
119
        }
120
    }
121
122
    /**
123
     * Create the config/recaptcha.php file if it does not exist.
124
     *
125
     * @param string $dir The application's root directory.
126
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
127
     *
128
     * @return void
129
     */
130 View Code Duplication
    public static function createRecaptchaConfig($dir, $io)
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...
131
    {
132
        $appConfig = $dir . '/config/recaptcha.php';
133
        $defaultConfig = $dir . '/config/recaptcha.default.php';
134
        if (!file_exists($appConfig)) {
135
            copy($defaultConfig, $appConfig);
136
            $io->write('Created `config/recaptcha.php` file');
137
        }
138
    }
139
140
    /**
141
     * Set globally writable permissions on the "tmp" and "logs" directory.
142
     *
143
     * This is not the most secure default, but it gets people up and running quickly.
144
     *
145
     * @param string $dir The application's root directory.
146
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
147
     * @return void
148
     */
149
    public static function setFolderPermissions($dir, $io)
150
    {
151
        // Change the permissions on a path and output the results.
152
        $changePerms = function ($path, $perms, $io) {
153
            // Get permission bits from stat(2) result.
154
            $currentPerms = fileperms($path) & 0777;
155
            if (($currentPerms & $perms) == $perms) {
156
                return;
157
            }
158
159
            $res = chmod($path, $currentPerms | $perms);
160
            if ($res) {
161
                $io->write('Permissions set on ' . $path);
162
            } else {
163
                $io->write('Failed to set permissions on ' . $path);
164
            }
165
        };
166
167
        $walker = function ($dir, $perms, $io) use (&$walker, $changePerms) {
168
            $files = array_diff(scandir($dir), ['.', '..']);
169
            foreach ($files as $file) {
170
                $path = $dir . '/' . $file;
171
172
                if (!is_dir($path)) {
173
                    continue;
174
                }
175
176
                $changePerms($path, $perms, $io);
177
                $walker($path, $perms, $io);
178
            }
179
        };
180
181
        $worldWritable = bindec('0000000111');
182
        $walker($dir . '/tmp', $worldWritable, $io);
183
        $changePerms($dir . '/tmp', $worldWritable, $io);
184
        $changePerms($dir . '/logs', $worldWritable, $io);
185
    }
186
187
    /**
188
     * Set the datasources.default.database value in the application's config file.
189
     *
190
     * @param string $dir The application's root directory.
191
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
192
     *
193
     * @return void
194
     */
195 View Code Duplication
    public static function setDatabaseName($dir, $io)
1 ignored issue
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...
196
    {
197
        $config = $dir . '/config/app.php';
198
        $content = file_get_contents($config);
199
200
        $databaseName = $io->ask('What is your new database name ? ', 'xeta');
201
        $content = str_replace('__DATABASE__', $databaseName, $content, $count);
202
203
        if ($count == 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $count of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
204
            $io->write('No Datasources.default.database placeholder to replace.');
205
            return;
206
        }
207
208
        $result = file_put_contents($config, $content);
209
        if ($result) {
210
            $io->write('Updated Datasources.default.database value in config/app.php');
211
            return;
212
        }
213
        $io->write('Unable to update Datasources.default.database value.');
214
    }
215
216
    /**
217
     * Set the security.salt value in the application's config file.
218
     *
219
     * @param string $dir The application's root directory.
220
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
221
     * @return void
222
     */
223 View Code Duplication
    public static function setSecuritySalt($dir, $io)
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...
224
    {
225
        $config = $dir . '/config/app.php';
226
        $content = file_get_contents($config);
227
228
        $newKey = hash('sha256', Security::randomBytes(64));
229
        $content = str_replace('__SALT__', $newKey, $content, $count);
230
231
        if ($count == 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $count of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
232
            $io->write('No Security.salt placeholder to replace.');
233
234
            return;
235
        }
236
237
        $result = file_put_contents($config, $content);
238
        if ($result) {
239
            $io->write('Updated Security.salt value in config/app.php');
240
241
            return;
242
        }
243
        $io->write('Unable to update Security.salt value.');
244
    }
245
246
    /**
247
     * Set up the admin and member password for the database.
248
     *
249
     * @param string $dir The application's root directory.
250
     * @param \Composer\IO\IOInterface $io IO interface to write to console.
251
     * @param string $newKey The new security.salt.
252
     *
253
     * @return void
254
     */
255
    public static function setAccountPassword($dir, $io, $newKey = null)
256
    {
257
        if ($newKey == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $newKey of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
258
            $io->write('The new Security.salt value is empty in config/app.php, can\'t set up the password.');
259
            return;
260
        }
261
262
        $database = $dir . '/config/Schema/xeta.sql';
263
        $content = file_get_contents($database);
264
265
        $adminPass = 'administrator';
266
        $memberPass = 'testaccount';
267
268
        $hasher = new DefaultPasswordHasher();
269
270
        $replacement = [
271
            $hasher->hash($adminPass),
272
            $hasher->hash($memberPass),
273
        ];
274
275
        $search = [
276
            '__ADMINPASSWORD__',
277
            '__MEMBERPASSWORD__'
278
        ];
279
280
        $content = str_replace($search, $replacement, $content, $count);
281
282
        if ($count != 2) {
283
            $io->write('Error, there was no password to replace.');
284
            return;
285
        }
286
287
        $result = file_put_contents($database, $content);
288
289
        if ($result) {
290
            $io->write('Set up Admin & Member passwords successfully !');
291
            return;
292
        }
293
294
        $io->write('Unable to set up Admin & Member passwords.');
295
    }
296
}
297