-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathHeaderCommentFixer.php
400 lines (345 loc) · 13.5 KB
/
HeaderCommentFixer.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
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <[email protected]>
* Dariusz Rumiński <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Antonio J. García Lagar <[email protected]>
* @author SpacePossum
*/
final class HeaderCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
const HEADER_PHPDOC = 'PHPDoc';
const HEADER_COMMENT = 'comment';
const HEADER_LOCATION_AFTER_OPEN = 1;
const HEADER_LOCATION_AFTER_DECLARE_STRICT = 2;
const HEADER_LINE_SEPARATION_BOTH = 1;
const HEADER_LINE_SEPARATION_TOP = 2;
const HEADER_LINE_SEPARATION_BOTTOM = 3;
const HEADER_LINE_SEPARATION_NONE = 4;
/** @var string */
private $headerComment;
/** @var string */
private $headerCommentType;
/** @var int */
private $headerLocation;
/** @var int */
private $headerLineSeparation;
/**
* {@inheritdoc}
*/
public function configure(array $configuration = null)
{
list(
$this->headerComment,
$this->headerCommentType,
$this->headerLocation,
$this->headerLineSeparation
) = $this->parseConfiguration($configuration);
}
/**
* {@inheritdoc}
*/
public function fix(\SplFileInfo $file, Tokens $tokens)
{
if (null === $this->headerComment) {
throw new RequiredFixerConfigurationException($this->getName(), 'Configuration is required.');
}
// figure out where the comment should be placed
$headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens);
// check if there is already a comment
$headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerNewIndex - 1);
if (null === $headerCurrentIndex) {
if ('' === $this->headerComment) {
return; // header not found and none should be set, return
}
$this->insertHeader($tokens, $headerNewIndex);
} elseif ($this->headerComment !== $tokens[$headerCurrentIndex]->getContent()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($headerCurrentIndex);
if ('' === $this->headerComment) {
return; // header found and cleared, none should be set, return
}
$this->insertHeader($tokens, $headerNewIndex);
} else {
$headerNewIndex = $headerCurrentIndex;
}
$this->fixWhiteSpaceAroundHeader($tokens, $headerNewIndex);
}
/**
* {@inheritdoc}
*/
public function getDefinition()
{
return new FixerDefinition(
'Add, replace or remove header comment.',
array(
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
array(
'header' => 'Made with love.',
)
),
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
array(
'header' => 'Made with love.',
'commentType' => 'PHPDoc',
'location' => 'after_open',
'separate' => 'bottom',
)
),
new CodeSample(
'<?php
declare(strict_types=1);
namespace A\B;
echo 1;
',
array(
'header' => 'Made with love.',
'commentType' => 'comment',
'location' => 'after_declare_strict',
)
),
),
null,
'The following configuration options are allowed:
- header proper header content here, this option is required
- commentType PHPDoc|comment*
- location after_open|after_declare_strict*
- separate top|bottom|none|both*
* is the default when the item is omitted',
array(
'commentType' => 'comment',
'location' => 'after_declare_strict',
'separate' => 'both',
)
);
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens[0]->isGivenKind(T_OPEN_TAG) && $tokens->isMonolithicPhp();
}
/**
* Enclose the given text in a comment block.
*
* @param string $header
* @param string $type
*
* @return string
*/
private function encloseTextInComment($header, $type)
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
$comment = (self::HEADER_COMMENT === $type ? '/*' : '/**').$lineEnding;
$lines = explode("\n", str_replace("\r", '', $header));
foreach ($lines as $line) {
$comment .= rtrim(' * '.$line).$lineEnding;
}
return $comment.' */';
}
/**
* Find the header comment index.
*
* @param Tokens $tokens
* @param int $headerNewIndex
*
* @return int|null
*/
private function findHeaderCommentCurrentIndex(Tokens $tokens, $headerNewIndex)
{
$index = $tokens->getNextNonWhitespace($headerNewIndex);
return null === $index || !$tokens[$index]->isComment() ? null : $index;
}
/**
* Find the index where the header comment must be inserted.
*
* @param Tokens $tokens
*
* @return int
*/
private function findHeaderCommentInsertionIndex(Tokens $tokens)
{
if (self::HEADER_LOCATION_AFTER_OPEN === $this->headerLocation) {
return 1;
}
$index = $tokens->getNextMeaningfulToken(0);
if (null === $index) {
// file without meaningful tokens but an open tag, comment should always be placed directly after the open tag
return 1;
}
if (!$tokens[$index]->isGivenKind(T_DECLARE)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($index);
if (null === $next || !$tokens[$next]->equals('(')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(array(T_STRING, 'strict_types'), false)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals('=')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->isGivenKind(T_LNUMBER)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(')')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(';')) { // don't insert after close tag
return 1;
}
return $next + 1;
}
/**
* @param Tokens $tokens
* @param int $headerIndex
*/
private function fixWhiteSpaceAroundHeader(Tokens $tokens, $headerIndex)
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
// fix lines after header comment
$expectedLineCount = self::HEADER_LINE_SEPARATION_BOTH === $this->headerLineSeparation || self::HEADER_LINE_SEPARATION_BOTTOM === $this->headerLineSeparation ? 2 : 1;
if ($headerIndex === count($tokens) - 1) {
$tokens->insertAt($headerIndex + 1, new Token(array(T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount))));
} else {
$afterCommentIndex = $tokens->getNextNonWhitespace($headerIndex);
$lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex + 1, null === $afterCommentIndex ? count($tokens) : $afterCommentIndex);
if ($lineBreakCount < $expectedLineCount) {
$missing = str_repeat($lineEnding, $expectedLineCount - $lineBreakCount);
if ($tokens[$headerIndex + 1]->isWhitespace()) {
$tokens[$headerIndex + 1]->setContent($missing.$tokens[$headerIndex + 1]->getContent());
} else {
$tokens->insertAt($headerIndex + 1, new Token(array(T_WHITESPACE, $missing)));
}
}
}
// fix lines before header comment
$expectedLineCount = self::HEADER_LINE_SEPARATION_BOTH === $this->headerLineSeparation || self::HEADER_LINE_SEPARATION_TOP === $this->headerLineSeparation ? 2 : 1;
$lineBreakCount = $this->getLineBreakCount($tokens, $tokens->getPrevNonWhitespace($headerIndex), $headerIndex);
if ($lineBreakCount < $expectedLineCount) {
// because of the way the insert index was determined for header comment there cannot be an empty token here
$tokens->insertAt($headerIndex, new Token(array(T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount - $lineBreakCount))));
}
}
/**
* @param Tokens $tokens
* @param int $indexStart
* @param int $indexEnd
*
* @return int
*/
private function getLineBreakCount(Tokens $tokens, $indexStart, $indexEnd)
{
$lineCount = 0;
for ($i = $indexStart; $i < $indexEnd; ++$i) {
$lineCount += substr_count($tokens[$i]->getContent(), "\n");
}
return $lineCount;
}
/**
* @param Tokens $tokens
* @param int $index
*/
private function insertHeader(Tokens $tokens, $index)
{
$tokens->insertAt($index, new Token(array(self::HEADER_COMMENT === $this->headerCommentType ? T_COMMENT : T_DOC_COMMENT, $this->headerComment)));
}
/**
* @param array|null $configuration
*
* @return array
*/
private function parseConfiguration(array $configuration = null)
{
if (null === $configuration || !array_key_exists('header', $configuration)) {
throw new RequiredFixerConfigurationException($this->getName(), 'Configuration is required.');
}
$header = $configuration['header'];
if (!is_string($header)) {
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Header configuration is invalid. Expected "string", got "%s".', is_object($header) ? get_class($header) : gettype($header)));
}
if (array_key_exists('commentType', $configuration)) {
$commentType = $configuration['commentType'];
if (!in_array($commentType, array(self::HEADER_PHPDOC, self::HEADER_COMMENT), true)) {
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Header type configuration is invalid, expected "PHPDoc" or "comment", got "%s".', is_object($commentType) ? get_class($commentType) : var_export($commentType, true)));
}
} else {
$commentType = self::HEADER_COMMENT;
}
$header = '' === trim($header) ? '' : $this->encloseTextInComment($header, $commentType);
if (array_key_exists('location', $configuration)) {
$location = $configuration['location'];
switch ($location) {
case 'after_open':
$location = self::HEADER_LOCATION_AFTER_OPEN;
break;
case 'after_declare_strict':
$location = self::HEADER_LOCATION_AFTER_DECLARE_STRICT;
break;
default:
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Header location configuration is invalid, expected "after_open" or "after_declare_strict", got "%s".', is_object($location) ? get_class($location) : var_export($location, true)));
}
} else {
$location = self::HEADER_LOCATION_AFTER_DECLARE_STRICT;
}
if (array_key_exists('separate', $configuration)) {
$headerLineSeparation = $configuration['separate'];
switch ($headerLineSeparation) {
case 'both':
$headerLineSeparation = self::HEADER_LINE_SEPARATION_BOTH;
break;
case 'top':
$headerLineSeparation = self::HEADER_LINE_SEPARATION_TOP;
break;
case 'bottom':
$headerLineSeparation = self::HEADER_LINE_SEPARATION_BOTTOM;
break;
case 'none':
$headerLineSeparation = self::HEADER_LINE_SEPARATION_NONE;
break;
default:
throw new InvalidFixerConfigurationException($this->getName(), sprintf('Header separate configuration is invalid, expected "both", "top", "bottom" or "none", got "%s".', is_object($headerLineSeparation) ? get_class($headerLineSeparation) : var_export($headerLineSeparation, true)));
}
} else {
$headerLineSeparation = self::HEADER_LINE_SEPARATION_BOTH;
}
return array(
$header,
$commentType,
$location,
$headerLineSeparation,
);
}
}