-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAlphabeticalUseStatementsSniff.php
389 lines (327 loc) · 10.5 KB
/
AlphabeticalUseStatementsSniff.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<?php
/**
* This file is part of the mo4-coding-standard (phpcs standard)
*
* @author Xaver Loppenstedt <[email protected]>
*
* @license http://spdx.org/licenses/MIT MIT License
*
* @link https://github.com/mayflower/mo4-coding-standard
*/
declare(strict_types=1);
namespace MO4\Sniffs\Formatting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces\UseDeclarationSniff;
use PHP_CodeSniffer\Util\Common;
use PHP_CodeSniffer\Util\Tokens as PHP_CodeSniffer_Tokens;
/**
* Alphabetical Use Statements sniff.
*
* Use statements must be in alphabetical order, grouped by empty lines.
*
* @author Xaver Loppenstedt <[email protected]>
* @author Steffen Ritter <[email protected]>
* @author Christian Albrecht <[email protected]>
*
* @copyright 2013-2017 Xaver Loppenstedt, some rights reserved.
*
* @license http://spdx.org/licenses/MIT MIT License
*
* @link https://github.com/mayflower/mo4-coding-standard
*
* @psalm-api
*/
class AlphabeticalUseStatementsSniff extends UseDeclarationSniff
{
private const NAMESPACE_SEPARATOR_STRING = '\\';
private const SUPPORTED_ORDERING_METHODS = [
'dictionary',
'string',
'string',
'string-locale',
'string-case-insensitive',
];
/**
* Sorting order, see SUPPORTED_ORDERING_METHODS for possible settings
*
* Unknown types will be mapped to 'string'.
*
* @var string
*/
public $order = 'dictionary';
/**
* Last import seen in group
*
* @var string
*/
private $lastImport = '';
/**
* Line number of the last seen use statement
*
* @var int
*/
private $lastLine = -1;
/**
* Current file
*
* @var string
*/
private $currentFile = '';
/**
* Processes this test, when one of its tokens is encountered.
*
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint
*
* @param File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr): void
{
if (!\in_array($this->order, self::SUPPORTED_ORDERING_METHODS, true)) {
$error = \sprintf(
"'%s' is not a valid order function for %s! Pick one of: %s",
$this->order,
Common::getSniffCode(self::class),
\implode(', ', self::SUPPORTED_ORDERING_METHODS)
);
$phpcsFile->addError($error, $stackPtr, 'InvalidOrder');
return;
}
parent::process($phpcsFile, $stackPtr);
if ($this->currentFile !== $phpcsFile->getFilename()) {
$this->lastLine = -1;
$this->lastImport = '';
$this->currentFile = $phpcsFile->getFilename();
}
$tokens = $phpcsFile->getTokens();
$line = $tokens[$stackPtr]['line'];
// Ignore function () use () {...}.
$isNonImportUse = $this->checkIsNonImportUse($phpcsFile, $stackPtr);
if (true === $isNonImportUse) {
return;
}
$currentImportArr = $this->getUseImport($phpcsFile, $stackPtr);
if (false === $currentImportArr) {
return;
}
$currentPtr = $currentImportArr['startPtr'];
$currentImport = $currentImportArr['content'];
if (($this->lastLine + 1) < $line) {
$this->lastLine = $line;
$this->lastImport = $currentImport;
return;
}
$fixable = false;
if ('' !== $this->lastImport
&& $this->compareString($this->lastImport, $currentImport) > 0
) {
$msg = 'USE statements must be sorted alphabetically, order %s';
$code = 'MustBeSortedAlphabetically';
$fixable = $phpcsFile->addFixableError($msg, $currentPtr, $code, [$this->order]);
}
if (true === $fixable) {
// Find the correct position in current use block.
$newDestinationPtr
= $this->findNewDestination($phpcsFile, $stackPtr, $currentImport);
$currentUseStr = $this->getUseStatementAsString($phpcsFile, $stackPtr);
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addContentBefore($newDestinationPtr, $currentUseStr);
$this->fixerClearLine($phpcsFile, $stackPtr);
$phpcsFile->fixer->endChangeset();
}
$this->lastImport = $currentImport;
$this->lastLine = $line;
}
/**
* Get the import class name for use statement pointed by $stackPtr.
*
* @param File $phpcsFile PHP CS File
* @param int $stackPtr pointer
*
* @return array|false
*/
private function getUseImport(File $phpcsFile, int $stackPtr)
{
$importTokens = [
T_NS_SEPARATOR,
T_STRING,
];
$start = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$emptyTokens,
($stackPtr + 1),
null,
true
);
// $start is false when "use" is the last token in file...
if (false === $start) {
return false;
}
$end = (int) $phpcsFile->findNext($importTokens, $start, null, true);
$import = $phpcsFile->getTokensAsString($start, ($end - $start));
return [
'startPtr' => $start,
'content' => $import,
];
}
/**
* Get the full use statement as string, including trailing white space.
*
* @param File $phpcsFile PHP CS File
* @param int $stackPtr pointer
*
* @return string
*/
private function getUseStatementAsString(File $phpcsFile, int $stackPtr): string
{
$tokens = $phpcsFile->getTokens();
$useEndPtr = (int) $phpcsFile->findNext([T_SEMICOLON], ($stackPtr + 2));
$useLength = ($useEndPtr - $stackPtr + 1);
if (T_WHITESPACE === $tokens[($useEndPtr + 1)]['code']) {
$useLength++;
}
return $phpcsFile->getTokensAsString($stackPtr, $useLength);
}
/**
* Check if "use" token is not used for import.
* E.g. function () use () {...}.
*
* @param File $phpcsFile PHP CS File
* @param int $stackPtr pointer
*
* @return bool
*/
private function checkIsNonImportUse(File $phpcsFile, int $stackPtr): bool
{
$tokens = $phpcsFile->getTokens();
$prev = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($stackPtr - 1),
0,
true,
null,
true
);
if (false !== $prev) {
$prevToken = $tokens[$prev];
if (T_CLOSE_PARENTHESIS === $prevToken['code']) {
return true;
}
}
return false;
}
/**
* Replace all the token in same line as the element pointed to by $stackPtr
* the by the empty string.
* This will delete the line.
*
* @param File $phpcsFile PHP CS file
* @param int $stackPtr pointer
*
* @return void
*/
private function fixerClearLine(File $phpcsFile, int $stackPtr): void
{
$tokens = $phpcsFile->getTokens();
$line = $tokens[$stackPtr]['line'];
for ($i = ($stackPtr - 1); $tokens[$i]['line'] === $line; $i--) {
$phpcsFile->fixer->replaceToken($i, '');
}
for ($i = $stackPtr; $tokens[$i]['line'] === $line; $i++) {
$phpcsFile->fixer->replaceToken($i, '');
}
}
/**
* Find a new destination pointer for the given import string in current
* use block.
*
* @param File $phpcsFile PHP CS File
* @param int $stackPtr pointer
* @param string $import import string requiring new position
*
* @return int
*/
private function findNewDestination(File $phpcsFile, int $stackPtr, string $import): int
{
$tokens = $phpcsFile->getTokens();
$line = $tokens[$stackPtr]['line'];
/** @var int|bool $prevLine */
$prevLine = false;
$prevPtr = $stackPtr;
do {
$ptr = $prevPtr;
// Use $line for the first iteration.
if (false !== $prevLine) {
$line = $prevLine;
}
$prevPtr = $phpcsFile->findPrevious(T_USE, ($ptr - 1));
if (false === $prevPtr) {
break;
}
$prevLine = $tokens[$prevPtr]['line'];
// phpcs:disable
/** @var array<string> $prevImportArr */
$prevImportArr = $this->getUseImport($phpcsFile, $prevPtr);
// phpcs:enable
} while ($prevLine === ($line - 1)
&& ($this->compareString($prevImportArr['content'], $import) > 0)
);
return $ptr;
}
/**
* Compare namespace strings according defined order function.
*
* @param string $a first namespace string
* @param string $b second namespace string
*
* @return int
*/
private function compareString(string $a, string $b): int
{
return match ($this->order) {
'string' => \strcmp($a, $b),
'string-locale' => \strcoll($a, $b),
'string-case-insensitive' => \strcasecmp($a, $b),
// Default is 'dictionary'.
default => $this->dictionaryCompare($a, $b),
};
}
/**
* Lexicographical namespace string compare.
*
* Example:
*
* use Doctrine\ORM\Query;
* use Doctrine\ORM\Query\Expr;
* use Doctrine\ORM\QueryBuilder;
*
* @param string $a first namespace string
* @param string $b second namespace string
*
* @return int
*/
private function dictionaryCompare(string $a, string $b): int
{
$min = \min(\strlen($a), \strlen($b));
for ($i = 0; $i < $min; $i++) {
if ($a[$i] === $b[$i]) {
continue;
}
if (self::NAMESPACE_SEPARATOR_STRING === $a[$i]) {
return -1;
}
if (self::NAMESPACE_SEPARATOR_STRING === $b[$i]) {
return 1;
}
if ($a[$i] < $b[$i]) {
return -1;
}
if ($a[$i] > $b[$i]) {
return 1;
}
}
return \strcmp(\substr($a, $min), \substr($b, $min));
}
}