/
PhpdocOrderFixer.php
208 lines (176 loc) · 6.98 KB
/
PhpdocOrderFixer.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
<?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\Phpdoc;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
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\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @author Graham Campbell <hello@gjcampbell.co.uk>
* @author Jakub Kwaśniewski <jakub@zero-85.pl>
*/
final class PhpdocOrderFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/**
* @const string[]
*
* @TODO: 4.0 - change default to ['param', 'return', 'throws']
*/
private const ORDER_DEFAULT = ['param', 'throws', 'return'];
public function getDefinition(): FixerDefinitionInterface
{
$code = <<<'EOF'
<?php
/**
* Hello there!
*
* @throws Exception|RuntimeException foo
* @custom Test!
* @return int Return the number of changes.
* @param string $foo
* @param bool $bar Bar
*/
EOF;
return new FixerDefinition(
'Annotations in PHPDoc should be ordered in defined sequence.',
[
new CodeSample($code),
new CodeSample($code, ['order' => self::ORDER_DEFAULT]),
new CodeSample($code, ['order' => ['param', 'return', 'throws']]),
new CodeSample($code, ['order' => ['param', 'custom', 'throws', 'return']]),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
/**
* {@inheritdoc}
*
* Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer.
* Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoEmptyReturnFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
*/
public function getPriority(): int
{
return -2;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('order', 'Sequence in which annotations in PHPDoc should be ordered.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([static function (array $order): bool {
if (\count($order) < 2) {
throw new InvalidOptionsException('The option "order" value is invalid. Minimum two tags are required.');
}
return true;
}])
->setDefault(self::ORDER_DEFAULT)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(T_DOC_COMMENT)) {
continue;
}
// assuming annotations are already grouped by tags
$content = $token->getContent();
// sort annotations
$successors = $this->configuration['order'];
while (\count($successors) >= 3) {
$predecessor = array_shift($successors);
$content = $this->moveAnnotationsBefore($predecessor, $successors, $content);
}
// we're parsing the content last time to make sure the internal
// state of the docblock is correct after the modifications
$predecessors = $this->configuration['order'];
$last = array_pop($predecessors);
$content = $this->moveAnnotationsAfter($last, $predecessors, $content);
// persist the content at the end
$tokens[$index] = new Token([T_DOC_COMMENT, $content]);
}
}
/**
* Move all given annotations in before given set of annotations.
*
* @param string $move Tag of annotations that should be moved
* @param string[] $before Tags of annotations that should moved annotations be placed before
*/
private function moveAnnotationsBefore(string $move, array $before, string $content): string
{
$doc = new DocBlock($content);
$toBeMoved = $doc->getAnnotationsOfType($move);
// nothing to do if there are no annotations to be moved
if (0 === \count($toBeMoved)) {
return $content;
}
$others = $doc->getAnnotationsOfType($before);
if (0 === \count($others)) {
return $content;
}
// get the index of the final line of the final toBoMoved annotation
$end = end($toBeMoved)->getEnd();
$line = $doc->getLine($end);
// move stuff about if required
foreach ($others as $other) {
if ($other->getStart() < $end) {
// we're doing this to maintain the original line indices
$line->setContent($line->getContent().$other->getContent());
$other->remove();
}
}
return $doc->getContent();
}
/**
* Move all given annotations after given set of annotations.
*
* @param string $move Tag of annotations that should be moved
* @param string[] $after Tags of annotations that should moved annotations be placed after
*/
private function moveAnnotationsAfter(string $move, array $after, string $content): string
{
$doc = new DocBlock($content);
$toBeMoved = $doc->getAnnotationsOfType($move);
// nothing to do if there are no annotations to be moved
if (0 === \count($toBeMoved)) {
return $content;
}
$others = $doc->getAnnotationsOfType($after);
// nothing to do if there are no other annotations
if (0 === \count($others)) {
return $content;
}
// get the index of the first line of the first toBeMoved annotation
$start = $toBeMoved[0]->getStart();
$line = $doc->getLine($start);
// move stuff about if required
foreach (array_reverse($others) as $other) {
if ($other->getEnd() > $start) {
// we're doing this to maintain the original line indices
$line->setContent($other->getContent().$line->getContent());
$other->remove();
}
}
return $doc->getContent();
}
}