Completed
Push — namespace-model ( c67c40...018a87 )
by Sam
07:37
created

phpcs_runner.php ➔ run_sniff()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
eloc 16
nc 4
nop 4
dl 0
loc 24
rs 8.6845
1
<?php
2
3
if(php_sapi_name() != 'cli') {
4
	die("This script must be called from the command line\n");
5
}
6
7
if(!empty($_SERVER['argv'][1])) {
8
	$path = $_SERVER['argv'][1];
9
} else {
10
	die("Usage: php {$_SERVER['argv'][0]} <file>\n");
11
}
12
13
$result = array('comments' => array());
14
15
$extension = pathinfo($path, PATHINFO_EXTENSION);
16
17
// Whitelist of extensions to check (default phpcs list)
18
if(in_array($extension, array('php', 'js', 'inc', 'css'))) {
19
	// Run each sniff
20
21
	// phpcs --encoding=utf-8 --standard=framework/tests/phpcs/tabs.xml
22
	run_sniff('tabs.xml', $path, $result);
23
24
	// phpcs --encoding=utf-8 --tab-width=4 --standard=framework/tests/phpcs/ruleset.xml
25
	run_sniff('ruleset.xml', $path, $result, '--tab-width=4');
26
}
27
echo json_encode($result);
28
29
function run_sniff($standard, $path, array &$result, $extraFlags = '') {
30
	$sniffPath = escapeshellarg(__DIR__ . '/phpcs/' . $standard);
31
	$checkPath = escapeshellarg($path);
32
33
	exec("phpcs --encoding=utf-8 $extraFlags --standard=$sniffPath --report=xml $checkPath", $output);
34
35
	// We can't check the return code as it's non-zero if the sniff finds an error
36
	if($output) {
37
		$xml = implode("\n", $output);
38
		$xml = simplexml_load_string($xml);
39
		$errors = $xml->xpath('/phpcs/file/error');
40
		if($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors 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...
41
			$sanePath = str_replace('/', '_', $path);
42
			foreach($errors as $error) {
43
				$attributes = $error->attributes();
44
				$result['comments'][] = array(
45
					'line' => (int)strval($attributes->line),
46
					'id' => $standard . '-' . $sanePath . '-' . $attributes->line . '-' . $attributes->column,
47
					'message' => strval($error)
48
				);
49
			}
50
		}
51
	}
52
}
53