1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Zenify\CodingStandard\Tests; |
6
|
|
|
|
7
|
|
|
use PHP_CodeSniffer; |
8
|
|
|
use Zenify\CodingStandard\Tests\Exception\FileNotFoundException; |
9
|
|
|
use Zenify\CodingStandard\Tests\Exception\StandardRulesetNotFoundException; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
final class CodeSnifferRunner |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var PHP_CodeSniffer |
17
|
|
|
*/ |
18
|
|
|
private $codeSniffer; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var string[] |
22
|
|
|
*/ |
23
|
|
|
private $standardRulesets = [ |
24
|
|
|
'ZenifyCodingStandard' => __DIR__ . '/../src/ZenifyCodingStandard/ruleset.xml' |
25
|
|
|
]; |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
public function __construct(string $sniff) |
29
|
|
|
{ |
30
|
|
|
$ruleset = $this->detectRulesetFromSniffName($sniff); |
31
|
|
|
|
32
|
|
|
$this->codeSniffer = new PHP_CodeSniffer; |
33
|
|
|
$this->codeSniffer->initStandard($ruleset, [$sniff]); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
|
37
|
|
|
public function getErrorCountInFile(string $source) : int |
38
|
|
|
{ |
39
|
|
|
$this->ensureFileExists($source); |
40
|
|
|
|
41
|
|
|
$file = $this->codeSniffer->processFile($source); |
42
|
|
|
return $file->getErrorCount(); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
public function getFixedContent(string $source) : string |
47
|
|
|
{ |
48
|
|
|
$this->ensureFileExists($source); |
49
|
|
|
|
50
|
|
|
$file = $this->codeSniffer->processFile($source); |
51
|
|
|
$file->fixer->fixFile(); |
52
|
|
|
|
53
|
|
|
return $file->fixer->getContents(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
|
57
|
|
|
public function detectRulesetFromSniffName(string $name) : string |
58
|
|
|
{ |
59
|
|
|
$standard = $this->detectStandardFromSniffName($name); |
60
|
|
|
|
61
|
|
|
if (isset($this->standardRulesets[$standard])) { |
62
|
|
|
return $this->standardRulesets[$standard]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
throw new StandardRulesetNotFoundException( |
66
|
|
|
sprintf('Ruleset for standard "%s" not found.', $standard) |
67
|
|
|
); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
|
71
|
|
|
private function ensureFileExists(string $source) |
72
|
|
|
{ |
73
|
|
|
if ( ! file_exists($source)) { |
74
|
|
|
throw new FileNotFoundException( |
75
|
|
|
sprintf('File "%s" was not found.', $source) |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
private function detectStandardFromSniffName(string $sniff) : string |
82
|
|
|
{ |
83
|
|
|
$parts = explode('.', $sniff); |
84
|
|
|
if (isset($parts[0])) { |
85
|
|
|
return $parts[0]; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return ''; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
} |
92
|
|
|
|