Passed
Push — master ( a5e8db...945884 )
by Danny
02:33
created

Configuration::cleanUpConfigForVCS()   D

Complexity

Conditions 9
Paths 130

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 16
nc 130
nop 0
dl 0
loc 31
rs 4.6666
c 0
b 0
f 0
1
<?php
2
namespace PressCLI\Option;
3
4
use PressCLI\Option\GlobalConfiguration;
5
use Symfony\Component\Console\Input\InputInterface;
6
use Symfony\Component\Console\Helper\QuestionHelper;
7
use Symfony\Component\Console\Output\OutputInterface;
8
9
class Configuration
10
{
11
    /**
12
     * Configuration file name.
13
     *
14
     * @var string
15
     */
16
    protected static $configFileName = '.press-cli.json';
17
18
    /**
19
     * Creates the configuration file.
20
     *
21
     * @param string          $directory
22
     * @param string          $name
23
     * @param InputInterface  $input
24
     * @param OutputInterface $output
25
     * @param QuestionHelper  $helper
26
     */
27
    public static function create($directory, $name, InputInterface $input, OutputInterface $output, QuestionHelper $helper)
28
    {
29
        // Create the global configuration if needed.
30
        if (!GlobalConfiguration::exists()) {
31
            $output->writeln('');
32
            GlobalConfiguration::create($output);
33
            $output->writeln('');
34
        }
35
36
        // Start local configuration.
37
        $output->writeln("\n<info>Creating project configuration...</info>");
38
        $configFile = rtrim($directory, '/') . '/' . self::$configFileName;
39
40
        if (file_exists($configFile)) {
41
            $output->writeln("<comment>Project configuration already exists at {$configFile}.</comment>");
42
43
            return;
44
        }
45
46
        // Add configuration from skeleton.
47
        $skeleton = self::configSkeleton($name, $input, $output, $helper);
48
        self::write($skeleton, $configFile);
49
50
        $output->writeln("<info>\nProject configuration created at {$configFile}!</info>");
51
    }
52
53
    /**
54
     * Writes the configuration to the file.
55
     *
56
     * @param array  $config
57
     * @param string $configFile
58
     */
59
    protected static function write($config, $configFile = null)
60
    {
61
        $configFile = is_null($configFile) ? self::$configFileName : $configFile;
62
        $config = json_encode($config, JSON_PRETTY_PRINT);
63
        $config = stripslashes($config);
64
        file_put_contents($configFile, $config);
65
    }
66
67
    /**
68
     * Removes the user password.
69
     */
70
    public static function cleanUpConfigForVCS()
71
    {
72
        $global = GlobalConfiguration::get();
73
        $afterInstall = isset($global['settings']['afterInstall']) ? $global['settings']['afterInstall'] : [];
74
75
        if (!$afterInstall) {
76
            return;
77
        }
78
79
        $config = self::get();
80
81
        // Remove user password.
82
        $removeUserPassword = isset($afterInstall['removeUserPassword']) ? (bool) $afterInstall['removeUserPassword'] : false;
83
        if ($removeUserPassword) {
84
            $config['user']['password'] = '';
85
        }
86
87
        // Remove user email.
88
        $removeUserPassword = isset($afterInstall['removeUserEmail']) ? (bool) $afterInstall['removeUserEmail'] : false;
89
        if ($removeUserPassword) {
90
            $config['user']['email'] = '';
91
        }
92
93
        // Remove user name.
94
        $removeUserPassword = isset($afterInstall['removeUserName']) ? (bool) $afterInstall['removeUserName'] : false;
95
        if ($removeUserPassword) {
96
            $config['user']['name'] = '';
97
        }
98
99
        self::write($config);
100
    }
101
102
    /**
103
     * Get the configuration.
104
     *
105
     * @return array
106
     */
107 View Code Duplication
    public static function get()
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...
108
    {
109
        if (!self::exists()) {
110
            return [];
111
        }
112
113
        $config = json_decode(file_get_contents(self::$configFileName), true);
114
115
        return $config;
116
    }
117
118
    /**
119
     * Configuration skeleton
120
     *
121
     * @return string
122
     */
123
    protected static function configSkeleton($name, InputInterface $input, OutputInterface $output, QuestionHelper $helper)
124
    {
125
        $config = presscli_config();
126
127
        // Merge global and local.
128
        $config = self::emptyConfig($config);
129
        $config = self::mergeConfiguration($config, GlobalConfiguration::get());
130
        $config = self::removeDuplicatePlugins($config);
131
132
        // Build out some standard stuff.
133
        $config['database']['name'] = self::makeDbName($name);
134
        $config['site']['url'] = self::makeURL($name);
135
        $config['theme']['name'] = self::makeThemeName($name);
136
137
        // Validate the configuration options.
138
        $config = Validator::validate($config, $helper, $input, $output);
139
140
        // Remove settings for local configuration.
141
        if (isset($config['settings'])) {
142
            unset($config['settings']);
143
        }
144
145
        return $config;
146
    }
147
148
    /**
149
     * Removes duplicate plugins.
150
     *
151
     * @param  array $config
152
     *
153
     * @return array
154
     */
155
    protected static function removeDuplicatePlugins($config)
156
    {
157
        $plugins = [];
158
        foreach ($config['plugins'] as $plugin) {
159
            $key = $plugin['plugin'];
160
            $plugins[ $key ] = $plugin;
161
        }
162
163
        $config['plugins'] = array_values($plugins);
164
165
        return $config;
166
    }
167
168
    /**
169
     * Merges the global configuration into the local configuration.
170
     *
171
     * @param  array $config1
172
     * @param  array $config2
173
     *
174
     * @return array
175
     */
176
    protected static function mergeConfiguration($config1, $config2)
177
    {
178
        foreach ($config2 as $key => $value) {
179
            if (array_key_exists($key, $config1) && is_array($value)) {
180
                $config1[$key] = self::mergeConfiguration($config1[$key], $config2[$key]);
181
            } else {
182
                $config1[$key] = $value;
183
            }
184
        }
185
186
        return $config1;
187
    }
188
189
    /**
190
     * Creates the database name from the initialization name.
191
     *
192
     * @param  string $name The name.
193
     *
194
     * @return string       The database name.
195
     */
196 View Code Duplication
    protected static function makeDbName($name)
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...
197
    {
198
        $dbname = self::sanitizeValue($name);
199
        $dbname = str_replace('-', '_', $dbname);
200
        $dbname = strtolower($dbname);
201
202
        return "wp_{$dbname}";
203
    }
204
205
    /**
206
     * Creates the URL from the initialization name.
207
     *
208
     * @param  string $name The name.
209
     *
210
     * @return string       The URL.
211
     */
212 View Code Duplication
    protected static function makeURL($name)
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...
213
    {
214
        $url = self::sanitizeValue($name);
215
        $url = str_replace('_', '-', $url);
216
        $url = strtolower($url);
217
218
        return "http://{$url}.dev";
219
    }
220
221
    /**
222
     * Creates the theme name from the initialization name.
223
     *
224
     * @param  string $name The name.
225
     *
226
     * @return string       The theme name.
227
     */
228 View Code Duplication
    protected static function makeThemeName($name)
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...
229
    {
230
        $themeName = self::sanitizeValue($name);
231
        $themeName = str_replace('_', '-', $themeName);
232
        $themeName = strtolower($themeName);
233
234
        return $themeName;
235
    }
236
237
    /**
238
     * Creates the database name from the initialization name.
239
     *
240
     * @param  string $value The value.
241
     *
242
     * @return string       The sanitized value.
243
     */
244
    protected static function sanitizeValue($value)
245
    {
246
        $value = str_replace(' ', '-', $value);
247
248
        return preg_replace('/[^A-Za-z0-9-_]/um', '', $value);
249
    }
250
251
    /**
252
     * Checks if the configuration exists.
253
     *
254
     * @return boolean
255
     */
256
    public static function exists()
257
    {
258
        return file_exists(self::$configFileName);
259
    }
260
261
    /**
262
     * Empty configuration values.
263
     *
264
     * @param  array $config The configuration.
265
     *
266
     * @return array         The emptied configuration.
267
     */
268
    protected static function emptyConfigValues($config) {
269
        return array_map(function($value) {
270
            if (is_array($value)) {
271
                $value = self::emptyConfigValues($value);
272
                return $value;
273
            }
274
275
            return '';
276
        }, $config);
277
    }
278
279
    /**
280
     * Empties the configuration.
281
     *
282
     * @param  array $config The configuration.
283
     *
284
     * @return array         The emptied configuration.
285
     */
286
    protected static function emptyConfig($config) {
287
        $config['plugins'] = [];
288
        $config['menus'] = [];
289
        $config['commands'] = isset($config['commands']) ? $config['commands'] : [];
290
        $config['commands'] = array_map(function($command) {
0 ignored issues
show
Unused Code introduced by
The parameter $command 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...
291
            return [];
292
        }, $config['commands']);
293
294
        $config = self::emptyConfigValues($config);
295
296
        return $config;
297
    }
298
}
299