forked from PHP-CS-Fixer/PHP-CS-Fixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderedAttributesFixer.php
310 lines (257 loc) · 10.7 KB
/
OrderedAttributesFixer.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
<?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\AttributeNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
/**
* @author HypeMC <hypemc@gmail.com>
*
* @phpstan-import-type _AttributeItems from AttributeAnalysis
*/
final class OrderedAttributesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
public const ORDER_ALPHA = 'alpha';
public const ORDER_CUSTOM = 'custom';
private const SUPPORTED_SORT_ALGORITHMS = [
self::ORDER_ALPHA,
self::ORDER_CUSTOM,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Sorts attributes using the configured sort algorithm.',
[
new VersionSpecificCodeSample(
<<<'EOL'
<?php
#[Foo]
#[Bar(3)]
#[Qux(new Bar(5))]
#[Corge(a: 'test')]
class Sample1 {}
#[
Foo,
Bar(3),
Qux(new Bar(5)),
Corge(a: 'test'),
]
class Sample2 {}
EOL,
new VersionSpecification(8_00_00),
),
new VersionSpecificCodeSample(
<<<'EOL'
<?php
use A\B\Foo;
use A\B\Bar as BarAlias;
use A\B as AB;
#[Foo]
#[BarAlias(3)]
#[AB\Qux(new Bar(5))]
#[\A\B\Corge(a: 'test')]
class Sample1 {}
EOL,
new VersionSpecification(8_00_00),
['sort_algorithm' => self::ORDER_CUSTOM, 'order' => ['A\B\Qux', 'A\B\Bar', 'A\B\Corge']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after FullyQualifiedStrictTypesFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return \defined('T_ATTRIBUTE') && $tokens->isTokenKindFound(T_ATTRIBUTE);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$fixerName = $this->getName();
return new FixerConfigurationResolver([
(new FixerOptionBuilder('sort_algorithm', 'How the attributes should be sorted.'))
->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)
->setDefault(self::ORDER_ALPHA)
->setNormalizer(static function (Options $options, string $value) use ($fixerName): string {
if (self::ORDER_CUSTOM === $value && [] === $options['order']) {
throw new InvalidFixerConfigurationException(
$fixerName,
'The custom order strategy requires providing `order` option with a list of attributes\'s FQNs.'
);
}
return $value;
})
->getOption(),
(new FixerOptionBuilder('order', 'A list of FQCNs of attributes defining the desired order used when custom sorting algorithm is configured.'))
->setAllowedTypes(['string[]'])
->setDefault([])
->setNormalizer(static function (Options $options, array $value) use ($fixerName): array {
if ($value !== array_unique($value)) {
throw new InvalidFixerConfigurationException($fixerName, 'The list includes attributes that are not unique.');
}
return array_flip(array_values(
array_map(static fn (string $attribute): string => ltrim($attribute, '\\'), $value),
));
})
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$index = 0;
while (null !== $index = $tokens->getNextTokenOfKind($index, [[T_ATTRIBUTE]])) {
/** @var list<array{name: string, start: int, end: int}> $elements */
$elements = array_map(function (AttributeAnalysis $attributeAnalysis) use ($tokens): array {
return [
'name' => $this->sortAttributes($tokens, $attributeAnalysis->getStartIndex(), $attributeAnalysis->getAttributes()),
'start' => $attributeAnalysis->getStartIndex(),
'end' => $attributeAnalysis->getEndIndex(),
];
}, AttributeAnalyzer::collect($tokens, $index));
$endIndex = end($elements)['end'];
try {
if (1 === \count($elements)) {
continue;
}
$sortedElements = $this->sortElements($elements);
if ($elements === $sortedElements) {
continue;
}
$this->sortTokens($tokens, $index, $endIndex, $sortedElements);
} finally {
$index = $endIndex;
}
}
}
/**
* @param _AttributeItems $attributes
*/
private function sortAttributes(Tokens $tokens, int $index, array $attributes): string
{
if (1 === \count($attributes)) {
return $this->getAttributeName($tokens, $attributes[0]['name'], $attributes[0]['start']);
}
foreach ($attributes as &$attribute) {
$attribute['name'] = $this->getAttributeName($tokens, $attribute['name'], $attribute['start']);
}
$sortedElements = $this->sortElements($attributes);
if ($attributes === $sortedElements) {
return $attributes[0]['name'];
}
$this->sortTokens($tokens, $index + 1, end($attributes)['end'], $sortedElements, new Token(','));
return $sortedElements[0]['name'];
}
private function getAttributeName(Tokens $tokens, string $name, int $index): string
{
if (self::ORDER_CUSTOM === $this->configuration['sort_algorithm']) {
$name = $this->determineAttributeFullyQualifiedName($tokens, $name, $index);
}
return ltrim($name, '\\');
}
private function determineAttributeFullyQualifiedName(Tokens $tokens, string $name, int $index): string
{
if ('\\' === $name[0]) {
return $name;
}
if (!$tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
$index = $tokens->getNextTokenOfKind($index, [[T_STRING], [T_NS_SEPARATOR]]);
}
[$namespaceAnalysis, $namespaceUseAnalyses] = $this->collectNamespaceAnalysis($tokens, $index);
$namespace = $namespaceAnalysis->getFullName();
$firstTokenOfName = $tokens[$index]->getContent();
$namespaceUseAnalysis = $namespaceUseAnalyses[$firstTokenOfName] ?? false;
if ($namespaceUseAnalysis instanceof NamespaceUseAnalysis) {
$namespace = $namespaceUseAnalysis->getFullName();
if ($name === $firstTokenOfName) {
return $namespace;
}
$name = substr(strstr($name, '\\'), 1);
}
return $namespace.'\\'.$name;
}
/**
* @param list<array{name: string, start: int, end: int}> $elements
*
* @return list<array{name: string, start: int, end: int}>
*/
private function sortElements(array $elements): array
{
usort($elements, function (array $a, array $b): int {
$sortAlgorithm = $this->configuration['sort_algorithm'];
if (self::ORDER_ALPHA === $sortAlgorithm) {
return $a['name'] <=> $b['name'];
}
if (self::ORDER_CUSTOM === $sortAlgorithm) {
return
($this->configuration['order'][$a['name']] ?? PHP_INT_MAX)
<=>
($this->configuration['order'][$b['name']] ?? PHP_INT_MAX);
}
throw new \InvalidArgumentException(sprintf('Invalid sort algorithm "%s" provided.', $sortAlgorithm));
});
return $elements;
}
/**
* @param list<array{name: string, start: int, end: int}> $elements
*/
private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements, ?Token $delimiter = null): void
{
$replaceTokens = [];
foreach ($elements as $pos => $element) {
for ($i = $element['start']; $i <= $element['end']; ++$i) {
$replaceTokens[] = clone $tokens[$i];
}
if (null !== $delimiter && $pos !== \count($elements) - 1) {
$replaceTokens[] = clone $delimiter;
}
}
$tokens->overrideRange($startIndex, $endIndex, $replaceTokens);
}
/**
* @return array{NamespaceAnalysis, array<string, NamespaceUseAnalysis>}
*/
private function collectNamespaceAnalysis(Tokens $tokens, int $startIndex): array
{
$namespaceAnalysis = (new NamespacesAnalyzer())->getNamespaceAt($tokens, $startIndex);
$namespaceUseAnalyses = (new NamespaceUsesAnalyzer())->getDeclarationsInNamespace($tokens, $namespaceAnalysis);
$uses = [];
foreach ($namespaceUseAnalyses as $use) {
if (!$use->isClass()) {
continue;
}
$uses[$use->getShortName()] = $use;
}
return [$namespaceAnalysis, $uses];
}
}