Repository navigation
Expand file tree
/
Copy pathFileProcessor.php
More file actions
245 lines (203 loc) · 9.63 KB
/
Copy pathFileProcessor.php
File metadata and controls
245 lines (203 loc) · 9.63 KB
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
<?php
declare(strict_types=1);
namespace Rector\Application;
use Nette\Utils\FileSystem;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PHPStan\AnalysedCodeException;
use PHPStan\Parser\ParserErrorsException;
use Rector\Caching\Detector\ChangedFilesDetector;
use Rector\ChangesReporting\ValueObjectFactory\ErrorFactory;
use Rector\ChangesReporting\ValueObjectFactory\FileDiffFactory;
use Rector\CodingStyle\ClassNameImport\UsedImportsResolver;
use Rector\Exception\ShouldNotHappenException;
use Rector\FileSystem\FilePathHelper;
use Rector\NodeTypeResolver\NodeScopeAndMetadataDecorator;
use Rector\PhpParser\Node\FileNode;
use Rector\PhpParser\NodeTraverser\RectorNodeTraverser;
use Rector\PhpParser\Parser\ParserErrors;
use Rector\PhpParser\Parser\RectorParser;
use Rector\PhpParser\Printer\BetterStandardPrinter;
use Rector\PostRector\Application\PostFileProcessor;
use Rector\PostRector\Contract\Rector\PostRectorInterface;
use Rector\Testing\PHPUnit\StaticPHPUnitEnvironment;
use Rector\ValueObject\Application\File;
use Rector\ValueObject\Configuration;
use Rector\ValueObject\Error\SystemError;
use Rector\ValueObject\FileProcessResult;
use Symfony\Component\Console\Style\SymfonyStyle;
use Throwable;
final readonly class FileProcessor
{
public function __construct(
private BetterStandardPrinter $betterStandardPrinter,
private RectorNodeTraverser $rectorNodeTraverser,
private SymfonyStyle $symfonyStyle,
private FileDiffFactory $fileDiffFactory,
private ChangedFilesDetector $changedFilesDetector,
private ErrorFactory $errorFactory,
private FilePathHelper $filePathHelper,
private PostFileProcessor $postFileProcessor,
private RectorParser $rectorParser,
private NodeScopeAndMetadataDecorator $nodeScopeAndMetadataDecorator,
private UsedImportsResolver $usedImportsResolver,
) {
}
public function processFile(File $file, Configuration $configuration): FileProcessResult
{
// 1. parse files to nodes
$parsingSystemError = $this->parseFileAndDecorateNodes($file);
if ($parsingSystemError instanceof SystemError) {
// we cannot process this file as the parsing and type resolving itself went wrong
return new FileProcessResult([$parsingSystemError], null, false);
}
$fileHasChanged = false;
$filePath = $file->getFilePath();
$previousPassRectorClasses = [];
do {
$ruleChangesBefore = count($file->getRectorWithLineChanges());
$file->changeHasChanged(false);
// 1. change nodes with Rector Rules
$newStmts = $this->rectorNodeTraverser->traverse($file->getNewStmts(), $file);
// 2. apply post rectors
$postNewStmts = $this->postFileProcessor->traverse($newStmts, $file);
// 3. this is needed for new tokens added in "afterTraverse()"
$file->changeNewStmts($postNewStmts);
// 4. print to file or string
// important to detect if file has changed
$this->printFile($file, $configuration, $filePath);
// in rector-src tests, fail a rule that re-applies to its own previous-pass output;
// such a rule is not finished in a single pass and must handle the nested/chained case itself.
// gated by env so sibling packages pulling rector-src as dev-main are not affected
if (StaticPHPUnitEnvironment::isPHPUnitRun() && getenv('RECTOR_ENFORCE_SINGLE_PASS') === '1') {
$previousPassRectorClasses = $this->ensureRectorsAreIdempotent(
$file,
$ruleChangesBefore,
$previousPassRectorClasses
);
}
// no change in current iteration, stop
if (! $file->hasChanged()) {
break;
}
$fileHasChanged = true;
} while (true);
// 5. add as cacheable if not changed at all
if (! $fileHasChanged) {
$this->changedFilesDetector->addCacheableFile($filePath);
} else {
// when changed, set final status changed to true
// to ensure it make sense to verify in next process when needed
$file->changeHasChanged(true);
}
$rectorWithLineChanges = $file->getRectorWithLineChanges();
if ($file->hasChanged() || $rectorWithLineChanges !== []) {
$currentFileDiff = $this->fileDiffFactory->createFileDiffWithLineChanges(
$configuration->shouldShowDiffs(),
$file,
$file->getOriginalFileContent(),
$file->getFileContent(),
$file->getRectorWithLineChanges()
);
$file->setFileDiff($currentFileDiff);
}
return new FileProcessResult([], $file->getFileDiff(), $file->hasChanged());
}
/**
* @param array<string, true> $previousPassRectorClasses rule classes that changed the file in the previous pass
* @return array<string, true> rule classes that changed the file in the current pass
*/
private function ensureRectorsAreIdempotent(File $file, int $ruleChangesBefore, array $previousPassRectorClasses): array
{
$currentPassRectorClasses = [];
$rectorWithLineChanges = $file->getRectorWithLineChanges();
foreach ($rectorWithLineChanges as $key => $rectorWithLineChange) {
if ($key < $ruleChangesBefore) {
continue;
}
$rectorClass = $rectorWithLineChange->getRectorClass();
// post rectors (imports) legitimately converge over several passes
if (is_a($rectorClass, PostRectorInterface::class, true)) {
continue;
}
$currentPassRectorClasses[$rectorClass] = true;
if (isset($previousPassRectorClasses[$rectorClass])) {
throw new ShouldNotHappenException(sprintf(
'The "%s" rule changed "%s" again after it already changed it in the previous pass. ' .
'A rule must reach its final result in a single pass; handle the nested or chained case inside refactor() instead of relying on the file being re-run.',
$rectorClass,
$file->getFilePath()
));
}
}
return $currentPassRectorClasses;
}
private function parseFileAndDecorateNodes(File $file): ?SystemError
{
try {
try {
$this->parseFileNodes($file);
} catch (ParserErrorsException) {
$this->parseFileNodes($file, false);
}
} catch (ShouldNotHappenException $shouldNotHappenException) {
throw $shouldNotHappenException;
} catch (AnalysedCodeException $analysedCodeException) {
// inform about missing classes in tests
if (StaticPHPUnitEnvironment::isPHPUnitRun()) {
throw $analysedCodeException;
}
return $this->errorFactory->createAutoloadError($analysedCodeException, $file->getFilePath());
} catch (Throwable $throwable) {
if ($this->symfonyStyle->isVerbose() || StaticPHPUnitEnvironment::isPHPUnitRun()) {
throw $throwable;
}
$relativeFilePath = $this->filePathHelper->relativePath($file->getFilePath());
if ($throwable instanceof ParserErrorsException) {
$throwable = new ParserErrors($throwable);
}
return new SystemError($throwable->getMessage(), $relativeFilePath, $throwable->getLine());
}
return null;
}
private function printFile(File $file, Configuration $configuration, string $filePath): void
{
// only save to string first, no need to print to file when not needed
$newFileContent = $this->betterStandardPrinter->printFormatPreserving(
$file->getNewStmts(),
$file->getOldStmts(),
$file->getOldTokens()
);
// change file content early to make $file->hasChanged() based on new content
$file->changeFileContent($newFileContent);
if ($configuration->isDryRun()) {
return;
}
if (! $file->hasChanged()) {
return;
}
FileSystem::write($filePath, $newFileContent, null);
}
private function parseFileNodes(File $file, bool $forNewestSupportedVersion = true): void
{
// store tokens by original file content, so we don't have to print them right now
$stmtsAndTokens = $this->rectorParser->parseFileContentToStmtsAndTokens(
$file->getOriginalFileContent(),
$forNewestSupportedVersion
);
$oldStmts = $stmtsAndTokens->getStmts();
// resolve names up front, so used imports (incl. the class FQN) are resolvable at construction,
// before scope decoration runs; only annotates namespacedName, does not replace name nodes
$nameResolvingNodeTraverser = new NodeTraverser(new NameResolver(null, [
'preserveOriginalNames' => true,
'replaceNodes' => false,
]));
$nameResolvingNodeTraverser->traverse($oldStmts);
// wrap in FileNode to allow file-level rules; seed used imports once, kept in sync incrementally
$usedImports = $this->usedImportsResolver->resolveForStmts($oldStmts);
$oldStmts = [new FileNode($oldStmts, $usedImports)];
$oldTokens = $stmtsAndTokens->getTokens();
$newStmts = $this->nodeScopeAndMetadataDecorator->decorateNodesFromFile($file->getFilePath(), $oldStmts);
$file->hydrateStmtsAndTokens($newStmts, $oldStmts, $oldTokens);
}
}