Completed
Push — master ( c90dfa...c2f681 )
by Juliette
23s
created

functions.php ➔ generate_version_dropdown()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 64
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 12
eloc 34
c 3
b 0
f 1
nc 12
nop 0
dl 0
loc 64
rs 6.0561

How to fix   Long Method    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
 * Some generic functions and mock objects for test variables.
4
 *
5
 * @package PHPCheatsheets
6
 */
7
8
// Prevent direct calls to this file.
9
if ( ! defined( 'APP_DIR' ) ) {
10
	header( 'Status: 403 Forbidden' );
11
	header( 'HTTP/1.1 403 Forbidden' );
12
	exit();
13
}
14
15
/**
16
 * Simple object to use for tests with the object variable type.
17
 */
18
class TestObject {
19
20
	/**
21
	 * A property.
22
	 *
23
	 * @var null
24
	 */
25
	var $test1;
26
27
	/**
28
	 * Another property.
29
	 *
30
	 * @var bool
31
	 */
32
	var $test2 = true;
33
34
35
	/**
36
	 * Example method.
37
	 *
38
	 * @param string $var
39
	 */
40
	function print_it( $var ) {
41
		echo htmlspecialchars( $var );
42
	}
43
}
44
45
/**
46
 * Another simple object to use for tests with the object variable type.
47
 */
48
class TestObjectToString extends TestObject {
49
50
	/**
51
	 * A third property.
52
	 *
53
	 * @var string
54
	 */
55
	var $test3 = 'some string';
56
57
58
	/**
59
	 * Example __toString method.
60
	 *
61
	 * @return string
62
	 */
63
	function __toString() {
64
		return $this->test3;
65
	}
66
}
67
68
69
/**
70
 * Helper function to compare strings, compatible with PHP4.
71
 *
72
 * @param mixed  $var1
73
 * @param mixed  $var2
74
 * @param string $function
75
 */
76
function pc_compare_strings( $var1, $var2, $function ) {
77
	$result = $function( $var1, $var2 );
78
	if ( is_int( $result ) ) {
79
		pr_int( $result );
80
	}
81
	else {
82
		pr_var( $result, '', true, true );
83
	}
84
}
85
86
87
/**
88
 * Catch errors to display in appendix.
89
 *
90
 * @param int    $error_no
91
 * @param string $error_str
92
 * @param string $error_file
93
 * @param int    $error_line
94
 *
95
 * @return null|false
96
 */
97
function do_handle_errors( $error_no, $error_str, $error_file, $error_line ) {
98
	if ( ! ( error_reporting() & $error_no ) ) {
99
		return;
100
	}
101
102
	if ( ! defined( 'E_STRICT' ) ) {
103
		define( 'E_STRICT', 2048 );
104
	}
105
	if ( ! defined( 'E_RECOVERABLE_ERROR' ) ) {
106
		define( 'E_RECOVERABLE_ERROR', 4096 );
107
	}
108
	if ( ! defined( 'E_DEPRECATED' ) ) {
109
		define( 'E_DEPRECATED', 8192 );
110
	}
111
	if ( ! defined( 'E_USER_DEPRECATED' ) ) {
112
		define( 'E_USER_DEPRECATED', 16384 );
113
	}
114
115
	switch ( $error_no ) {
116
		case E_ERROR: // 1 //
117
		case E_CORE_ERROR: // 16 //
118
		case E_COMPILE_ERROR: // 64 //
119
			$type  = 'Fatal error';
120
			$class = 'error';
121
			break;
122
123
		case E_USER_ERROR: // 256 //
124
			$type  = 'Fatal error';
125
			$class = 'error';
126
			break;
127
128
		case E_WARNING: // 2 //
129
		case E_CORE_WARNING: // 32 //
130
		case E_COMPILE_WARNING: // 128 //
131
			$type  = 'Warning';
132
			$class = 'warning';
133
			break;
134
135
		case E_USER_WARNING: // 512 //
136
			$type  = 'Warning';
137
			$class = 'warning';
138
			break;
139
140
		case E_PARSE: // 4 //
141
			$type  = 'Parse error';
142
			$class = 'error';
143
			break;
144
145
		case E_NOTICE: // 8 //
146
		case E_USER_NOTICE: // 1024 //
147
			$type  = 'Notice';
148
			$class = 'notice';
149
			break;
150
151
		case E_STRICT: // 2048 //
152
			$type  = 'Strict warning';
153
			$class = 'warning';
154
			break;
155
156
		case E_RECOVERABLE_ERROR: // 4096 //
157
			$type  = '(Catchable) Fatal error';
158
			$class = 'error';
159
			break;
160
161
		case E_DEPRECATED: // 8192 //
162
		case E_USER_DEPRECATED: // 16384 //
163
			$type  = 'Deprecated';
164
			$class = 'notice';
165
			break;
166
167
		default:
168
			$type  = 'Unknown error ( ' . $error_no . ' )';
169
			$class = 'error';
170
			break;
171
	}
172
173
174
	// Group some messages.
175
	$search = array(
176
		'array_key_exists() expects parameter 2 to be array',
177
		'key() expects parameter 1 to be array',
178
		'current() expects parameter 1 to be array',
179
		'array_filter() expects parameter 1 to be array',
180
		'preg_match() expects parameter 2 to be string',
181
		'strlen() expects parameter 1 to be string',
182
		'count_chars() expects parameter 1 to be string',
183
		'mb_strlen() expects parameter 1 to be string',
184
		'trim() expects parameter 1 to be string',
185
		'get_class() expects parameter 1 to be object',
186
		'get_resource_type() expects parameter 1 to be resource',
187
		'intdiv() expects parameter 1 to be integer',
188
		'intdiv() expects parameter 2 to be integer',
189
	);
190
191
	$replace = array(
192
		'array_key_exists() expects parameter 2 to be array, <em>null/boolean/integer/double/string/object/resource</em> given',
193
		'key() expects parameter 1 to be array, <em>null/boolean/integer/double/string/object/resource</em> given',
194
		'current() expects parameter 1 to be array, <em>null/boolean/integer/double/string/object/resource</em> given',
195
		'array_filter() expects parameter 1 to be array, <em>null/boolean/integer/double/string/object/resource</em> given',
196
		'preg_match() expects parameter 2 to be string, <em>array/object/resource</em> given',
197
		'strlen() expects parameter 1 to be string, <em>array/object/resource</em> given',
198
		'count_chars() expects parameter 1 to be string, <em>array/object/resource</em> given',
199
		'mb_strlen() expects parameter 1 to be string, <em>array/object/resource</em> given',
200
		'trim() expects parameter 1 to be string, <em>array/object/resource</em> given',
201
		'get_class() expects parameter 1 to be object, <em>boolean/integer/double/string/array/resource</em> given',
202
		'get_resource_type() expects parameter 1 to be resource, <em>null/boolean/integer/double/string/array/object</em> given',
203
		'intdiv() expects parameter 1 to be integer, <em>float/string/array/object/resource</em> given',
204
		'intdiv() expects parameter 2 to be integer, <em>float/string/array/object/resource</em> given',
205
	);
206
207
	// Group some more messages and make error message links work.
208
	$preg_search  = array(
209
		'`^(bc(?:add|sub|mul|div|mod|comp)|str(?:case|natcase|nat)?cmp|strcoll|similar_text|levenshtein)\(\) expects parameter ([12]) to be string, (?:array|object|resource) given$`',
210
		'`^fmod\(\) expects parameter ([12]) to be (double|float), (?:string|array|object|resource) given$`',
211
		'`^(is_(?:nan|(?:in)?finite))\(\) expects parameter ([12]) to be (double|float), (?:string|array|object|resource) given$`',
212
		'`^Object of class [A-Za-z]+ could not be converted to (int|double|float|string)$`',
213
		'`^Object of class [A-Za-z]+ to string conversion$`',
214
		'`^Cannot use object of type [A-Za-z]+ as array$`',
215
		'`<a href=(["\'])function\.`',
216
	);
217
	$preg_replace = array(
218
		'$1() expects parameter $2 to be string, <em>array/object/resource</em> given',
219
		'fmod() expects parameter $1 to be $2, <em>string/array/object/resource</em> given',
220
		'$1() expects parameter $2 to be $3, <em>string/array/object/resource</em> given',
221
		'Object of class <em>stdClass/TestObject/TestObjectToString</em> could not be converted to $1',
222
		'Object of class <em>stdClass/TestObject/TestObjectToString</em> to string conversion',
223
		'Cannot use object of type <em>stdClass/TestObject/TestObjectToString</em> as array',
224
		'<a href=$1http://php.net/function.',
225
	);
226
227
	foreach ( $search as $k => $s ) {
228
		if ( strpos( $error_str, $s ) === 0 ) {
229
			$error_str = $replace[ $k ];
230
			break;
231
		}
232
	}
233
	$error_str = preg_replace( $preg_search, $preg_replace, $error_str );
234
235
236
	$message = '<span class="' . $class . '">' . $type . '</span>: ' . $error_str;
237
238
	if ( isset( $GLOBALS['encountered_errors'] ) ) {
239
		// Ignore strict warnings (can't avoid having them if I want to keep this sheet working with PHP4).
240
		if ( $error_no !== E_STRICT ) {
241
			$key = get_error_key( $message );
242
243
			if ( $class === 'notice' || $class === 'warning' ) {
244
				$GLOBALS['has_error'][]['msg'] = ' (&nbsp;<span class="' . $class . '"><a href="#' . $GLOBALS['test'] . '-errors">#' . ( $key + 1 ) . '</a></span>&nbsp;)';
245
				return;
246
			}
247
			else if ( $class === 'error' ) {
248
				$GLOBALS['has_error'][]['msg'] = ' <span class="error">' . $type . ' (&nbsp;<a href="#' . $GLOBALS['test'] . '-errors">#' . ( $key + 1 ) . '</a>&nbsp;)</span>';
249
				return;
250
			}
251
			else {
252
				echo $message, ' in ', $error_file, ' on line ', $error_line, "<br />\n";
253
			}
254
		}
255
		else {
256
			return;
257
		}
258
	}
259
	else {
260
		if ( $error_no !== E_STRICT ) {
261
			echo $message, ' in ', $error_file, ' on line ', $error_line, "<br />\n";
262
		}
263
		else {
264
			return;
265
		}
266
	}
267
268
	return false; // Make sure it plays nice with other error handlers (remove if no other error handlers are set).
269
}
270
271
272
/**
273
 * Get the index key for an error message and add the error message to the global array if it doesn't exist yet.
274
 *
275
 * @param string $message
276
 *
277
 * @return int
278
 */
279
function get_error_key( $message ) {
280
	$key = array_search( $message, $GLOBALS['encountered_errors'] );
281
	if ( $key === false ) {
282
		$GLOBALS['encountered_errors'][] = $message;
283
		$key                             = array_search( $message, $GLOBALS['encountered_errors'] );
284
	}
285
	return $key;
286
}
287
288
289
/**
290
 * Determine the base url to use.
291
 *
292
 * @return string
293
 */
294
function determine_base_uri() {
295
	$valid_hosts = array(
296
		'phpcheatsheets.com',
297
		'phpcheatsheet.com',
298
		'phpcheatsheets.localdev',
299
		'localhost',
300
	);
301
302
	$base_uri = 'http://phpcheatsheets.com/';
303
304
	if ( isset( $_SERVER['HTTP_HOST'] ) && in_array( $_SERVER['HTTP_HOST'], $valid_hosts, true ) ) {
305
		$base_uri = 'http://' . $_SERVER['HTTP_HOST'] . determine_script_path();
306
	}
307
	elseif ( isset( $_SERVER['SERVER_NAME'] ) && in_array( $_SERVER['SERVER_NAME'], $valid_hosts, true ) ) {
308
		$base_uri = 'http://' . $_SERVER['SERVER_NAME'] . determine_script_path();
309
	}
310
311
	return $base_uri;
312
}
313
314
315
/**
316
 * Determine the script path part of the base url.
317
 *
318
 * @return string
319
 */
320
function determine_script_path() {
321
	if ( ! empty( $_SERVER['SCRIPT_NAME'] ) && stripos( $_SERVER['SCRIPT_NAME'], 'index.php' ) !== false ) {
322
		return substr( $_SERVER['SCRIPT_NAME'], 0, stripos( $_SERVER['SCRIPT_NAME'], 'index.php' ) );
323
	}
324
	else if ( ! empty( $_SERVER['REQUEST_URI'] ) && stripos( $_SERVER['REQUEST_URI'], 'index.php' ) !== false ) {
325
		return substr( $_SERVER['REQUEST_URI'], 0, stripos( $_SERVER['REQUEST_URI'], 'index.php' ) );
326
	}
327
	else {
328
		return '/';
329
	}
330
}
331
332
333
/**
334
 * PHP4 compat.
335
 */
336
if ( ! function_exists( 'stripos' ) ) {
337
	/**
338
	 * Make an equivalent to the PHP5 stripos() function available in PHP4.
339
	 *
340
	 * @param string $haystack
341
	 * @param string $needle
342
	 *
343
	 * @return int|false
344
	 */
345
	function stripos( $haystack, $needle ) {
346
		$haystack = strtolower( $haystack );
347
		$needle   = strtolower( $needle );
348
		return strpos( $haystack, $needle );
349
	}
350
}
351
352
353
/**
354
 * Generate dropdown list of available static versions.
355
 *
356
 * @return string
357
 */
358
function generate_version_dropdown() {
359
360
	$available = glob( APP_DIR . '/static_results/' . $GLOBALS['type'] . '/php*.html' );
361
	usort( $available, 'version_compare' );
362
	$available = array_reverse( $available );
363
364
	$optgroup = 100;
365
	$options  = array();
366
367
	$options_html          = '';
368
	$optgroup_html_pattern = '
369
					<optgroup label="PHP %1$s">%2$s' . "\n\t\t\t\t\t</optgroup>";
370
371
	$regex = sprintf( '`^%1$s/static_results/%2$s/php(([457]\.[0-9]+)\.[0-9-]+(?:(?:alpha|beta|RC)(?:[0-9])?)?)\.html$`',
372
		preg_quote( APP_DIR, '`' ),
373
		preg_quote( $GLOBALS['type'], '`' )
374
	);
375
376
	foreach ( $available as $file ) {
377
		if ( preg_match( $regex, $file, $match ) ) {
378
			if ( $options !== array() && ( version_compare( $optgroup, $match[2], '>' ) && $optgroup !== 100 ) ) {
379
				$options_html .= sprintf( $optgroup_html_pattern, $optgroup, implode( "\n", $options ) );
380
				$options       = array();
381
			}
382
			$optgroup = $match[2];
383
384
385
			$selected = '';
386
			if ( ( isset( $GLOBALS['autogen'] ) && $GLOBALS['autogen'] === true ) && $match[1] === PHP_VERSION ) {
387
				$selected = ' selected="selected"';
388
			}
389
			$options[] = sprintf( '
390
						<option value="php%1$s"%2$s>PHP %1$s</option>',
391
				htmlspecialchars( $match[1], ENT_QUOTES, 'UTF-8' ),
392
				$selected
393
			);
394
		}
395
	}
396
	// Add last group.
397
	if ( $options !== array() ) {
398
		$options_html .= sprintf( $optgroup_html_pattern, $optgroup, implode( "\n", $options ) );
399
	}
400
401
	$dropdown = sprintf( '
402
			<form action="%6$sindex.php" method="get" id="choose-version">
403
				<input type="hidden" name="page" value="%1$s" />
404
				<input type="hidden" id="phpv-tab" name="tab" value="%2$s" />
405
				<select id="phpversion-dropdown" name="phpversion">
406
					<optgroup label="Live">
407
						<option value="live" %3$s >PHP %4$s</option>
408
					</optgroup>
409
					%5$s
410
				</select>
411
			</form>',
412
		htmlspecialchars( $GLOBALS['type'], ENT_QUOTES, 'UTF-8' ),
413
		htmlspecialchars( $GLOBALS['tab'], ENT_QUOTES, 'UTF-8' ),
414
		( ( ! isset( $GLOBALS['autogen'] ) || $GLOBALS['autogen'] !== true ) ? ' selected="selected"' : '' ),
415
		htmlspecialchars( PHP_VERSION, ENT_QUOTES, 'UTF-8' ),
416
		$options_html,
417
		htmlspecialchars( BASE_URI, ENT_QUOTES, 'UTF-8' )
418
	);
419
420
	return $dropdown;
421
}
422