forked from rectorphp/rector-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplicationFileProcessor.php
More file actions
277 lines (230 loc) · 9.64 KB
/
ApplicationFileProcessor.php
File metadata and controls
277 lines (230 loc) · 9.64 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
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
<?php
declare(strict_types=1);
namespace Rector\Core\Application;
use PHPStan\Analyser\NodeScopeResolver;
use Rector\Caching\Detector\ChangedFilesDetector;
use Rector\Core\Application\FileDecorator\FileDiffFileDecorator;
use Rector\Core\Configuration\Option;
use Rector\Core\Configuration\Parameter\ParameterProvider;
use Rector\Core\Contract\Console\OutputStyleInterface;
use Rector\Core\Contract\Processor\FileProcessorInterface;
use Rector\Core\Util\ArrayParametersMerger;
use Rector\Core\ValueObject\Application\File;
use Rector\Core\ValueObject\Configuration;
use Rector\Core\ValueObject\Error\SystemError;
use Rector\Core\ValueObject\Reporting\FileDiff;
use Rector\Core\ValueObjectFactory\Application\FileFactory;
use Rector\Parallel\Application\ParallelFileProcessor;
use Rector\Parallel\ValueObject\Bridge;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symplify\EasyParallel\CpuCoreCountProvider;
use Symplify\EasyParallel\Exception\ParallelShouldNotHappenException;
use Symplify\EasyParallel\ScheduleFactory;
final class ApplicationFileProcessor
{
/**
* @var string
*/
private const ARGV = 'argv';
/**
* @var SystemError[]
*/
private array $systemErrors = [];
/**
* @param FileProcessorInterface[] $fileProcessors
*/
public function __construct(
private readonly Filesystem $filesystem,
private readonly FileDiffFileDecorator $fileDiffFileDecorator,
private readonly OutputStyleInterface $rectorOutputStyle,
private readonly FileFactory $fileFactory,
private readonly NodeScopeResolver $nodeScopeResolver,
private readonly ArrayParametersMerger $arrayParametersMerger,
private readonly ParallelFileProcessor $parallelFileProcessor,
private readonly ParameterProvider $parameterProvider,
private readonly ScheduleFactory $scheduleFactory,
private readonly CpuCoreCountProvider $cpuCoreCountProvider,
private readonly ChangedFilesDetector $changedFilesDetector,
private readonly iterable $fileProcessors,
) {
}
/**
* @return array{system_errors: SystemError[], file_diffs: FileDiff[]}
*/
public function run(Configuration $configuration, InputInterface $input): array
{
$filePaths = $this->fileFactory->findFilesInPaths($configuration->getPaths(), $configuration);
// no files found
if ($filePaths === []) {
return [
Bridge::SYSTEM_ERRORS => [],
Bridge::FILE_DIFFS => [],
];
}
$this->configureCustomErrorHandler();
if ($configuration->isParallel()) {
$systemErrorsAndFileDiffs = $this->runParallel($filePaths, $configuration, $input);
} else {
// 1. collect all files from files+dirs provided paths
$files = $this->fileFactory->createFromPaths($filePaths);
// 2. PHPStan has to know about all files too
$this->configurePHPStanNodeScopeResolver($filePaths, $configuration);
$systemErrorsAndFileDiffs = $this->processFiles($files, $configuration);
if ($configuration->shouldShowDiffs()) {
$this->fileDiffFileDecorator->decorate($files);
}
$this->printFiles($files, $configuration);
}
$systemErrorsAndFileDiffs[Bridge::SYSTEM_ERRORS] = array_merge(
$systemErrorsAndFileDiffs[Bridge::SYSTEM_ERRORS],
$this->systemErrors
);
$this->restoreErrorHandler();
return $systemErrorsAndFileDiffs;
}
/**
* @api use only for tests
*
* @param File[] $files
* @return array{system_errors: SystemError[], file_diffs: FileDiff[]}
*/
public function processFiles(array $files, Configuration $configuration): array
{
$shouldShowProgressBar = $configuration->shouldShowProgressBar();
if ($shouldShowProgressBar) {
$fileCount = count($files);
$this->rectorOutputStyle->progressStart($fileCount);
$this->rectorOutputStyle->progressAdvance(0);
}
$systemErrorsAndFileDiffs = [
Bridge::SYSTEM_ERRORS => [],
Bridge::FILE_DIFFS => [],
];
foreach ($files as $file) {
foreach ($this->fileProcessors as $fileProcessor) {
if (! $fileProcessor->supports($file, $configuration)) {
continue;
}
$result = $fileProcessor->process($file, $configuration);
$systemErrorsAndFileDiffs = $this->arrayParametersMerger->merge($systemErrorsAndFileDiffs, $result);
}
if ($systemErrorsAndFileDiffs[Bridge::SYSTEM_ERRORS] !== []) {
$this->changedFilesDetector->invalidateFile($file->getFilePath());
} elseif (! $configuration->isDryRun() || $systemErrorsAndFileDiffs[Bridge::FILE_DIFFS] === []) {
$this->changedFilesDetector->cacheFileWithDependencies($file->getFilePath());
}
// progress bar +1
if ($shouldShowProgressBar) {
$this->rectorOutputStyle->progressAdvance();
}
}
return $systemErrorsAndFileDiffs;
}
/**
* @param string[] $filePaths
*/
public function configurePHPStanNodeScopeResolver(array $filePaths, Configuration $configuration): void
{
$fileExtensions = $configuration->getFileExtensions();
$fileWithExtensionsFilter = static function (string $filePath) use ($fileExtensions): bool {
$filePathExtension = pathinfo($filePath, PATHINFO_EXTENSION);
return in_array($filePathExtension, $fileExtensions, true);
};
$filePaths = array_filter($filePaths, $fileWithExtensionsFilter);
$this->nodeScopeResolver->setAnalysedFiles($filePaths);
}
/**
* @param File[] $files
*/
private function printFiles(array $files, Configuration $configuration): void
{
if ($configuration->isDryRun()) {
return;
}
foreach ($files as $file) {
if (! $file->hasChanged()) {
continue;
}
$this->printFile($file);
}
}
private function printFile(File $file): void
{
$filePath = $file->getFilePath();
$this->filesystem->dumpFile($filePath, $file->getFileContent());
// @todo how to keep original chmod rights?
// $this->filesystem->chmod($filePath, $smartFileInfo->getPerms());
}
/**
* Inspired by @see https://github.com/phpstan/phpstan-src/blob/89af4e7db257750cdee5d4259ad312941b6b25e8/src/Analyser/Analyser.php#L134
*/
private function configureCustomErrorHandler(): void
{
$errorHandlerCallback = function (int $code, string $message, string $file, int $line): bool {
if ((error_reporting() & $code) === 0) {
// silence @ operator
return true;
}
// not relevant for us
if (in_array($code, [E_DEPRECATED, E_WARNING], true)) {
return true;
}
$this->systemErrors[] = new SystemError($message, $file, $line);
return true;
};
set_error_handler($errorHandlerCallback);
}
private function restoreErrorHandler(): void
{
restore_error_handler();
}
/**
* @param string[] $filePaths
* @return array{system_errors: SystemError[], file_diffs: FileDiff[]}
*/
private function runParallel(array $filePaths, Configuration $configuration, InputInterface $input): array
{
// @todo possibly relative paths?
// must be a string, otherwise the serialization returns empty arrays
// $filePaths // = $this->filePathNormalizer->resolveFilePathsFromFileInfos($filePaths);
$schedule = $this->scheduleFactory->create(
$this->cpuCoreCountProvider->provide(),
$this->parameterProvider->provideIntParameter(Option::PARALLEL_JOB_SIZE),
$this->parameterProvider->provideIntParameter(Option::PARALLEL_MAX_NUMBER_OF_PROCESSES),
$filePaths
);
$postFileCallback = static function (int $stepCount): void {
};
if ($configuration->shouldShowProgressBar()) {
$fileCount = count($filePaths);
$this->rectorOutputStyle->progressStart($fileCount);
$this->rectorOutputStyle->progressAdvance(0);
$postFileCallback = function (int $stepCount): void {
$this->rectorOutputStyle->progressAdvance($stepCount);
// running in parallel here → nothing else to do
};
}
$mainScript = $this->resolveCalledRectorBinary();
if ($mainScript === null) {
throw new ParallelShouldNotHappenException('[parallel] Main script was not found');
}
// mimics see https://github.com/phpstan/phpstan-src/commit/9124c66dcc55a222e21b1717ba5f60771f7dda92#diff-387b8f04e0db7a06678eb52ce0c0d0aff73e0d7d8fc5df834d0a5fbec198e5daR139
return $this->parallelFileProcessor->process($schedule, $mainScript, $postFileCallback, $input);
}
/**
* Path to called "rector" binary file, e.g. "vendor/bin/rector" returns "vendor/bin/rector" This is needed to re-call the
* ecs binary in sub-process in the same location.
*/
private function resolveCalledRectorBinary(): ?string
{
if (! isset($_SERVER[self::ARGV][0])) {
return null;
}
$potentialEcsBinaryPath = $_SERVER[self::ARGV][0];
if (! file_exists($potentialEcsBinaryPath)) {
return null;
}
return $potentialEcsBinaryPath;
}
}