-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathTypeHintOrderFixer.php
223 lines (181 loc) · 6.55 KB
/
TypeHintOrderFixer.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
<?php
declare(strict_types=1);
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao\EasyCodingStandard\Fixer;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class TypeHintOrderFixer extends AbstractFixer
{
use IndentationFixerTrait;
private static array $nativeTypes = [
'array',
'callable',
'bool',
'float',
'int',
'string',
'iterable',
'object',
'mixed',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Type hints must be ordered and grouped by non-native types and native types.',
[
new CodeSample(
<<<'EOT'
<?php
class Foo
{
public function __construct(
private readonly FooService|null $fooService,
private int|iterable $count,
private readonly Logger|null $logger = null
) {
}
}
EOT,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FUNCTION, T_FN]);
}
/**
* Must run after NoUselessReturnFixer.
*/
public function getPriority(): int
{
return -20;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 1, $count = \count($tokens); $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FUNCTION, T_FN])) {
continue;
}
// Anonymous functions
if ($tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) {
$index = $this->handleFunction($tokens, $index);
continue;
}
$nextMeaningful = $tokens->getNextMeaningfulToken($index);
// Ignore constants
if ($tokens[$nextMeaningful]->isGivenKind(T_CONST)) {
continue;
}
if ($tokens[$nextMeaningful]->isGivenKind(T_STATIC)) {
$nextMeaningful = $tokens->getNextMeaningfulToken($nextMeaningful);
}
if (\defined('T_READONLY') && $tokens[$nextMeaningful]->isGivenKind(T_READONLY)) {
$nextMeaningful = $tokens->getNextMeaningfulToken($nextMeaningful);
}
// No type hint
if ($tokens[$nextMeaningful]->isGivenKind(T_VARIABLE)) {
continue;
}
if ($tokens[$nextMeaningful]->isGivenKind(T_FUNCTION)) {
$index = $this->handleFunction($tokens, $nextMeaningful);
} else {
$index = $this->handleClassProperty($tokens, $nextMeaningful);
}
}
}
private function handleFunction(Tokens $tokens, int $nextMeaningful): int
{
$end = $tokens->getNextTokenOfKind($nextMeaningful, [';', '{']);
// Arguments
$argsStart = $tokens->getNextTokenOfKind($nextMeaningful, ['(']);
$argsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argsStart);
$vars = $tokens->findGivenKind(T_VARIABLE, $argsStart, $argsEnd);
if ([] !== $vars) {
foreach (array_keys($vars) as $pos) {
$prevMeaningful = $tokens->getPrevMeaningfulToken($pos);
// No type hint
if ($tokens[$prevMeaningful]->equals('(') || $tokens[$prevMeaningful]->equals(',')) {
continue;
}
while ($prevMeaningful - 1 > $argsStart && !$tokens[$prevMeaningful - 1]->isGivenKind(T_WHITESPACE)) {
--$prevMeaningful;
}
if ($new = $this->orderTypeHint($tokens->generatePartialCode($prevMeaningful, $pos - 2))) {
$tokens->overrideRange($prevMeaningful, $pos - 2, $new);
}
}
}
// Return type
$vars = $tokens->findGivenKind(CT::T_TYPE_COLON, $argsEnd, $end - 1);
if ([] !== $vars) {
$start = $stop = array_key_first($vars) + 2;
while ($stop < $end - 1 && !$tokens[$stop + 1]->isGivenKind(T_WHITESPACE)) {
++$stop;
}
if ($new = $this->orderTypeHint($tokens->generatePartialCode($start, $stop))) {
$tokens->overrideRange($start, $stop, $new);
}
}
return $end;
}
private function handleClassProperty(Tokens $tokens, int $nextMeaningful): int
{
$end = $tokens->getNextTokenOfKind($nextMeaningful, [';']);
for ($i = $nextMeaningful; $i <= $end; ++$i) {
if ($tokens[$i]->isGivenKind(T_VARIABLE)) {
if ($new = $this->orderTypeHint($tokens->generatePartialCode($nextMeaningful, $i - 2))) {
$tokens->overrideRange($nextMeaningful, $i - 2, $new);
}
break;
}
}
return $end;
}
private function orderTypeHint(string $typehint): Tokens|null
{
if (!str_contains($typehint, '|') && !str_contains($typehint, '?')) {
return null;
}
$natives = [];
$objects = [];
$hasFalse = false;
$hasNull = false;
$chunks = explode('|', $typehint);
foreach ($chunks as $chunk) {
if ('?' === $chunk[0]) {
$chunk = substr($chunk, 1);
$hasNull = true;
}
if ('false' === $chunk) {
$hasFalse = true;
} elseif ('null' === $chunk) {
$hasNull = true;
} elseif (\in_array($chunk, self::$nativeTypes, true)) {
$natives[$chunk] = $chunk;
} else {
$objects[ltrim($chunk, '\\')] = $chunk;
}
}
ksort($natives);
ksort($objects);
$new = implode('|', [...array_values($objects), ...array_values($natives)]);
if ($hasFalse) {
$new .= '|false';
}
if ($hasNull) {
$new .= '|null';
}
return Tokens::fromCode($new);
}
}