-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathAbstract_PHP_CodeSniffer_Check.php
More file actions
340 lines (292 loc) · 9.82 KB
/
Copy pathAbstract_PHP_CodeSniffer_Check.php
File metadata and controls
340 lines (292 loc) · 9.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
/**
* Class WordPress\Plugin_Check\Checker\Checks\Abstract_PHP_CodeSniffer_Check
*
* @package plugin-check
*/
namespace WordPress\Plugin_Check\Checker\Checks;
use Exception;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Runner;
use WordPress\Plugin_Check\Checker\Check_Result;
use WordPress\Plugin_Check\Checker\Static_Check;
use WordPress\Plugin_Check\Traits\Amend_Check_Result;
use WordPress\Plugin_Check\Utilities\Plugin_Request_Utility;
/**
* Check for running one or more PHP CodeSniffer sniffs.
*
* @since 1.0.0
*/
abstract class Abstract_PHP_CodeSniffer_Check implements Static_Check {
use Amend_Check_Result;
/**
* List of allowed PHPCS arguments.
*
* @since 1.0.0
* @var array
*/
protected $allowed_args = array(
'standard' => true,
'extensions' => true,
'sniffs' => true,
'runtime-set' => true,
'exclude' => true, //phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude
);
/**
* Returns an associative array of arguments to pass to PHPCS.
*
* @since 1.0.0
*
* @param Check_Result $result The check result to amend, including the plugin context to check.
* @return array {
* An associative array of PHPCS CLI arguments. Can include one or more of the following options.
*
* @type string $standard The name or path to the coding standard to check against.
* @type string $extensions A comma separated list of file extensions to check against.
* @type string $sniffs A comma separated list of sniff codes to include from checks.
* @type string $exclude A comma separated list of sniff codes to exclude from checks.
* }
*/
abstract protected function get_args( Check_Result $result );
/**
* Amends the given result by running the check on the associated plugin.
*
* @SuppressWarnings(PHPMD.NPathComplexity)
*
* @since 1.0.0
*
* @param Check_Result $result The check result to amend, including the plugin context to check.
*
* @throws Exception Thrown when the check fails with a critical error (unrelated to any errors detected as part of
* the check).
*/
final public function run( Check_Result $result ) {
// Include the PHPCS autoloader.
$autoloader = WP_PLUGIN_CHECK_PLUGIN_DIR_PATH . 'vendor/squizlabs/php_codesniffer/autoload.php';
if ( file_exists( $autoloader ) ) {
include_once $autoloader;
}
if ( ! class_exists( Runner::class ) ) {
throw new Exception(
__( 'Unable to find PHPCS Runner class.', 'plugin-check' )
);
}
if ( ! class_exists( Config::class ) ) {
throw new Exception(
__( 'Unable to find PHPCS Config class.', 'plugin-check' )
);
}
// Backup the original command line arguments.
$orig_cmd_args = $_SERVER['argv'] ?? '';
$args = $this->get_args( $result );
// Reset PHP_CodeSniffer config.
$this->reset_php_codesniffer_config();
// Get current installed_paths config.
$installed_paths = Config::getConfigData( 'installed_paths' );
// Override installed_paths to load custom sniffs.
if ( isset( $args['installed_paths'] ) && is_array( $args['installed_paths'] ) ) {
Config::setConfigData( 'installed_paths', implode( ',', $args['installed_paths'] ), true );
}
// Create the default arguments for PHPCS.
$defaults = $this->get_argv_defaults( $result );
// Set the check arguments for PHPCS.
$_SERVER['argv'] = $this->parse_argv( $args, $defaults );
// Run PHPCS.
$php_codesniffer_error_handler = $this->register_php_codesniffer_error_handler();
try {
ob_start();
$this->run_php_codesniffer();
$reports = ob_get_clean();
} catch ( Exception $e ) {
if ( ob_get_level() > 0 ) {
ob_end_clean();
}
throw $e;
} finally {
$this->restore_php_codesniffer_error_handler( $php_codesniffer_error_handler );
// Reset installed_paths.
Config::setConfigData( 'installed_paths', $installed_paths, true );
// Restore original arguments.
$_SERVER['argv'] = $orig_cmd_args;
}
// Parse the reports into data to add to the overall $result.
$reports = json_decode( trim( $reports ), true );
if ( empty( $reports['files'] ) ) {
return;
}
foreach ( $reports['files'] as $file_name => $file_results ) {
if ( empty( $file_results['messages'] ) ) {
continue;
}
foreach ( $file_results['messages'] as $file_message ) {
$this->add_result_message_for_file(
$result,
strtoupper( $file_message['type'] ) === 'ERROR',
esc_html( $file_message['message'] ),
$file_message['source'],
$file_name,
$file_message['line'],
$file_message['column'],
'',
$file_message['severity']
);
}
}
}
/**
* Runs PHP_CodeSniffer.
*
* @since n.e.x.t
*/
protected function run_php_codesniffer() {
/*
* PHPStan cannot infer the class_exists() check performed by run().
*
* @phpstan-ignore-next-line
*/
$runner = new Runner();
/* @phpstan-ignore-next-line */
$runner->runPHPCS();
}
/**
* Parse the command arguments.
*
* @since 1.0.0
*
* @param array $argv An array of arguments to pass.
* @param array $defaults An array of default arguments.
* @return array An indexed array of PHPCS CLI arguments.
*/
private function parse_argv( $argv, $defaults ) {
// Only accept allowed PHPCS arguments from check arguments array.
$check_args = array_intersect_key( $argv, $this->allowed_args );
// Format check arguments for PHPCS.
foreach ( $check_args as $key => $value ) {
if ( 'runtime-set' === $key ) {
if ( is_array( $value ) ) {
foreach ( $value as $item_key => $item_value ) {
$defaults = array_merge( $defaults, array( "--{$key}", $item_key, $item_value ) );
}
}
} else {
$defaults[] = "--{$key}=$value";
}
}
return $defaults;
}
/**
* Gets the default command arguments.
*
* @since 1.0.0
*
* @param Check_Result $result The check result to amend, including the plugin context to check.
* @return array An indexed array of PHPCS CLI arguments.
*/
private function get_argv_defaults( Check_Result $result ): array {
$defaults = array(
'',
$result->plugin()->location(),
'--report=Json',
'--report-width=9999',
);
$ignore_patterns = array();
$directories_to_ignore = Plugin_Request_Utility::get_directories_to_ignore();
$files_to_ignore = Plugin_Request_Utility::get_files_to_ignore();
// Ignore directories.
if ( ! empty( $directories_to_ignore ) ) {
$ignore_patterns[] = '*/' . implode( '/*,*/', $directories_to_ignore ) . '/*';
}
// Ignore files.
if ( ! empty( $files_to_ignore ) ) {
$ignore_patterns[] = '/' . implode( ',/', $files_to_ignore );
}
if ( ! empty( $ignore_patterns ) ) {
$defaults[] = '--ignore=' . implode( ',', $ignore_patterns );
}
// Set the Minimum WP version supported for the plugin.
if ( $result->plugin()->minimum_supported_wp() ) {
// Due to the syntax of runtime-set, these must be passed as individual args.
$defaults[] = '--runtime-set';
$defaults[] = 'minimum_wp_version';
$defaults[] = $result->plugin()->minimum_supported_wp();
}
return $defaults;
}
/**
* Registers an error handler for known PHPCS notices.
*
* @since n.e.x.t
*/
private function register_php_codesniffer_error_handler() {
$previous_error_handler = null;
$error_handler = static function ( $errno, $errstr, $errfile, $errline ) use ( &$previous_error_handler ) {
$normalized_file = wp_normalize_path( $errfile );
if (
E_DEPRECATED === $errno &&
false !== strpos( $errstr, 'auto_detect_line_endings is deprecated' ) &&
false !== strpos( $normalized_file, 'vendor/squizlabs/php_codesniffer/src/Runner.php' )
) {
return true;
}
/*
* PHPStan cannot infer the deferred assignment after the closure is created.
*
* @phpstan-ignore-next-line
*/
if ( is_callable( $previous_error_handler ) ) {
return (bool) call_user_func( $previous_error_handler, $errno, $errstr, $errfile, $errline );
}
return false;
};
$previous_error_handler = set_error_handler( $error_handler );
return $error_handler;
}
/**
* Restores the error handler that was active before running PHP_CodeSniffer.
*
* PHP_CodeSniffer registers its own error handler while processing files. If
* processing throws, PHP_CodeSniffer does not restore that handler, so it must
* be removed before the temporary deprecation handler can be restored.
*
* @since n.e.x.t
*
* @param callable $php_codesniffer_error_handler The temporary error handler registered before running PHP_CodeSniffer.
*/
private function restore_php_codesniffer_error_handler( $php_codesniffer_error_handler ) {
$current_error_handler = set_error_handler( $php_codesniffer_error_handler );
restore_error_handler();
if ( $current_error_handler !== $php_codesniffer_error_handler ) {
restore_error_handler();
}
restore_error_handler();
}
/**
* Resets \PHP_CodeSniffer\Config::$overriddenDefaults to prevent
* incorrect results when running multiple checks.
*
* @since 1.0.0
*/
private function reset_php_codesniffer_config() {
if ( class_exists( Config::class ) ) {
/*
* PHPStan ignore reason: PHPStan raised an issue because we can't
* use class in ReflectionClass.
*
* @phpstan-ignore-next-line
*/
$reflected_phpcs_config = new \ReflectionClass( Config::class );
$overridden_defaults = $reflected_phpcs_config->getProperty( 'overriddenDefaults' );
/*
* The setAccessible function has no effect in PHP >= 8.1, and it is marked as deprecated in PHP 8.5.
* Since the tests are also run on PHP 7.4 and 8.0, we can only call the function if the php version is lower than 8.1.
*/
if ( version_compare( PHP_VERSION, '8.1.0', '<' ) ) {
$overridden_defaults->setAccessible( true );
}
$overridden_defaults->setValue( $reflected_phpcs_config, array() );
if ( version_compare( PHP_VERSION, '8.1.0', '<' ) ) {
$overridden_defaults->setAccessible( false );
}
}
}
}