Completed
Push — master ( 265d0d...5b91fe )
by Nazar
07:12
created

Options::apply_formatting()   C

Complexity

Conditions 14
Paths 14

Size

Total Lines 47
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 15.1335

Importance

Changes 0
Metric Value
cc 14
eloc 38
nc 14
nop 1
dl 0
loc 47
ccs 32
cts 39
cp 0.8205
crap 15.1335
rs 5.0622
c 0
b 0
f 0

How to fix   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
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016-2017, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Config;
9
use
10
	cs\Config,
11
	cs\DB;
12
13
/**
14
 * Class for getting of db and storage configuration of module
15
 */
16
class Options {
17
	/**
18
	 * Get formats for all supported options
19
	 *
20
	 * Format includes option type, default value, supported values or ranges, whether option is password or is multilingual
21
	 *
22
	 * @return array[]
23
	 */
24 6
	public static function get_formatting () {
25 6
		$formatting                                               = static::get_formatting_const();
26 6
		$formatting['set_single']['language']['values']           = static::get_active_languages();
27 6
		$formatting['set_single']['timezone']['values']           = get_timezones_list();
28 6
		$formatting['set_single']['default_module']['values']     = static::get_modules_that_can_be_default();
29 6
		$formatting['set_single']['theme']['values']              = static::get_themes();
30 6
		$formatting['set_multiple']['active_languages']['values'] = static::get_languages();
31 6
		return static::get_formatting_normalize($formatting);
32
	}
33
	/**
34
	 * @return array[]
35
	 */
36 108
	protected static function get_formatting_const () {
37
		return [
38 108
			'array'        => [
39
				'url'           => [],
40
				'cookie_domain' => []
41
			],
42
			'int_bool'     => [
43 90
				'site_mode'                         => 1,
44 90
				'title_reverse'                     => 0,
45 90
				'cache_compress_js_css'             => 1,
46 90
				'frontend_load_optimization'        => 1,
47 90
				'vulcanization'                     => 1,
48 90
				'put_js_after_body'                 => 1,
49 90
				'disable_webcomponents'             => 0,
50 90
				'multilingual'                      => 0,
51 90
				'db_balance'                        => 0,
52 90
				'db_mirror_mode'                    => DB::MIRROR_MODE_MASTER_MASTER,
53 90
				'gravatar_support'                  => 0,
54 90
				'smtp'                              => 0,
55 90
				'smtp_auth'                         => 0,
56 90
				'allow_user_registration'           => 1,
57 90
				'require_registration_confirmation' => 1,
58 90
				'auto_sign_in_after_registration'   => 1,
59 90
				'registration_confirmation_time'    => 1,
60 90
				'remember_user_ip'                  => 0,
61 90
				'simple_admin_mode'                 => 1
62
			],
63
			'int_range'    => [
64
				'inserts_limit'         => [
65
					'min'   => 1,
66
					'value' => 1000
67
				],
68
				'key_expire'            => [
69
					'min'   => 1,
70
					'value' => 60 * 2
71
				],
72
				'session_expire'        => [
73
					'min'   => 1,
74
					'value' => 3600 * 24 * 30
75
				],
76
				'update_ratio'          => [
77
					'min'   => 0,
78
					'max'   => 100,
79
					'value' => 75
80
				],
81
				'password_min_length'   => [
82
					'min'   => 1,
83
					'value' => 4
84
				],
85
				'password_min_strength' => [
86
					'min'   => 0,
87
					'max'   => 7,
88
					'value' => 3
89
				]
90
			],
91
			'set_single'   => [
92
				'smtp_secure'    => [
93
					'value'  => '',
94
					'values' => ['', 'ssl', 'tls']
95
				],
96
				'language'       => [
97
					'value'  => 'English',
98
					'source' => 'active_languages'
99
				],
100
				'timezone'       => [
101
					'value' => 'UTC'
102
				],
103
				'default_module' => [
104
					'value' => Config::SYSTEM_MODULE
105
				],
106
				'theme'          => [
107
					'value' => Config::SYSTEM_THEME
108
				]
109
			],
110
			'set_multiple' => [
111
				'active_languages' => [
112
					'value' => [
113
						'English'
114
					]
115
				]
116
			],
117
			'string'       => [
118
				'admin_email'   => '',
119
				'cookie_prefix' => '',
120
				'smtp_host'     => '',
121
				'smtp_port'     => '',
122
				'smtp_user'     => '',
123
				'smtp_password' => [
124
					'value'    => '',
125
					'password' => true
126
				],
127
				'mail_from'     => ''
128
			],
129
			'text'         => [
130
				'title_delimiter' => ' | ',
131
				'site_name'       => [
132
					'multilingual' => true,
133
					'value'        => ''
134
				],
135
				'closed_title'    => [
136
					'multilingual' => true,
137
					'value'        => 'Site closed'
138
				],
139
				'mail_from_name'  => [
140
					'multilingual' => true,
141
					'value'        => 'Administrator'
142
				]
143
			],
144
			'html'         => [
145
				'closed_text'    => [
146
					'multilingual' => true,
147
					'value'        => '<p>Site closed for maintenance</p>'
148
				],
149
				'mail_signature' => [
150
					'multilingual' => true,
151
					'value'        => ''
152
				]
153
			]
154
		];
155
	}
156
	/**
157
	 * @return array[]
158
	 */
159 108
	protected static function get_formatting_const_plain () {
160 108
		static $formatting;
161 108
		if (!isset($formatting)) {
162 108
			$formatting = array_merge(...array_values(static::get_formatting_const()));
0 ignored issues
show
Bug introduced by
array_values(static::get_formatting_const()) is expanded, but the parameter $array1 of array_merge() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

162
			$formatting = array_merge(/** @scrutinizer ignore-type */ ...array_values(static::get_formatting_const()));
Loading history...
163
		}
164 108
		return $formatting;
165
	}
166
	/**
167
	 * @return string[]
168
	 */
169 6
	protected static function get_languages () {
170 6
		$languages = defined('LANGUAGES')
171 6
			? array_unique(
172 6
				array_merge(
173 6
					_mb_substr(get_files_list(LANGUAGES, '/^.*?\.php$/i', 'f'), 0, -4) ?: [],
0 ignored issues
show
Bug introduced by
It seems like _mb_substr(get_files_lis...'f'), 0, -4) ?: array() can also be of type string; however, parameter $array1 of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
					/** @scrutinizer ignore-type */ _mb_substr(get_files_list(LANGUAGES, '/^.*?\.php$/i', 'f'), 0, -4) ?: [],
Loading history...
174 6
					_mb_substr(get_files_list(LANGUAGES, '/^.*?\.json$/i', 'f'), 0, -5) ?: []
0 ignored issues
show
Bug introduced by
It seems like _mb_substr(get_files_lis...'f'), 0, -5) ?: array() can also be of type string; however, parameter $array2 of array_merge() does only seem to accept null|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

174
					/** @scrutinizer ignore-type */ _mb_substr(get_files_list(LANGUAGES, '/^.*?\.json$/i', 'f'), 0, -5) ?: []
Loading history...
175
				)
176
			)
177 6
			: ['English'];
178 6
		asort($languages);
179 6
		return $languages;
180
	}
181
	/**
182
	 * @return string[]
183
	 */
184 6
	protected static function get_themes () {
185 6
		$themes = defined('THEMES') ? get_files_list(THEMES, false, 'd') : [Config::SYSTEM_THEME];
186 6
		asort($themes);
187 6
		return $themes;
188
	}
189
	/**
190
	 * @return string[]
191
	 */
192 6
	protected static function get_modules_that_can_be_default () {
193 6
		$Config = Config::instance(true);
194 6
		if (!defined('MODULES') || !isset($Config->components['modules'])) {
195
			return [Config::SYSTEM_MODULE];
196
		}
197
		/** @noinspection PhpParamsInspection */
198 6
		return array_filter(
199 6
			array_keys($Config->components['modules']),
200
			function ($module) use ($Config) {
201 6
				return $Config->module($module) && file_exists_with_extension(MODULES."/$module/index", ['php', 'html', 'json']);
202 6
			}
203
		);
204
	}
205
	/**
206
	 * @return string[]
207
	 */
208 6
	protected static function get_active_languages () {
209 6
		$Config = Config::instance(true);
210 6
		if (!isset($Config->core['active_languages'])) {
211
			return ['English'];
212
		}
213
		/** @noinspection PhpIncompatibleReturnTypeInspection */
214 6
		return $Config->core['active_languages'];
215
	}
216
	/**
217
	 * @param array[] $format
218
	 *
219
	 * @return array[]
220
	 */
221 6
	protected static function get_formatting_normalize ($format) {
222 6
		foreach ($format as $type => &$items) {
223 6
			foreach ($items as $item => &$data) {
224 6
				if (!is_array($data) || !isset($data['value'])) {
225
					$data = [
226 6
						'value' => $data
227
					];
228
				}
229 6
				$data['type'] = $type;
230 6
				if (($type == 'set_single' || $type == 'set_multiple') && !is_array_assoc($data['values'])) {
231 6
					$data['values'] = array_combine($data['values'], $data['values']);
232
				}
233
			}
234 6
			unset($data);
235
		}
236 6
		return array_merge(...array_values($format));
0 ignored issues
show
Bug introduced by
array_values($format) is expanded, but the parameter $array1 of array_merge() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
		return array_merge(/** @scrutinizer ignore-type */ ...array_values($format));
Loading history...
237
	}
238
	/**
239
	 * Get default values for all supported options
240
	 *
241
	 * @return array
242
	 */
243 108
	public static function get_defaults () {
244 108
		$formatting = static::get_formatting_const_plain();
245 108
		foreach ($formatting as &$f) {
246 108
			if (isset($f['value'])) {
247 108
				$f = $f['value'];
248
			}
249
		}
250 108
		return $formatting;
251
	}
252
	/**
253
	 * Get list of multilingual options
254
	 *
255
	 * @return string[]
256
	 */
257 18
	public static function get_multilingual () {
258 18
		$formatting = static::get_formatting_const_plain();
259 18
		$result     = [];
260 18
		foreach ($formatting as $key => $f) {
261 18
			if (isset($f['multilingual'])) {
262 18
				$result[] = $key;
263
			}
264
		}
265 18
		return $result;
266
	}
267
	/**
268
	 * Take options and check each value according to needed format, correct value or use default if needed
269
	 *
270
	 * @param array $target_options
271
	 *
272
	 * @return array
273
	 */
274 6
	public static function apply_formatting ($target_options) {
275 6
		$options = static::get_formatting();
276 6
		foreach ($target_options as $option => &$value) {
277 6
			if (!isset($options[$option])) {
278 3
				unset($target_options[$option]);
279
			} else {
280 6
				$format = $options[$option];
281 6
				switch ($format['type']) {
282
					case 'array':
283 6
						$value = xap((array)$value);
284 6
						break;
285
					case 'int_bool':
286 6
						$value = (int)(bool)$value;
287 6
						break;
288
					case 'int_range':
289 6
						if (isset($format['min'])) {
290 6
							$value = max($format['min'], (int)$value);
291
						}
292 6
						if (isset($format['max'])) {
293 6
							$value = min($format['max'], (int)$value);
294
						}
295 6
						break;
296
					case 'set_single':
297 6
						$value = (string)$value;
298 6
						if (!in_array($value, $format['values'], true)) {
299 3
							$value = $format['value'];
300
						}
301 6
						break;
302
					case 'set_multiple':
303 6
						$value = array_filter(
304 6
							(array)$value,
305 6
							function ($value) use ($format) {
306 6
								return in_array((string)$value, $format['values'], true);
307 6
							}
308
						);
309 6
						$value = $value ?: [$format['value']];
310 6
						break;
311
					case 'text':
312 6
						$value = xap($value);
313 6
						break;
314
					case 'html':
315 6
						$value = xap($value, true);
316 6
						break;
317
				}
318
			}
319
		}
320 6
		return $target_options;
321
	}
322
}
323