-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDisallowCompactUsageSniff.php
86 lines (68 loc) · 2.19 KB
/
DisallowCompactUsageSniff.php
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
<?php
namespace Worksome\CodingStyle\Sniffs\Functions;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use Worksome\CodingStyle\Utility;
class DisallowCompactUsageSniff implements Sniff
{
public function register(): array
{
return [
T_STRING,
];
}
public function process(File $phpcsFile, $stackPtr)
{
$methodName = $phpcsFile->getTokensAsString($stackPtr, 1);
// Check if method is env method.
if (strtolower($methodName) !== 'compact') {
return;
}
$phpcsFile->addFixableError(
'Usage of compact function is disallowed.',
$stackPtr,
self::class
);
[$variables, $lastTokenPointer] = $this->findVariablesInCompactCall($phpcsFile, $stackPtr);
$phpCode = $this->generatePhpArray($variables);
// Remove all the old code after the `compact` string.
foreach (range(1, $lastTokenPointer - 1) as $currentPointer) {
$phpcsFile->fixer->replaceToken(
$stackPtr + $currentPointer,
''
);
}
// Replace the `compact` string with our new array.
$phpcsFile->fixer->replaceToken(
$stackPtr,
$phpCode
);
}
private function generatePhpArray(array $variables): string
{
$phpCode = '[';
foreach ($variables as $variable) {
$phpCode .= "'$variable' => \$$variable, ";
}
// Remove the trailing `, ` from the array.
$phpCode = substr($phpCode, 0, -2);
// Close the array
$phpCode .= ']';
return $phpCode;
}
private function findVariablesInCompactCall(File $phpcsFile, int $stackPtr): array
{
$variables = [];
$pointer = 1;
do {
$token = $phpcsFile->getTokensAsString($stackPtr + $pointer, 1);
$pointer++;
if (! Utility::preg_match("/['\"](.*?)['\"]/", $token, $matches)) {
continue;
}
$variableName = $matches[1];
$variables[] = $variableName;
} while ($token !== ')');
return [$variables, $pointer, $matches];
}
}