-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathSourceCodeChecker.php
More file actions
328 lines (283 loc) · 9.55 KB
/
SourceCodeChecker.php
File metadata and controls
328 lines (283 loc) · 9.55 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
<?php
declare(strict_types=1);
namespace Peck\Checkers;
use Peck\Config;
use Peck\Contracts\Checker;
use Peck\Contracts\Services\Spellchecker;
use Peck\Support\NotPaths;
use Peck\Support\SpellcheckFormatter;
use Peck\ValueObjects\Issue;
use Peck\ValueObjects\Misspelling;
use ReflectionClass;
use ReflectionClassConstant;
use ReflectionException;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Throwable;
/**
* @internal
*/
final readonly class SourceCodeChecker implements Checker
{
/**
* Creates a new instance of SourceCodeChecker.
*/
public function __construct(
private Config $config,
private Spellchecker $spellchecker,
) {}
/**
* Checks for issues in the given directory.
*
* @param array{directory: string, onSuccess: callable(): void, onFailure: callable(): void} $parameters
* @return array<int, Issue>
*/
public function check(array $parameters): array
{
$sourceFiles = iterator_to_array(Finder::create()
->files()
->notPath(NotPaths::get($parameters['directory'], $this->config->whitelistedPaths))
->ignoreDotFiles(true)
->ignoreVCS(true)
->ignoreUnreadableDirs()
->ignoreVCSIgnored(true)
->in($parameters['directory'])
->name('*.php')
->sortByName()
->getIterator());
$issues = [];
foreach ($sourceFiles as $sourceFile) {
$newIssues = $this->getIssuesFromSourceFile($sourceFile);
$issues = [
...$issues,
...$newIssues,
];
$newIssues !== [] ? $parameters['onFailure']() : $parameters['onSuccess']();
}
return $issues;
}
/**
* Get the issues from the given source file.
*
* @return array<int, Issue>
*/
private function getIssuesFromSourceFile(SplFileInfo $file): array
{
$definition = $this->getFullyQualifiedDefinitionName($file);
if ($definition === null) {
return [];
}
try {
$reflection = new ReflectionClass($definition);
} catch (ReflectionException) { // @phpstan-ignore-line
return [];
}
$namesToCheck = [
...$this->getMethodNames($reflection),
...$this->getPropertyNames($reflection),
...$this->getConstantNames($reflection),
...$this->getStringValues($file),
];
if ($docComment = $reflection->getDocComment()) {
$namesToCheck = [
...$namesToCheck,
...array_values(array_filter(
explode(PHP_EOL, $docComment),
fn (string $line): bool => ! str_contains($line, '* @',
))),
];
}
if ($namesToCheck === []) {
return [];
}
$issues = [];
foreach ($namesToCheck as $name) {
$issues = [
...$issues,
...array_map(
fn (Misspelling $misspelling): Issue => new Issue(
$misspelling,
$file->getRealPath(),
$this->getErrorLine($file, $name),
), $this->spellchecker->check(SpellcheckFormatter::format($name))),
];
}
return $issues;
}
/**
* Get the string values contained in the given file.
*
* @return array<int, string>
*/
private function getStringValues(SplFileInfo $file): array
{
try {
$tokens = token_get_all($file->getContents());
} catch (Throwable) {
return [];
}
foreach ($tokens as $token) {
if (is_array($token) && $token[0] === T_CONSTANT_ENCAPSED_STRING) {
// Remove the surrounding quotes from the string
$string = substr($token[1], 1, -1);
// Handle escaped quotes depending on string type
if ($token[1][0] === '"') {
$string = stripcslashes($string);
}
$stringsToCheck[] = $string;
}
}
return $stringsToCheck ?? [];
}
/**
* Get the method names contained in the given reflection.
*
* @param ReflectionClass<object> $reflection
* @return array<int, string>
*/
private function getMethodNames(ReflectionClass $reflection): array
{
$methods = array_filter(
$reflection->getMethods(),
function (ReflectionMethod $method) use ($reflection): bool {
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasMethod($method->getName())) {
return false;
}
}
return $method->class === $reflection->name;
},
);
foreach ($methods as $method) {
$namesToCheck[] = $method->getName();
$namesToCheck = [
...$namesToCheck,
...$this->getMethodParameters($method),
];
if ($docComment = $method->getDocComment()) {
$namesToCheck = [
...$namesToCheck,
...array_values(array_filter(
explode(PHP_EOL, $docComment),
fn (string $line): bool => ! str_contains($line, '* @',
))),
];
}
}
return $namesToCheck ?? [];
}
/**
* Get the method parameters names contained in the given method.
*
* @return array<int, string>
*/
private function getMethodParameters(ReflectionMethod $method): array
{
return array_map(
fn (ReflectionParameter $parameter): string => $parameter->getName(),
$method->getParameters(),
);
}
/**
* Get the constant names and their values contained in the given reflection.
* This also includes cases from enums and their values (for string backed enums).
*
* @param ReflectionClass<object> $reflection
* @return array<int, string>
*/
private function getConstantNames(ReflectionClass $reflection): array
{
return array_map(
fn (ReflectionClassConstant $constant): string => $constant->name,
array_values(array_filter(
$reflection->getReflectionConstants(),
function (ReflectionClassConstant $constant) use ($reflection): bool {
if ($constant->class !== $reflection->name) {
return false;
}
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasConstant($constant->getName())) {
return false;
}
}
return true;
}
))
);
}
/**
* Get the property names contained in the given reflection.
*
* @param ReflectionClass<object> $reflection
* @return array<int, string>
*/
private function getPropertyNames(ReflectionClass $reflection): array
{
$properties = array_filter(
$reflection->getProperties(),
function (ReflectionProperty $property) use ($reflection): bool {
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasProperty($property->getName())) {
return false;
}
}
return $property->class === $reflection->name;
},
);
$propertiesNames = array_map(
fn (ReflectionProperty $property): string => $property->getName(),
$properties,
);
$propertiesDocComments = array_reduce(
array_map(
fn (ReflectionProperty $property): array => explode(PHP_EOL, $property->getDocComment() ?: ''),
$properties,
),
fn (array $carry, array $item): array => [
...$carry,
...$item,
],
[],
);
return [
...$propertiesNames,
...$propertiesDocComments,
];
}
/**
* Get the fully qualified definition name of the class, enum or trait.
*
* @return class-string<object>|null
*/
private function getFullyQualifiedDefinitionName(SplFileInfo $file): ?string
{
if (preg_match('/namespace (.*);/', $file->getContents(), $matches)) {
/** @var class-string $fullyQualifiedName */
$fullyQualifiedName = $matches[1].'\\'.$file->getFilenameWithoutExtension();
return $fullyQualifiedName;
}
return null;
}
/**
* Get the line number of the error.
*/
private function getErrorLine(SplFileInfo $file, string $misspellingWord): int
{
$contentsArray = explode(PHP_EOL, $file->getContents());
$contentsArrayLines = array_map(fn ($lineNumber): int => $lineNumber + 1, array_keys($contentsArray));
$lines = array_values(array_filter(
array_map(
fn (string $line, int $lineNumber): ?int => str_contains($line, $misspellingWord) ? $lineNumber : null,
$contentsArray,
$contentsArrayLines,
),
));
if ($lines === []) {
return 0;
}
return $lines[0];
}
}