/
AnalyseApplication.php
244 lines (221 loc) · 8.35 KB
/
AnalyseApplication.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
<?php declare(strict_types = 1);
namespace PHPStan\Command;
use PHPStan\AnalysedCodeException;
use PHPStan\Analyser\AnalyserResult;
use PHPStan\Analyser\Error;
use PHPStan\Analyser\IgnoredErrorHelper;
use PHPStan\Analyser\ResultCache\ResultCacheManagerFactory;
use PHPStan\Analyser\RuleErrorTransformer;
use PHPStan\Analyser\ScopeContext;
use PHPStan\Analyser\ScopeFactory;
use PHPStan\BetterReflection\NodeCompiler\Exception\UnableToCompileNode;
use PHPStan\BetterReflection\Reflection\Exception\CircularReference;
use PHPStan\BetterReflection\Reflection\Exception\NotAClassReflection;
use PHPStan\BetterReflection\Reflection\Exception\NotAnInterfaceReflection;
use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
use PHPStan\Collectors\CollectedData;
use PHPStan\Internal\BytesHelper;
use PHPStan\Node\CollectedDataNode;
use PHPStan\PhpDoc\StubFilesProvider;
use PHPStan\PhpDoc\StubValidator;
use PHPStan\Rules\Registry as RuleRegistry;
use PHPStan\ShouldNotHappenException;
use Symfony\Component\Console\Input\InputInterface;
use function array_merge;
use function count;
use function is_string;
use function memory_get_peak_usage;
use function microtime;
use function sprintf;
class AnalyseApplication
{
public function __construct(
private AnalyserRunner $analyserRunner,
private StubValidator $stubValidator,
private ResultCacheManagerFactory $resultCacheManagerFactory,
private IgnoredErrorHelper $ignoredErrorHelper,
private int $internalErrorsCountLimit,
private StubFilesProvider $stubFilesProvider,
private RuleRegistry $ruleRegistry,
private ScopeFactory $scopeFactory,
private RuleErrorTransformer $ruleErrorTransformer,
)
{
}
/**
* @param string[] $files
* @param mixed[]|null $projectConfigArray
*/
public function analyse(
array $files,
bool $onlyFiles,
Output $stdOutput,
Output $errorOutput,
bool $defaultLevelUsed,
bool $debug,
?string $projectConfigFile,
?array $projectConfigArray,
InputInterface $input,
): AnalysisResult
{
$resultCacheManager = $this->resultCacheManagerFactory->create([]);
$ignoredErrorHelperResult = $this->ignoredErrorHelper->initialize();
if (count($ignoredErrorHelperResult->getErrors()) > 0) {
$errors = $ignoredErrorHelperResult->getErrors();
$internalErrors = [];
$collectedData = [];
$savedResultCache = false;
$memoryUsageBytes = memory_get_peak_usage(true);
if ($errorOutput->isDebug()) {
$errorOutput->writeLineFormatted('Result cache was not saved because of ignoredErrorHelperResult errors.');
}
} else {
$resultCache = $resultCacheManager->restore($files, $debug, $onlyFiles, $projectConfigArray, $errorOutput);
$intermediateAnalyserResult = $this->runAnalyser(
$resultCache->getFilesToAnalyse(),
$files,
$debug,
$projectConfigFile,
$stdOutput,
$errorOutput,
$input,
);
$projectStubFiles = $this->stubFilesProvider->getProjectStubFiles();
if ($resultCache->isFullAnalysis() && count($projectStubFiles) !== 0) {
$stubErrors = $this->stubValidator->validate($projectStubFiles, $debug);
$intermediateAnalyserResult = new AnalyserResult(
array_merge($intermediateAnalyserResult->getErrors(), $stubErrors),
$intermediateAnalyserResult->getInternalErrors(),
$intermediateAnalyserResult->getCollectedData(),
$intermediateAnalyserResult->getDependencies(),
$intermediateAnalyserResult->getExportedNodes(),
$intermediateAnalyserResult->hasReachedInternalErrorsCountLimit(),
$intermediateAnalyserResult->getPeakMemoryUsageBytes(),
);
}
$resultCacheResult = $resultCacheManager->process($intermediateAnalyserResult, $resultCache, $errorOutput, $onlyFiles, true);
$analyserResult = $resultCacheResult->getAnalyserResult();
$internalErrors = $analyserResult->getInternalErrors();
$errors = $analyserResult->getErrors();
$hasInternalErrors = count($internalErrors) > 0 || $analyserResult->hasReachedInternalErrorsCountLimit();
$memoryUsageBytes = $analyserResult->getPeakMemoryUsageBytes();
if (!$hasInternalErrors) {
foreach ($this->getCollectedDataErrors($analyserResult->getCollectedData()) as $error) {
$errors[] = $error;
}
}
$errors = $ignoredErrorHelperResult->process($errors, $onlyFiles, $files, $hasInternalErrors);
$collectedData = $analyserResult->getCollectedData();
$savedResultCache = $resultCacheResult->isSaved();
if ($analyserResult->hasReachedInternalErrorsCountLimit()) {
$errors[] = sprintf('Reached internal errors count limit of %d, exiting...', $this->internalErrorsCountLimit);
}
$errors = array_merge($errors, $internalErrors);
}
$fileSpecificErrors = [];
$notFileSpecificErrors = [];
foreach ($errors as $error) {
if (is_string($error)) {
$notFileSpecificErrors[] = $error;
continue;
}
$fileSpecificErrors[] = $error;
}
return new AnalysisResult(
$fileSpecificErrors,
$notFileSpecificErrors,
$internalErrors,
[],
$collectedData,
$defaultLevelUsed,
$projectConfigFile,
$savedResultCache,
$memoryUsageBytes,
);
}
/**
* @param CollectedData[] $collectedData
* @return Error[]
*/
private function getCollectedDataErrors(array $collectedData): array
{
$nodeType = CollectedDataNode::class;
$node = new CollectedDataNode($collectedData);
$file = 'N/A';
$scope = $this->scopeFactory->create(ScopeContext::create($file));
$errors = [];
foreach ($this->ruleRegistry->getRules($nodeType) as $rule) {
try {
$ruleErrors = $rule->processNode($node, $scope);
} catch (AnalysedCodeException $e) {
$errors[] = new Error($e->getMessage(), $file, $node->getLine(), $e, null, null, $e->getTip());
continue;
} catch (IdentifierNotFound $e) {
$errors[] = new Error(sprintf('Reflection error: %s not found.', $e->getIdentifier()->getName()), $file, $node->getLine(), $e, null, null, 'Learn more at https://phpstan.org/user-guide/discovering-symbols');
continue;
} catch (UnableToCompileNode | NotAClassReflection | NotAnInterfaceReflection | CircularReference $e) {
$errors[] = new Error(sprintf('Reflection error: %s', $e->getMessage()), $file, $node->getLine(), $e);
continue;
}
foreach ($ruleErrors as $ruleError) {
$errors[] = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getLine());
}
}
return $errors;
}
/**
* @param string[] $files
* @param string[] $allAnalysedFiles
*/
private function runAnalyser(
array $files,
array $allAnalysedFiles,
bool $debug,
?string $projectConfigFile,
Output $stdOutput,
Output $errorOutput,
InputInterface $input,
): AnalyserResult
{
$filesCount = count($files);
$allAnalysedFilesCount = count($allAnalysedFiles);
if ($filesCount === 0) {
$errorOutput->getStyle()->progressStart($allAnalysedFilesCount);
$errorOutput->getStyle()->progressAdvance($allAnalysedFilesCount);
$errorOutput->getStyle()->progressFinish();
return new AnalyserResult([], [], [], [], [], false, memory_get_peak_usage(true));
}
if (!$debug) {
$preFileCallback = null;
$postFileCallback = static function (int $step) use ($errorOutput): void {
$errorOutput->getStyle()->progressAdvance($step);
};
$errorOutput->getStyle()->progressStart($allAnalysedFilesCount);
$errorOutput->getStyle()->progressAdvance($allAnalysedFilesCount - $filesCount);
} else {
$startTime = null;
$preFileCallback = static function (string $file) use ($stdOutput, &$startTime): void {
$stdOutput->writeLineFormatted($file);
$startTime = microtime(true);
};
$postFileCallback = null;
if ($stdOutput->isDebug()) {
$previousMemory = memory_get_peak_usage(true);
$postFileCallback = static function () use ($stdOutput, &$previousMemory, &$startTime): void {
if ($startTime === null) {
throw new ShouldNotHappenException();
}
$currentTotalMemory = memory_get_peak_usage(true);
$elapsedTime = microtime(true) - $startTime;
$stdOutput->writeLineFormatted(sprintf('--- consumed %s, total %s, took %.2f s', BytesHelper::bytes($currentTotalMemory - $previousMemory), BytesHelper::bytes($currentTotalMemory), $elapsedTime));
$previousMemory = $currentTotalMemory;
};
}
}
$analyserResult = $this->analyserRunner->runAnalyser($files, $allAnalysedFiles, $preFileCallback, $postFileCallback, $debug, true, $projectConfigFile, null, null, $input);
if (!$debug) {
$errorOutput->getStyle()->progressFinish();
}
return $analyserResult;
}
}