-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ClassAttributesSeparationFixer.php
578 lines (475 loc) · 20.3 KB
/
ClassAttributesSeparationFixer.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
<?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* Make sure there is one blank line above and below class elements.
*
* The exception is when an element is the first or last item in a 'classy'.
*/
final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/**
* @internal
*/
public const SPACING_NONE = 'none';
/**
* @internal
*/
public const SPACING_ONE = 'one';
private const SPACING_ONLY_IF_META = 'only_if_meta';
/**
* @var array<string, string>
*/
private array $classElementTypes = [];
/**
* {@inheritdoc}
*/
public function configure(array $configuration): void
{
parent::configure($configuration);
$this->classElementTypes = []; // reset previous configuration
foreach ($this->configuration['elements'] as $elementType => $spacing) {
$this->classElementTypes[$elementType] = $spacing;
}
}
/**
* {@inheritdoc}
*/
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Class, trait and interface elements must be separated with one or none blank line.',
[
new CodeSample(
'<?php
final class Sample
{
protected function foo()
{
}
protected function bar()
{
}
}
'
),
new CodeSample(
'<?php
class Sample
{private $a; // foo
/** second in a hour */
private $b;
}
',
['elements' => ['property' => self::SPACING_ONE]]
),
new CodeSample(
'<?php
class Sample
{
const A = 1;
/** seconds in some hours */
const B = 3600;
}
',
['elements' => ['const' => self::SPACING_ONE]]
),
new CodeSample(
'<?php
class Sample
{
/** @var int */
const SECOND = 1;
/** @var int */
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
}
',
['elements' => ['const' => self::SPACING_ONLY_IF_META]]
),
new VersionSpecificCodeSample(
'<?php
class Sample
{
public $a;
#[SetUp]
public $b;
/** @var string */
public $c;
/** @internal */
#[Assert\String()]
public $d;
public $e;
}
',
new VersionSpecification(80000),
['elements' => ['property' => self::SPACING_ONLY_IF_META]]
),
]
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer.
* Must run after OrderedClassElementsFixer, SingleClassElementPerStatementFixer.
*/
public function getPriority(): int
{
return 55;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($this->getElementsByClass($tokens) as $class) {
$elements = $class['elements'];
$elementCount = \count($elements);
if (0 === $elementCount) {
continue;
}
if (isset($this->classElementTypes[$elements[0]['type']])) {
$this->fixSpaceBelowClassElement($tokens, $class);
$this->fixSpaceAboveClassElement($tokens, $class, 0);
}
for ($index = 1; $index < $elementCount; ++$index) {
if (isset($this->classElementTypes[$elements[$index]['type']])) {
$this->fixSpaceAboveClassElement($tokens, $class, $index);
}
}
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.'))
->setAllowedTypes(['array'])
->setAllowedValues([static function (array $option): bool {
foreach ($option as $type => $spacing) {
$supportedTypes = ['const', 'method', 'property', 'trait_import', 'case'];
if (!\in_array($type, $supportedTypes, true)) {
throw new InvalidOptionsException(
sprintf(
'Unexpected element type, expected any of "%s", got "%s".',
implode('", "', $supportedTypes),
\gettype($type).'#'.$type
)
);
}
$supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META];
if (!\in_array($spacing, $supportedSpacings, true)) {
throw new InvalidOptionsException(
sprintf(
'Unexpected spacing for element type "%s", expected any of "%s", got "%s".',
$spacing,
implode('", "', $supportedSpacings),
\is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing)
)
);
}
}
return true;
}])
->setDefault([
'const' => self::SPACING_ONE,
'method' => self::SPACING_ONE,
'property' => self::SPACING_ONE,
'trait_import' => self::SPACING_NONE,
'case' => self::SPACING_NONE,
])
->getOption(),
]);
}
/**
* Fix spacing above an element of a class, interface or trait.
*
* Deals with comments, PHPDocs and spaces above the element with respect to the position of the
* element within the class, interface or trait.
*/
private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex): void
{
$element = $class['elements'][$elementIndex];
$elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0;
$nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']);
// element is directly after class open brace
if ($nonWhiteAbove === $class['open']) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
return;
}
// deal with comments above an element
if ($tokens[$nonWhiteAbove]->isGivenKind(T_COMMENT)) {
// check if the comment belongs to the previous element
if ($elementAboveEnd === $nonWhiteAbove) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
return;
}
// more than one line break, always bring it back to 2 line breaks between the element start and what is above it
if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
return;
}
// there are 2 cases:
if (
1 === $element['start'] - $nonWhiteAbove
|| $tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0
|| $tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0
) {
// 1. The comment is meant for the element (although not a PHPDoc),
// make sure there is one line break between the element and the comment...
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
// ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening)
$nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
$nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2);
} else {
// 2. The comment belongs to the code above the element,
// make sure there is a blank line above the element (i.e. 2 line breaks)
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
}
return;
}
// deal with element with a PHPDoc/attribute above it
if ($tokens[$nonWhiteAbove]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) {
// there should be one linebreak between the element and the attribute above it
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
// make sure there is blank line above the comment (with the exception when it is directly after a class opening)
$nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
$nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2);
return;
}
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
}
private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex): int
{
$type = $class['elements'][$elementIndex]['type'];
$spacing = $this->classElementTypes[$type];
if (self::SPACING_ONE === $spacing) {
return 2;
}
if (self::SPACING_NONE === $spacing) {
if (!isset($class['elements'][$elementIndex + 1])) {
return 1;
}
$aboveElement = $class['elements'][$elementIndex + 1];
if ($aboveElement['type'] !== $type) {
return 2;
}
$aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']);
return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
}
if (self::SPACING_ONLY_IF_META === $spacing) {
$aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']);
return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
}
throw new \RuntimeException(sprintf('Unknown spacing "%s".', $spacing));
}
private function fixSpaceBelowClassElement(Tokens $tokens, array $class): void
{
$element = $class['elements'][0];
// if this is last element fix; fix to the class end `}` here if appropriate
if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) {
$this->correctLineBreaks($tokens, $element['end'], $class['close'], 1);
}
}
private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
++$startIndex;
$numbOfWhiteTokens = $endIndex - $startIndex;
if (0 === $numbOfWhiteTokens) {
$tokens->insertAt($startIndex, new Token([T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)]));
return;
}
$lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex);
if ($reqLineCount === $lineBreakCount) {
return;
}
if ($lineBreakCount < $reqLineCount) {
$tokens[$startIndex] = new Token([
T_WHITESPACE,
str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(),
]);
return;
}
// $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time
if (1 === $numbOfWhiteTokens) {
$tokens[$startIndex] = new Token([
T_WHITESPACE,
Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount),
]);
return;
}
// $numbOfWhiteTokens = > 1
$toReplaceCount = $lineBreakCount - $reqLineCount;
for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) {
$tokenLineCount = substr_count($tokens[$i]->getContent(), "\n");
if ($tokenLineCount > 0) {
$tokens[$i] = new Token([
T_WHITESPACE,
Preg::replace('/\r\n|\n/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)),
]);
$toReplaceCount -= $tokenLineCount;
}
}
}
private function getLineBreakCount(Tokens $tokens, int $startIndex, int $endIndex): int
{
$lineCount = 0;
for ($i = $startIndex; $i < $endIndex; ++$i) {
$lineCount += substr_count($tokens[$i]->getContent(), "\n");
}
return $lineCount;
}
private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd): int
{
for ($i = $start; $i > $elementAboveEnd; --$i) {
if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i);
continue;
}
if ($tokens[$i]->isComment()) {
$start = $i;
continue;
}
if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) {
break;
}
}
return $start;
}
private function getElementsByClass(Tokens $tokens): \Generator
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$class = $classIndex = false;
$elements = $tokensAnalyzer->getClassyElements();
for (end($elements);; prev($elements)) {
$index = key($elements);
if (null === $index) {
break;
}
$element = current($elements);
$element['index'] = $index;
if ($element['classIndex'] !== $classIndex) {
if (false !== $class) {
yield $class;
}
$classIndex = $element['classIndex'];
$classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']);
$classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
$class = [
'index' => $classIndex,
'open' => $classOpen,
'close' => $classEnd,
'elements' => [],
];
}
unset($element['classIndex']);
$element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class, $element);
$element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class, $element, $tokensAnalyzer);
$class['elements'][] = $element; // reset the key by design
}
if (false !== $class) {
yield $class;
}
}
private function getFirstTokenIndexOfClassElement(Tokens $tokens, array $class, array $element): int
{
$modifierTypes = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_ABSTRACT, T_FINAL, T_STATIC, T_STRING, T_NS_SEPARATOR, T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION];
if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required
$modifierTypes[] = T_READONLY;
}
$firstElementAttributeIndex = $element['index'];
do {
$nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex);
if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind($modifierTypes)) {
$firstElementAttributeIndex = $nonWhiteAbove;
} else {
break;
}
} while ($firstElementAttributeIndex > $class['open']);
return $firstElementAttributeIndex;
}
// including trailing single line comments if belonging to the class element
private function getLastTokenIndexOfClassElement(Tokens $tokens, array $class, array $element, TokensAnalyzer $tokensAnalyzer): int
{
// find last token of the element
if ('method' === $element['type'] && !$tokens[$class['index']]->isGivenKind(T_INTERFACE)) {
$attributes = $tokensAnalyzer->getMethodAttributes($element['index']);
if (true === $attributes['abstract']) {
$elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']);
} else {
$elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{']));
}
} elseif ('trait_import' === $element['type']) {
$elementEndIndex = $element['index'];
do {
$elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex);
} while ($tokens[$elementEndIndex]->isGivenKind([T_STRING, T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(','));
if (!$tokens[$elementEndIndex]->equals(';')) {
$elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{']));
}
} else { // 'const', 'property', enum-'case', or 'method' of an interface
$elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']);
}
$singleLineElement = true;
for ($i = $element['index'] + 1; $i < $elementEndIndex; ++$i) {
if (str_contains($tokens[$i]->getContent(), "\n")) {
$singleLineElement = false;
break;
}
}
if ($singleLineElement) {
while (true) {
$nextToken = $tokens[$elementEndIndex + 1];
if (($nextToken->isComment() || $nextToken->isWhitespace()) && !str_contains($nextToken->getContent(), "\n")) {
++$elementEndIndex;
} else {
break;
}
}
if ($tokens[$elementEndIndex]->isWhitespace()) {
$elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex);
}
}
return $elementEndIndex;
}
}