forked from PHP-CS-Fixer/PHP-CS-Fixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultilineWhitespaceBeforeSemicolonsFixer.php
295 lines (250 loc) · 8.69 KB
/
MultilineWhitespaceBeforeSemicolonsFixer.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
<?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\Semicolon;
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\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Graham Campbell <hello@gjcampbell.co.uk>
* @author Egidijus Girčys <e.gircys@gmail.com>
*/
final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/**
* @internal
*/
public const STRATEGY_NO_MULTI_LINE = 'no_multi_line';
/**
* @internal
*/
public const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls';
/**
* {@inheritdoc}
*/
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.',
[
new CodeSample(
'<?php
function foo () {
return 1 + 2
;
}
'
),
new CodeSample(
'<?php
$this->method1()
->method2()
->method(3);
?>
',
['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS]
),
]
);
}
/**
* {@inheritdoc}
*
* Must run before SpaceAfterSemicolonFixer.
* Must run after CombineConsecutiveIssetsFixer, GetClassToClassKeywordFixer, NoEmptyStatementFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer.
*/
public function getPriority(): int
{
return 0;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(';');
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(
'strategy',
'Forbid multi-line whitespace or move the semicolon to the new line for chained calls.'
))
->setAllowedValues([self::STRATEGY_NO_MULTI_LINE, self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS])
->setDefault(self::STRATEGY_NO_MULTI_LINE)
->getOption(),
]);
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy']) {
$this->applyChainedCallsFix($tokens);
return;
}
if (self::STRATEGY_NO_MULTI_LINE === $this->configuration['strategy']) {
$this->applyNoMultiLineFix($tokens);
}
}
private function applyNoMultiLineFix(Tokens $tokens): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
foreach ($tokens as $index => $token) {
if (!$token->equals(';')) {
continue;
}
$previousIndex = $index - 1;
$previous = $tokens[$previousIndex];
if (!$previous->isWhitespace() || !str_contains($previous->getContent(), "\n")) {
continue;
}
$content = $previous->getContent();
if (str_starts_with($content, $lineEnding) && $tokens[$index - 2]->isComment()) {
$tokens->ensureWhitespaceAtIndex($previousIndex, 0, $lineEnding);
} else {
$tokens->clearAt($previousIndex);
}
}
}
private function applyChainedCallsFix(Tokens $tokens): void
{
for ($index = \count($tokens) - 1; $index >= 0; --$index) {
// continue if token is not a semicolon
if (!$tokens[$index]->equals(';')) {
continue;
}
// get the indent of the chained call, null in case it's not a chained call
$indent = $this->findWhitespaceBeforeFirstCall($index - 1, $tokens);
if (null === $indent) {
continue;
}
// unset semicolon
$tokens->clearAt($index);
// find the line ending token index after the semicolon
$index = $this->getNewLineIndex($index, $tokens);
// line ending string of the last method call
$lineEnding = $this->whitespacesConfig->getLineEnding();
// appended new line to the last method call
$newline = new Token([T_WHITESPACE, $lineEnding.$indent]);
// insert the new line with indented semicolon
$tokens->insertAt($index, [$newline, new Token(';')]);
}
}
/**
* Find the index for the new line. Return the given index when there's no new line.
*/
private function getNewLineIndex(int $index, Tokens $tokens): int
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
for ($index, $count = \count($tokens); $index < $count; ++$index) {
if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) {
return $index;
}
}
return $index;
}
/**
* Checks if the semicolon closes a chained call and returns the whitespace of the first call at $index.
* i.e. it will return the whitespace marked with '____' in the example underneath.
*
* ..
* ____$this->methodCall()
* ->anotherCall();
* ..
*/
private function findWhitespaceBeforeFirstCall(int $index, Tokens $tokens): ?string
{
// semicolon followed by a closing bracket?
if (!$tokens[$index]->equals(')')) {
return null;
}
// find opening bracket
$openingBrackets = 1;
for (--$index; $index > 0; --$index) {
if ($tokens[$index]->equals(')')) {
++$openingBrackets;
continue;
}
if ($tokens[$index]->equals('(')) {
if (1 === $openingBrackets) {
break;
}
--$openingBrackets;
}
}
// method name
if (!$tokens[--$index]->isGivenKind(T_STRING)) {
return null;
}
// ->, ?-> or ::
if (!$tokens[--$index]->isObjectOperator() && !$tokens[$index]->isGivenKind(T_DOUBLE_COLON)) {
return null;
}
// white space
if (!$tokens[--$index]->isGivenKind(T_WHITESPACE)) {
return null;
}
$closingBrackets = 0;
for ($index; $index >= 0; --$index) {
if ($tokens[$index]->equals(')')) {
++$closingBrackets;
}
if ($tokens[$index]->equals('(')) {
--$closingBrackets;
}
// must be the variable of the first call in the chain
if ($tokens[$index]->isGivenKind([T_VARIABLE, T_RETURN, T_STRING]) && 0 === $closingBrackets) {
if ($tokens[--$index]->isGivenKind(T_WHITESPACE)
|| $tokens[$index]->isGivenKind(T_OPEN_TAG)) {
return $this->getIndentAt($tokens, $index);
}
}
}
return null;
}
private function getIndentAt(Tokens $tokens, int $index): ?string
{
$content = '';
$lineEnding = $this->whitespacesConfig->getLineEnding();
// find line ending token
for ($index; $index > 0; --$index) {
if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) {
break;
}
}
if ($tokens[$index]->isWhitespace()) {
$content = $tokens[$index]->getContent();
--$index;
}
if ($tokens[$index]->isGivenKind(T_OPEN_TAG)) {
$content = $tokens[$index]->getContent().$content;
}
if (1 === Preg::match('/\R{1}(\h*)$/', $content, $matches)) {
return $matches[1];
}
return null;
}
}