Completed
Push — add/search-info-icon-plans ( ad2f6c...06b579 )
by
unknown
24:26 queued 17:35
created

Jetpack_Cxn_Test_Base   F

Complexity

Total Complexity 67

Size/Duplication

Total Lines 518
Duplicated Lines 5.79 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
dl 30
loc 518
rs 3.04
c 0
b 0
f 0
wmc 67
lcom 2
cbo 3

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add_test() 0 20 4
B list_tests() 0 20 9
A run_test() 0 6 2
A run_tests() 0 11 3
B raw_results() 0 25 8
A pass() 0 13 4
A list_fails() 0 12 5
A passing_test() 10 10 1
A skipped_test() 0 10 1
A informational_test() 0 10 1
A failing_test() 11 11 1
A test_result_defaults() 0 12 1
B output_results_for_cli() 0 27 10
B output_results_for_core_async_site_health() 9 54 6
A output_fails_as_wp_error() 0 24 5
A encrypt_string_for_wpcom() 0 21 5

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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
 * Base class for Jetpack's debugging tests.
4
 *
5
 * @package Jetpack.
6
 */
7
8
use Automattic\Jetpack\Status;
9
10
/**
11
 * Jetpack Connection Testing
12
 *
13
 * Framework for various "unit tests" against the Jetpack connection.
14
 *
15
 * Individual tests should be added to the class-jetpack-cxn-tests.php file.
16
 *
17
 * @author Brandon Kraft
18
 * @package Jetpack
19
 */
20
21
/**
22
 * "Unit Tests" for the Jetpack connection.
23
 *
24
 * @since 7.1.0
25
 */
26
class Jetpack_Cxn_Test_Base {
27
28
	/**
29
	 * Tests to run on the Jetpack connection.
30
	 *
31
	 * @var array $tests
32
	 */
33
	protected $tests = array();
34
35
	/**
36
	 * Results of the Jetpack connection tests.
37
	 *
38
	 * @var array $results
39
	 */
40
	protected $results = array();
41
42
	/**
43
	 * Status of the testing suite.
44
	 *
45
	 * Used internally to determine if a test should be skipped since the tests are already failing. Assume passing.
46
	 *
47
	 * @var bool $pass
48
	 */
49
	protected $pass = true;
50
51
	/**
52
	 * Jetpack_Cxn_Test constructor.
53
	 */
54
	public function __construct() {
55
		$this->tests   = array();
56
		$this->results = array();
57
	}
58
59
	/**
60
	 * Adds a new test to the Jetpack Connection Testing suite.
61
	 *
62
	 * @since 7.1.0
63
	 * @since 7.3.0 Adds name parameter and returns WP_Error on failure.
64
	 *
65
	 * @param callable $callable Test to add to queue.
66
	 * @param string   $name Unique name for the test.
67
	 * @param string   $type   Optional. Core Site Health type: 'direct' if test can be run during initial load or 'async' if test should run async.
68
	 * @param array    $groups Optional. Testing groups to add test to.
69
	 *
70
	 * @return mixed True if successfully added. WP_Error on failure.
71
	 */
72
	public function add_test( $callable, $name, $type = 'direct', $groups = array( 'default' ) ) {
73
		if ( is_array( $name ) ) {
74
			// Pre-7.3.0 method passed the $groups parameter here.
75
			return new WP_Error( __( 'add_test arguments changed in 7.3.0. Please reference inline documentation.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('add_test arguments c...mentation.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
76
		}
77
		if ( array_key_exists( $name, $this->tests ) ) {
78
			return new WP_Error( __( 'Test names must be unique.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Test names must be unique.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
79
		}
80
		if ( ! is_callable( $callable ) ) {
81
			return new WP_Error( __( 'Tests must be valid PHP callables.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Tests must be valid ...callables.', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
82
		}
83
84
		$this->tests[ $name ] = array(
85
			'name'  => $name,
86
			'test'  => $callable,
87
			'group' => $groups,
88
			'type'  => $type,
89
		);
90
		return true;
91
	}
92
93
	/**
94
	 * Lists all tests to run.
95
	 *
96
	 * @since 7.3.0
97
	 *
98
	 * @param string $type Optional. Core Site Health type: 'direct' or 'async'. All by default.
99
	 * @param string $group Optional. A specific testing group. All by default.
100
	 *
101
	 * @return array $tests Array of tests with test information.
102
	 */
103
	public function list_tests( $type = 'all', $group = 'all' ) {
104
		if ( ! ( 'all' === $type || 'direct' === $type || 'async' === $type ) ) {
105
			_doing_it_wrong( 'Jetpack_Cxn_Test_Base->list_tests', 'Type must be all, direct, or async', '7.3.0' );
106
		}
107
108
		$tests = array();
109
		foreach ( $this->tests as $name => $value ) {
110
			// Get all valid tests by group staged.
111
			if ( 'all' === $group || $group === $value['group'] ) {
112
				$tests[ $name ] = $value;
113
			}
114
115
			// Next filter out any that do not match the type.
116
			if ( 'all' !== $type && $type !== $value['type'] ) {
117
				unset( $tests[ $name ] );
118
			}
119
		}
120
121
		return $tests;
122
	}
123
124
	/**
125
	 * Run a specific test.
126
	 *
127
	 * @since 7.3.0
128
	 *
129
	 * @param string $name Name of test.
130
	 *
131
	 * @return mixed $result Test result array or WP_Error if invalid name. {
132
	 * @type string $name Test name
133
	 * @type mixed  $pass True if passed, false if failed, 'skipped' if skipped.
134
	 * @type string $message Human-readable test result message.
135
	 * @type string $resolution Human-readable resolution steps.
136
	 * }
137
	 */
138
	public function run_test( $name ) {
139
		if ( array_key_exists( $name, $this->tests ) ) {
140
			return call_user_func( $this->tests[ $name ]['test'] );
141
		}
142
		return new WP_Error( __( 'There is no test by that name: ', 'jetpack' ) . $name );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('There is no test by ...: ', 'jetpack') . $name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
143
	}
144
145
	/**
146
	 * Runs the Jetpack connection suite.
147
	 */
148
	public function run_tests() {
149
		foreach ( $this->tests as $test ) {
150
			$result          = call_user_func( $test['test'] );
151
			$result['group'] = $test['group'];
152
			$result['type']  = $test['type'];
153
			$this->results[] = $result;
154
			if ( false === $result['pass'] ) {
155
				$this->pass = false;
156
			}
157
		}
158
	}
159
160
	/**
161
	 * Returns the full results array.
162
	 *
163
	 * @since 7.1.0
164
	 * @since 7.3.0 Add 'type'
165
	 *
166
	 * @param string $type  Test type, async or direct.
167
	 * @param string $group Testing group whose results we want. Defaults to all tests.
168
	 * @return array Array of test results.
169
	 */
170
	public function raw_results( $type = 'all', $group = 'all' ) {
171
		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...
172
			$this->run_tests();
173
		}
174
175
		$results = $this->results;
176
177
		if ( 'all' !== $group ) {
178
			foreach ( $results as $test => $result ) {
179
				if ( ! in_array( $group, $result['group'], true ) ) {
180
					unset( $results[ $test ] );
181
				}
182
			}
183
		}
184
185
		if ( 'all' !== $type ) {
186
			foreach ( $results as $test => $result ) {
187
				if ( $type !== $result['type'] ) {
188
					unset( $results[ $test ] );
189
				}
190
			}
191
		}
192
193
		return $results;
194
	}
195
196
	/**
197
	 * Returns the status of the connection suite.
198
	 *
199
	 * @since 7.1.0
200
	 * @since 7.3.0 Add 'type'
201
	 *
202
	 * @param string $type  Test type, async or direct. Optional, direct all tests.
203
	 * @param string $group Testing group to check status of. Optional, default all tests.
204
	 *
205
	 * @return true|array True if all tests pass. Array of failed tests.
206
	 */
207
	public function pass( $type = 'all', $group = 'all' ) {
208
		$results = $this->raw_results( $type, $group );
209
210
		foreach ( $results as $result ) {
211
			// 'pass' could be true, false, or 'skipped'. We only want false.
212
			if ( isset( $result['pass'] ) && false === $result['pass'] ) {
213
				return false;
214
			}
215
		}
216
217
		return true;
218
219
	}
220
221
	/**
222
	 * Return array of failed test messages.
223
	 *
224
	 * @since 7.1.0
225
	 * @since 7.3.0 Add 'type'
226
	 *
227
	 * @param string $type  Test type, direct or async.
228
	 * @param string $group Testing group whose failures we want. Defaults to "all".
229
	 *
230
	 * @return false|array False if no failed tests. Otherwise, array of failed tests.
231
	 */
232
	public function list_fails( $type = 'all', $group = 'all' ) {
233
		$results = $this->raw_results( $type, $group );
234
235
		foreach ( $results as $test => $result ) {
236
			// We do not want tests that passed or ones that are misconfigured (no pass status or no failure message).
237
			if ( ! isset( $result['pass'] ) || false !== $result['pass'] || ! isset( $result['short_description'] ) ) {
238
				unset( $results[ $test ] );
239
			}
240
		}
241
242
		return $results;
243
	}
244
245
	/**
246
	 * Helper function to return consistent responses for a passing test.
247
	 * Possible Args:
248
	 * - name: string The raw method name that runs the test. Default 'unnamed_test'.
249
	 * - label: bool|string If false, tests will be labeled with their `name`. You can pass a string to override this behavior. Default false.
250
	 * - short_description: bool|string A brief, non-html description that will appear in CLI results. Default 'Test passed!'.
251
	 * - long_description: bool|string An html description that will appear in the site health page. Default false.
252
	 * - severity: bool|string 'critical', 'recommended', or 'good'. Default: false.
253
	 * - action: bool|string A URL for the recommended action. Default: false
254
	 * - action_label: bool|string The label for the recommended action. Default: false
255
	 * - show_in_site_health: bool True if the test should be shown on the Site Health page. Default: true
256
	 *
257
	 * @param array $args Arguments to override defaults.
258
	 *
259
	 * @return array Test results.
260
	 */
261 View Code Duplication
	public static function passing_test( $args ) {
262
		$defaults                      = self::test_result_defaults();
263
		$defaults['short_description'] = __( 'Test passed!', 'jetpack' );
264
265
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,?,{"short_description":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
266
267
		$args['pass'] = true;
268
269
		return $args;
270
	}
271
272
	/**
273
	 * Helper function to return consistent responses for a skipped test.
274
	 * Possible Args:
275
	 * - name: string The raw method name that runs the test. Default unnamed_test.
276
	 * - label: bool|string If false, tests will be labeled with their `name`. You can pass a string to override this behavior. Default false.
277
	 * - short_description: bool|string A brief, non-html description that will appear in CLI results, and as headings in admin UIs. Default false.
278
	 * - long_description: bool|string An html description that will appear in the site health page. Default false.
279
	 * - severity: bool|string 'critical', 'recommended', or 'good'. Default: false.
280
	 * - action: bool|string A URL for the recommended action. Default: false
281
	 * - action_label: bool|string The label for the recommended action. Default: false
282
	 * - show_in_site_health: bool True if the test should be shown on the Site Health page. Default: true
283
	 *
284
	 * @param array $args Arguments to override defaults.
285
	 *
286
	 * @return array Test results.
287
	 */
288
	public static function skipped_test( $args = array() ) {
289
		$args = wp_parse_args(
290
			$args,
291
			self::test_result_defaults()
0 ignored issues
show
Documentation introduced by
self::test_result_defaults() is of type array<string,string|bool...ite_health":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
292
		);
293
294
		$args['pass'] = 'skipped';
295
296
		return $args;
297
	}
298
299
	/**
300
	 * Helper function to return consistent responses for an informational test.
301
	 * Possible Args:
302
	 * - name: string The raw method name that runs the test. Default unnamed_test.
303
	 * - label: bool|string If false, tests will be labeled with their `name`. You can pass a string to override this behavior. Default false.
304
	 * - short_description: bool|string A brief, non-html description that will appear in CLI results, and as headings in admin UIs. Default false.
305
	 * - long_description: bool|string An html description that will appear in the site health page. Default false.
306
	 * - severity: bool|string 'critical', 'recommended', or 'good'. Default: false.
307
	 * - action: bool|string A URL for the recommended action. Default: false
308
	 * - action_label: bool|string The label for the recommended action. Default: false
309
	 * - show_in_site_health: bool True if the test should be shown on the Site Health page. Default: true
310
	 *
311
	 * @param array $args Arguments to override defaults.
312
	 *
313
	 * @return array Test results.
314
	 */
315
	public static function informational_test( $args = array() ) {
316
		$args = wp_parse_args(
317
			$args,
318
			self::test_result_defaults()
0 ignored issues
show
Documentation introduced by
self::test_result_defaults() is of type array<string,string|bool...ite_health":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
319
		);
320
321
		$args['pass'] = 'informational';
322
323
		return $args;
324
	}
325
326
	/**
327
	 * Helper function to return consistent responses for a failing test.
328
	 * Possible Args:
329
	 * - name: string The raw method name that runs the test. Default unnamed_test.
330
	 * - label: bool|string If false, tests will be labeled with their `name`. You can pass a string to override this behavior. Default false.
331
	 * - short_description: bool|string A brief, non-html description that will appear in CLI results, and as headings in admin UIs. Default 'Test failed!'.
332
	 * - long_description: bool|string An html description that will appear in the site health page. Default false.
333
	 * - severity: bool|string 'critical', 'recommended', or 'good'. Default: 'critical'.
334
	 * - action: bool|string A URL for the recommended action. Default: false.
335
	 * - action_label: bool|string The label for the recommended action. Default: false.
336
	 * - show_in_site_health: bool True if the test should be shown on the Site Health page. Default: true
337
	 *
338
	 * @since 7.1.0
339
	 *
340
	 * @param array $args Arguments to override defaults.
341
	 *
342
	 * @return array Test results.
343
	 */
344 View Code Duplication
	public static function failing_test( $args ) {
345
		$defaults                      = self::test_result_defaults();
346
		$defaults['short_description'] = __( 'Test failed!', 'jetpack' );
347
		$defaults['severity']          = 'critical';
348
349
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,?,{"severity":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
350
351
		$args['pass'] = false;
352
353
		return $args;
354
	}
355
356
	/**
357
	 * Provides defaults for test arguments.
358
	 *
359
	 * @since 8.5.0
360
	 *
361
	 * @return array Result defaults.
362
	 */
363
	private static function test_result_defaults() {
364
		return array(
365
			'name'                => 'unnamed_test',
366
			'label'               => false,
367
			'short_description'   => false,
368
			'long_description'    => false,
369
			'severity'            => false,
370
			'action'              => false,
371
			'action_label'        => false,
372
			'show_in_site_health' => true,
373
		);
374
	}
375
376
	/**
377
	 * Provide WP_CLI friendly testing results.
378
	 *
379
	 * @since 7.1.0
380
	 * @since 7.3.0 Add 'type'
381
	 *
382
	 * @param string $type  Test type, direct or async.
383
	 * @param string $group Testing group whose results we are outputting. Default all tests.
384
	 */
385
	public function output_results_for_cli( $type = 'all', $group = 'all' ) {
386
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
387
			if ( ( new Status() )->is_development_mode() ) {
388
				WP_CLI::line( __( 'Jetpack is in Development Mode:', 'jetpack' ) );
389
				WP_CLI::line( Jetpack::development_mode_trigger_text() );
390
			}
391
			WP_CLI::line( __( 'TEST RESULTS:', 'jetpack' ) );
392
			foreach ( $this->raw_results( $group ) as $test ) {
393
				if ( true === $test['pass'] ) {
394
					WP_CLI::log( WP_CLI::colorize( '%gPassed:%n  ' . $test['name'] ) );
395
				} elseif ( 'skipped' === $test['pass'] ) {
396
					WP_CLI::log( WP_CLI::colorize( '%ySkipped:%n ' . $test['name'] ) );
397
					if ( $test['short_description'] ) {
398
						WP_CLI::log( '         ' . $test['short_description'] ); // Number of spaces to "tab indent" the reason.
399
					}
400
				} elseif ( 'informational' === $test['pass'] ) {
401
					WP_CLI::log( WP_CLI::colorize( '%yInfo:%n    ' . $test['name'] ) );
402
					if ( $test['short_description'] ) {
403
						WP_CLI::log( '         ' . $test['short_description'] ); // Number of spaces to "tab indent" the reason.
404
					}
405
				} else { // Failed.
406
					WP_CLI::log( WP_CLI::colorize( '%rFailed:%n  ' . $test['name'] ) );
407
					WP_CLI::log( '         ' . $test['short_description'] ); // Number of spaces to "tab indent" the reason.
408
				}
409
			}
410
		}
411
	}
412
413
	/**
414
	 * Output results of failures in format expected by Core's Site Health tool for async tests.
415
	 *
416
	 * Specifically not asking for a testing group since we're opinionated that Site Heath should see all.
417
	 *
418
	 * @since 7.3.0
419
	 *
420
	 * @return array Array of test results
421
	 */
422
	public function output_results_for_core_async_site_health() {
423
		$result = array(
424
			'label'       => __( 'Jetpack passed all async tests.', 'jetpack' ),
425
			'status'      => 'good',
426
			'badge'       => array(
427
				'label' => __( 'Jetpack', 'jetpack' ),
428
				'color' => 'green',
429
			),
430
			'description' => sprintf(
431
				'<p>%s</p>',
432
				__( "Jetpack's async local testing suite passed all tests!", 'jetpack' )
433
			),
434
			'actions'     => '',
435
			'test'        => 'jetpack_debugger_local_testing_suite_core',
436
		);
437
438
		if ( $this->pass() ) {
439
			return $result;
440
		}
441
442
		$fails = $this->list_fails( 'async' );
443
		$error = false;
444
		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...
445
			if ( ! $error ) {
446
				$error                 = true;
447
				$result['label']       = $fail['message'];
448
				$result['status']      = $fail['severity'];
449
				$result['description'] = sprintf(
450
					'<p>%s</p>',
451
					$fail['resolution']
452
				);
453 View Code Duplication
				if ( ! empty( $fail['action'] ) ) {
454
					$result['actions'] = sprintf(
455
						'<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>',
456
						esc_url( $fail['action'] ),
457
						__( 'Resolve', 'jetpack' ),
458
						/* translators: accessibility text */
459
						__( '(opens in a new tab)', 'jetpack' )
460
					);
461
				}
462
			} else {
463
				$result['description'] .= sprintf(
464
					'<p>%s</p>',
465
					__( 'There was another problem:', 'jetpack' )
466
				) . ' ' . $fail['message'] . ': ' . $fail['resolution'];
467
				if ( 'critical' === $fail['severity'] ) { // In case the initial failure is only "recommended".
468
					$result['status'] = 'critical';
469
				}
470
			}
471
		}
472
473
		return $result;
474
475
	}
476
477
	/**
478
	 * Provide single WP Error instance of all failures.
479
	 *
480
	 * @since 7.1.0
481
	 * @since 7.3.0 Add 'type'
482
	 *
483
	 * @param string $type  Test type, direct or async.
484
	 * @param string $group Testing group whose failures we want converted. Default all tests.
485
	 *
486
	 * @return WP_Error|false WP_Error with all failed tests or false if there were no failures.
487
	 */
488
	public function output_fails_as_wp_error( $type = 'all', $group = 'all' ) {
489
		if ( $this->pass( $group ) ) {
490
			return false;
491
		}
492
		$fails = $this->list_fails( $type, $group );
493
		$error = false;
494
495
		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...
496
			$code    = 'failed_' . $result['name'];
497
			$message = $result['short_description'];
498
			$data    = array(
499
				'resolution' => $result['action'] ?
500
					$result['action_label'] . ' :' . $result['action'] :
501
					'',
502
			);
503
			if ( ! $error ) {
504
				$error = new WP_Error( $code, $message, $data );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $code.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
505
			} else {
506
				$error->add( $code, $message, $data );
0 ignored issues
show
Bug introduced by
The method add() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
507
			}
508
		}
509
510
		return $error;
511
	}
512
513
	/**
514
	 * Encrypt data for sending to WordPress.com.
515
	 *
516
	 * @todo When PHP minimum is 5.3+, add cipher detection to use an agreed better cipher than RC4. RC4 should be the last resort.
517
	 *
518
	 * @param string $data Data to encrypt with the WP.com Public Key.
519
	 *
520
	 * @return false|array False if functionality not available. Array of encrypted data, encryption key.
521
	 */
522
	public function encrypt_string_for_wpcom( $data ) {
523
		$return = false;
524
		if ( ! function_exists( 'openssl_get_publickey' ) || ! function_exists( 'openssl_seal' ) ) {
525
			return $return;
526
		}
527
528
		$public_key = openssl_get_publickey( JETPACK__DEBUGGER_PUBLIC_KEY );
529
530
		if ( $public_key && openssl_seal( $data, $encrypted_data, $env_key, array( $public_key ) ) ) {
531
			// We are returning base64-encoded values to ensure they're characters we can use in JSON responses without issue.
532
			$return = array(
533
				'data'   => base64_encode( $encrypted_data ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
534
				'key'    => base64_encode( $env_key[0] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
535
				'cipher' => 'RC4', // When Jetpack's minimum WP version is at PHP 5.3+, we will add in detecting and using a stronger one.
536
			);
537
		}
538
539
		openssl_free_key( $public_key );
540
541
		return $return;
542
	}
543
}
544