Completed
Push — renovate/jest-monorepo ( bbafd9...36469d )
by
unknown
33:09 queued 24:56
created

Jetpack_Cxn_Test_Base   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 423
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 423
rs 3.36
c 0
b 0
f 0
wmc 63
lcom 1
cbo 1

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add_test() 0 19 4
B list_tests() 0 20 9
A run_test() 0 7 2
A run_tests() 0 10 3
A raw_results() 0 19 5
A pass() 0 13 4
A list_fails() 0 12 5
A passing_test() 0 8 1
A skipped_test() 0 8 1
A failing_test() 0 24 5
B output_results_for_cli() 0 22 8
B output_results_for_core_site_health() 0 54 6
A output_fails_as_wp_error() 0 22 4
A encrypt_string_for_wpcom() 0 21 5

How to fix   Complexity   

Complex Class

Complex classes like Jetpack_Cxn_Test_Base often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Cxn_Test_Base, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Jetpack Connection Testing
4
 *
5
 * Framework for various "unit tests" against the Jetpack connection.
6
 *
7
 * Individual tests should be added to the class-jetpack-cxn-tests.php file.
8
 *
9
 * @author Brandon Kraft
10
 * @package Jetpack
11
 */
12
13
/**
14
 * "Unit Tests" for the Jetpack connection.
15
 *
16
 * @since 7.1.0
17
 */
18
class Jetpack_Cxn_Test_Base {
19
20
	/**
21
	 * Tests to run on the Jetpack connection.
22
	 *
23
	 * @var array $tests
24
	 */
25
	protected $tests = array();
26
27
	/**
28
	 * Results of the Jetpack connection tests.
29
	 *
30
	 * @var array $results
31
	 */
32
	protected $results = array();
33
34
	/**
35
	 * Status of the testing suite.
36
	 *
37
	 * Used internally to determine if a test should be skipped since the tests are already failing. Assume passing.
38
	 *
39
	 * @var bool $pass
40
	 */
41
	protected $pass = true;
42
43
	/**
44
	 * Jetpack_Cxn_Test constructor.
45
	 */
46
	public function __construct() {
47
		$this->tests   = array();
48
		$this->results = array();
49
	}
50
51
	/**
52
	 * Adds a new test to the Jetpack Connection Testing suite.
53
	 *
54
	 * @since 7.1.0
55
	 * @since 7.3.0 Adds name parameter and returns WP_Error on failure.
56
	 *
57
	 * @param callable $callable Test to add to queue.
58
	 * @param string   $name Unique name for the test.
59
	 * @param string   $type   Optional. Core Site Health type: 'direct' if test can be run during initial load or 'async' if test should run async.
60
	 * @param array    $groups Optional. Testing groups to add test to.
61
	 *
62
	 * @return mixed True if successfully added. WP_Error on failure.
63
	 */
64
	public function add_test( $callable, $name, $type = 'direct', $groups = array( 'default' ) ) {
65
		if ( is_array( $name ) ) {
66
			// Pre-7.3.0 method passed the $groups parameter here.
67
			return new WP_Error( __( 'add_test arguments changed in 7.3.0. Please reference inline documentation.', 'jetpack' ) );
68
		}
69
		if ( array_key_exists( $name, $this->tests ) ) {
70
			return new WP_Error( __( 'Test names must be unique.', 'jetpack' ) );
71
		}
72
		if ( ! is_callable( $callable ) ) {
73
			return new WP_Error( __( 'Tests must be valid PHP callables.', 'jetpack' ) );
74
		}
75
76
		$this->tests[ $name ] = array(
77
			'test'  => $callable,
78
			'group' => $groups,
79
			'type'  => $type,
80
		);
81
		return true;
82
	}
83
84
	/**
85
	 * Lists all tests to run.
86
	 *
87
	 * @since 7.3.0
88
	 *
89
	 * @param string $type Optional. Core Site Health type: 'direct' or 'async'. All by default.
90
	 * @param string $group Optional. A specific testing group. All by default.
91
	 *
92
	 * @return array $tests Array of tests with test information.
93
	 */
94
	public function list_tests( $type = 'all', $group = 'all' ) {
95
		if ( ! ( 'all' === $type || 'direct' === $type || 'async' === $type ) ) {
96
			_doing_it_wrong( 'Jetpack_Cxn_Test_Base->list_tests', 'Type must be all, direct, or async', '7.3.0' );
97
		}
98
99
		$tests = array();
100
		foreach ( $this->tests as $name => $value ) {
101
			// Get all valid tests by group staged.
102
			if ( 'all' === $group || $group === $value['group'] ) {
103
				$tests[ $name ] = $value;
104
			}
105
106
			// Next filter out any that do not match the type.
107
			if ( 'all' !== $type && $type !== $value['type'] ) {
108
				unset( $tests[ $name ] );
109
			}
110
		}
111
112
		return $tests;
113
	}
114
115
	/**
116
	 * Run a specific test.
117
	 *
118
	 * @since 7.3.0
119
	 *
120
	 * @param string $name Name of test.
121
	 *
122
	 * @return mixed $result Test result array or WP_Error if invalid name. {
123
	 * @type string $name Test name
124
	 * @type mixed  $pass True if passed, false if failed, 'skipped' if skipped.
125
	 * @type string $message Human-readable test result message.
126
	 * @type string $resolution Human-readable resolution steps.
127
	 * }
128
	 */
129
	public function run_test( $name ) {
130
		if ( array_key_exists( $name, $this->tests ) ) {
131
			return call_user_func( $this->tests[ $name ] );
132
		}
133
134
		return new WP_Error( __( 'There is no test by that name: ', 'jetpack' ) . $name );
135
	}
136
137
	/**
138
	 * Runs the Jetpack connection suite.
139
	 */
140
	public function run_tests() {
141
		foreach ( $this->tests as $test ) {
142
			$result          = call_user_func( $test['test'] );
143
			$result['group'] = $test['group'];
144
			$this->results[] = $result;
145
			if ( false === $result['pass'] ) {
146
				$this->pass = false;
147
			}
148
		}
149
	}
150
151
	/**
152
	 * Returns the full results array.
153
	 *
154
	 * @param string $group Testing group whose results we want. Defaults to "default" group. Use "all" for all tests.
155
	 * @return array Array of test results.
156
	 */
157
	public function raw_results( $group = 'default' ) {
158
		if ( ! $this->results ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
159
			$this->run_tests();
160
		}
161
162
		$results = $this->results;
163
164
		if ( 'all' === $group ) {
165
			return $results;
166
		}
167
168
		foreach ( $results as $test => $result ) {
169
			if ( ! in_array( $group, $result['group'], true ) ) {
170
				unset( $results[ $test ] );
171
			}
172
		}
173
174
		return $results;
175
	}
176
177
	/**
178
	 * Returns the status of the connection suite.
179
	 *
180
	 * @param string $group Testing group to check status of. Optional, default all tests.
181
	 *
182
	 * @return true|array True if all tests pass. Array of failed tests.
183
	 */
184
	public function pass( $group = 'default' ) {
185
		$results = $this->raw_results( $group );
186
187
		foreach ( $results as $result ) {
188
			// 'pass' could be true, false, or 'skipped'. We only want false.
189
			if ( isset( $result['pass'] ) && false === $result['pass'] ) {
190
				return false;
191
			}
192
		}
193
194
		return true;
195
196
	}
197
198
	/**
199
	 * Return array of failed test messages.
200
	 *
201
	 * @param string $group Testing group whose failures we want. Defaults to "default". Use "all" for all tests.
202
	 *
203
	 * @return false|array False if no failed tests. Otherwise, array of failed tests.
204
	 */
205
	public function list_fails( $group = 'default' ) {
206
		$results = $this->raw_results( $group );
207
208
		foreach ( $results as $test => $result ) {
209
			// We do not want tests that passed or ones that are misconfigured (no pass status or no failure message).
210
			if ( ! isset( $result['pass'] ) || false !== $result['pass'] || ! isset( $result['message'] ) ) {
211
				unset( $results[ $test ] );
212
			}
213
		}
214
215
		return $results;
216
	}
217
218
	/**
219
	 * Helper function to return consistent responses for a passing test.
220
	 *
221
	 * @param string $name Test name.
222
	 *
223
	 * @return array Test results.
224
	 */
225
	public static function passing_test( $name = 'Unnamed' ) {
226
		return array(
227
			'name'       => $name,
228
			'pass'       => true,
229
			'message'    => __( 'Test Passed!', 'jetpack' ),
230
			'resolution' => false,
231
		);
232
	}
233
234
	/**
235
	 * Helper function to return consistent responses for a skipped test.
236
	 *
237
	 * @param string $name Test name.
238
	 * @param string $message Reason for skipping the test. Optional.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $message not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
239
	 *
240
	 * @return array Test results.
241
	 */
242
	public static function skipped_test( $name = 'Unnamed', $message = false ) {
243
		return array(
244
			'name'       => $name,
245
			'pass'       => 'skipped',
246
			'message'    => $message,
247
			'resolution' => false,
248
		);
249
	}
250
251
	/**
252
	 * Helper function to return consistent responses for a failing test.
253
	 *
254
	 * @since 7.1.0
255
	 * @since 7.3.0 Added $action for resolution action link, $severity for issue severity.
256
	 *
257
	 * @param string $name Test name.
258
	 * @param string $message Message detailing the failure.
259
	 * @param string $resolution Optional. Steps to resolve.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $resolution not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
260
	 * @param string $action Optional. URL to direct users to self-resolve.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $action not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
261
	 * @param string $severity Optional. "critical" or "recommended" for failure stats. "good" for passing.
262
	 *
263
	 * @return array Test results.
264
	 */
265
	public static function failing_test( $name, $message, $resolution = false, $action = false, $severity = 'critical' ) {
266
		// Provide standard resolutions steps, but allow pass-through of non-standard ones.
267
		switch ( $resolution ) {
268
			case 'cycle_connection':
269
				$resolution = __( 'Please disconnect and reconnect Jetpack.', 'jetpack' ); // @todo: Link.
270
				break;
271
			case 'outbound_requests':
272
				$resolution = __( 'Please ask your hosting provider to confirm your server can make outbound requests to jetpack.com.', 'jetpack' );
273
				break;
274
			case 'support':
275
			case false:
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $resolution of type false|string against false; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
276
				$resolution = __( 'Please contact Jetpack support.', 'jetpack' ); // @todo: Link to support.
277
				break;
278
		}
279
280
		return array(
281
			'name'       => $name,
282
			'pass'       => false,
283
			'message'    => $message,
284
			'resolution' => $resolution,
285
			'action'     => $action,
286
			'severity'   => $severity,
287
		);
288
	}
289
290
	/**
291
	 * Provide WP_CLI friendly testing results.
292
	 *
293
	 * @param string $group Testing group whose results we are outputting. Default "default". Use "all" for all tests.
294
	 */
295
	public function output_results_for_cli( $group = 'default' ) {
296
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
297
			if ( Jetpack::is_development_mode() ) {
298
				WP_CLI::line( __( 'Jetpack is in Development Mode:', 'jetpack' ) );
299
				WP_CLI::line( Jetpack::development_mode_trigger_text() );
300
			}
301
			WP_CLI::line( __( 'TEST RESULTS:', 'jetpack' ) );
302
			foreach ( $this->raw_results( $group ) as $test ) {
303
				if ( true === $test['pass'] ) {
304
					WP_CLI::log( WP_CLI::colorize( '%gPassed:%n  ' . $test['name'] ) );
305
				} elseif ( 'skipped' === $test['pass'] ) {
306
					WP_CLI::log( WP_CLI::colorize( '%ySkipped:%n ' . $test['name'] ) );
307
					if ( $test['message'] ) {
308
						WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
309
					}
310
				} else { // Failed.
311
					WP_CLI::log( WP_CLI::colorize( '%rFailed:%n  ' . $test['name'] ) );
312
					WP_CLI::log( '         ' . $test['message'] ); // Number of spaces to "tab indent" the reason.
313
				}
314
			}
315
		}
316
	}
317
318
	/**
319
	 * Output results of failures in format expected by Core's Site Health tool.
320
	 *
321
	 * Specifically not asking for a testing group since we're opinionated that Site Heath should see all.
322
	 *
323
	 * @return array Array of test results
324
	 */
325
	public function output_results_for_core_site_health() {
326
		$result = array(
327
			'label'       => __( 'Jetpack is fired up and working great.', 'jetpack' ),
328
			'status'      => 'good',
329
			'badge'       => array(
330
				'label' => __( 'Jetpack', 'jetpack' ),
331
				'color' => 'green',
332
			),
333
			'description' => sprintf(
334
				'<p>%s</p>',
335
				__( "Jetpack's local testing suite passed all tests!", 'jetpack' )
336
			),
337
			'actions'     => '',
338
			'test'        => 'jetpack_debugger_local_testing_suite_core',
339
		);
340
341
		if ( $this->pass() ) {
342
			return $result;
343
		}
344
345
		$fails = $this->list_fails();
346
		$error = false;
347
		foreach ( $fails as $fail ) {
0 ignored issues
show
Bug introduced by
The expression $fails of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
348
			if ( ! $error ) {
349
				$error                 = true;
350
				$result['label']       = $fail['message'];
351
				$result['status']      = $fail['severity'];
352
				$result['description'] = sprintf(
353
					'<p>%s</p>',
354
					$fail['resolution']
355
				);
356
				if ( ! empty( $fail['action'] ) ) {
357
					$result['actions'] = sprintf(
358
						'<a class="button button-primary" href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
359
						esc_url( $fail['action'] ),
360
						__( 'Resolve', 'jetpack' ),
361
						/* translators: accessibility text */
362
						__( '(opens in a new tab)', 'jetpack' )
363
					);
364
				}
365
			} else {
366
				$result['description'] .= sprintf(
367
					'<p>%s</p>',
368
					__( 'There was another problem:', 'jetpack' )
369
				) . ' ' . $fail['message'] . ': ' . $fail['resolution'];
370
				if ( 'critical' === $fail['severity'] ) { // In case the initial failure is only "recommended".
371
					$result['status'] = 'critical';
372
				}
373
			}
374
		}
375
376
		return $result;
377
378
	}
379
380
	/**
381
	 * Provide single WP Error instance of all failures.
382
	 *
383
	 * @param string $group Testing group whose failures we want converted. Default "default". Use "all" for all tests.
384
	 *
385
	 * @return WP_Error|false WP_Error with all failed tests or false if there were no failures.
386
	 */
387
	public function output_fails_as_wp_error( $group = 'default' ) {
388
		if ( $this->pass( $group ) ) {
389
			return false;
390
		}
391
		$fails = $this->list_fails( $group );
392
		$error = false;
393
394
		foreach ( $fails as $result ) {
0 ignored issues
show
Bug introduced by
The expression $fails of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
395
			$code    = 'failed_' . $result['name'];
396
			$message = $result['message'];
397
			$data    = array(
398
				'resolution' => $result['resolution'],
399
			);
400
			if ( ! $error ) {
401
				$error = new WP_Error( $code, $message, $data );
402
			} else {
403
				$error->add( $code, $message, $data );
404
			}
405
		}
406
407
		return $error;
408
	}
409
410
	/**
411
	 * Encrypt data for sending to WordPress.com.
412
	 *
413
	 * @todo When PHP minimum is 5.3+, add cipher detection to use an agreed better cipher than RC4. RC4 should be the last resort.
414
	 *
415
	 * @param string $data Data to encrypt with the WP.com Public Key.
416
	 *
417
	 * @return false|array False if functionality not available. Array of encrypted data, encryption key.
418
	 */
419
	public function encrypt_string_for_wpcom( $data ) {
420
		$return = false;
421
		if ( ! function_exists( 'openssl_get_publickey' ) || ! function_exists( 'openssl_seal' ) ) {
422
			return $return;
423
		}
424
425
		$public_key = openssl_get_publickey( JETPACK__DEBUGGER_PUBLIC_KEY );
426
427
		if ( $public_key && openssl_seal( $data, $encrypted_data, $env_key, array( $public_key ) ) ) {
428
			// We are returning base64-encoded values to ensure they're characters we can use in JSON responses without issue.
429
			$return = array(
430
				'data'   => base64_encode( $encrypted_data ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
431
				'key'    => base64_encode( $env_key[0] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
432
				'cipher' => 'RC4', // When Jetpack's minimum WP version is at PHP 5.3+, we will add in detecting and using a stronger one.
433
			);
434
		}
435
436
		openssl_free_key( $public_key );
437
438
		return $return;
439
	}
440
}
441