Repository navigation
Expand file tree
/
Copy pathFileProcessor.php
More file actions
232 lines (191 loc) · 9.05 KB
/
Copy pathFileProcessor.php
File metadata and controls
232 lines (191 loc) · 9.05 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
<?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\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();
// infinite-loop guard: remember every file content the loop produces; a rule set that
// keeps flipping the file between states would never settle, so once a content repeats
// we stop and report instead of looping forever
$seenContentHashes = [
hash('xxh128', $file->getOriginalFileContent()) => true,
];
do {
$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);
// no change in current iteration, stop
if (! $file->hasChanged()) {
break;
}
$fileHasChanged = true;
// this exact content was already produced in an earlier pass: the rules cycle
// and will never converge, so stop here
$contentHash = hash('xxh128', $file->getFileContent());
if (isset($seenContentHashes[$contentHash])) {
return $this->createNotConvergingResult($file, $fileHasChanged);
}
$seenContentHashes[$contentHash] = 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());
}
private function createNotConvergingResult(File $file, bool $fileHasChanged): FileProcessResult
{
$rectorClasses = [];
foreach ($file->getRectorWithLineChanges() as $rectorWithLineChange) {
$rectorClasses[$rectorWithLineChange->getRectorClass()] = true;
}
$message = sprintf(
'File did not stabilize, the rules keep flipping it between states. Rules applied: %s',
implode(', ', array_keys($rectorClasses))
);
// in tests a non-converging file is a rule bug that must surface, not a silent partial result
if (StaticPHPUnitEnvironment::isPHPUnitRun()) {
throw new ShouldNotHappenException($message . ' in ' . $file->getFilePath());
}
$systemError = new SystemError($message, $this->filePathHelper->relativePath($file->getFilePath()));
return new FileProcessResult([$systemError], $file->getFileDiff(), $fileHasChanged);
}
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);
}
}