1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Testing;
4:
5: use Nette\Utils\FileSystem;
6: use PhpParser\Node;
7: use PHPStan\Analyser\Analyser;
8: use PHPStan\Analyser\AnalyserResultFinalizer;
9: use PHPStan\Analyser\Error;
10: use PHPStan\Analyser\ExpressionResultFactory;
11: use PHPStan\Analyser\FileAnalyser;
12: use PHPStan\Analyser\FixedErrorDiff;
13: use PHPStan\Analyser\Generics\TemplateArgumentObserver;
14: use PHPStan\Analyser\Ignore\LineIgnoreFixer;
15: use PHPStan\Analyser\Ignore\UnmatchedIgnoreFixer;
16: use PHPStan\Analyser\IgnoreErrorExtension;
17: use PHPStan\Analyser\InternalError;
18: use PHPStan\Analyser\LocalIgnoresProcessor;
19: use PHPStan\Analyser\NodeScopeResolver;
20: use PHPStan\Analyser\PerFileAnalysisResettable;
21: use PHPStan\Analyser\RuleErrorTransformer;
22: use PHPStan\Analyser\StatementsHandler;
23: use PHPStan\Analyser\TypeSpecifier;
24: use PHPStan\Analyser\ValueDependencyCollector;
25: use PHPStan\Collectors\Collector;
26: use PHPStan\Collectors\Registry as CollectorRegistry;
27: use PHPStan\Dependency\DependencyResolver;
28: use PHPStan\File\FileHelper;
29: use PHPStan\File\FileReader;
30: use PHPStan\Fixable\Patcher;
31: use PHPStan\Rules\DirectRegistry as DirectRuleRegistry;
32: use PHPStan\Rules\IdentifierRuleError;
33: use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
34: use PHPStan\Rules\Rule;
35: use PHPStan\ShouldNotHappenException;
36: use function array_combine;
37: use function array_flip;
38: use function array_intersect_key;
39: use function array_key_exists;
40: use function array_map;
41: use function array_merge;
42: use function array_unique;
43: use function array_values;
44: use function basename;
45: use function count;
46: use function implode;
47: use function sprintf;
48: use function str_replace;
49: use function strcmp;
50: use function sys_get_temp_dir;
51: use function uniqid;
52: use function usort;
53:
54: /**
55: * @api
56: * @template TRule of Rule
57: */
58: abstract class RuleTestCase extends PHPStanTestCase
59: {
60:
61: private const FIX_ROUNDS_LIMIT = 10;
62:
63: private ?Analyser $analyser = null;
64:
65: /**
66: * @return TRule
67: */
68: abstract protected function getRule(): Rule;
69:
70: /**
71: * @return array<Collector<Node, mixed>>
72: */
73: protected function getCollectors(): array
74: {
75: return [];
76: }
77:
78: /**
79: * No longer configures the analysis - register the extensions as services
80: * in a config file returned from getAdditionalConfigFiles() instead.
81: * Returning any extension fails the test.
82: *
83: * @return ReadWritePropertiesExtension[]
84: */
85: protected function getReadWritePropertiesExtensions(): array
86: {
87: return [];
88: }
89:
90: protected function getTypeSpecifier(): TypeSpecifier
91: {
92: return self::getContainer()->getService('typeSpecifier');
93: }
94:
95: protected function createNodeScopeResolver(): NodeScopeResolver
96: {
97: if (
98: $this->getReadWritePropertiesExtensions() !== []
99: || $this->shouldPolluteScopeWithLoopInitialAssignments() !== self::getContainer()->getParameter('polluteScopeWithLoopInitialAssignments')
100: || $this->shouldPolluteScopeWithAlwaysIterableForeach() !== self::getContainer()->getParameter('polluteScopeWithAlwaysIterableForeach')
101: ) {
102: throw new ShouldNotHappenException('getReadWritePropertiesExtensions(), shouldPolluteScopeWithLoopInitialAssignments() and shouldPolluteScopeWithAlwaysIterableForeach() no longer configure the analysis. Register the extensions as services and set the parameters in a config file returned from getAdditionalConfigFiles() instead.');
103: }
104:
105: return new NodeScopeResolver(
106: self::getContainer(),
107: self::getContainer()->getByType(TemplateArgumentObserver::class),
108: self::getContainer()->getByType(FileHelper::class),
109: self::getContainer()->getExtensionsCollection(PerFileAnalysisResettable::class),
110: self::getContainer()->getByType(ExpressionResultFactory::class),
111: self::getContainer()->getByType(StatementsHandler::class),
112: );
113: }
114:
115: private function getAnalyser(DirectRuleRegistry $ruleRegistry): Analyser
116: {
117: if ($this->analyser === null) {
118: $collectorRegistry = new CollectorRegistry($this->getCollectors());
119:
120: $nodeScopeResolver = $this->createNodeScopeResolver();
121:
122: $fileAnalyser = new FileAnalyser(
123: self::createScopeFactory(
124: $this->createReflectionProvider(),
125: $this->getTypeSpecifier(),
126: ),
127: $nodeScopeResolver,
128: $this->getParser(),
129: self::getContainer()->getExtensionsCollection(IgnoreErrorExtension::class),
130: self::getContainer()->getByType(RuleErrorTransformer::class),
131: new LocalIgnoresProcessor(),
132: false,
133: self::getContainer()->getByType(ValueDependencyCollector::class),
134: self::getContainer()->getByType(DependencyResolver::class),
135: );
136: $this->analyser = new Analyser(
137: $fileAnalyser,
138: $ruleRegistry,
139: $collectorRegistry,
140: $nodeScopeResolver,
141: 50,
142: );
143: }
144:
145: return $this->analyser;
146: }
147:
148: /**
149: * @param string[] $files
150: * @param list<array{0: string, 1: int, 2?: string|null}> $expectedErrors
151: */
152: public function analyse(array $files, array $expectedErrors): void
153: {
154: [$actualErrors, $delayedErrors] = $this->gatherAnalyserErrorsWithDelayedErrors($files);
155: $strictlyTypedSprintf = static function (int $line, string $message, ?string $tip): string {
156: $message = sprintf('%02d: %s', $line, $message);
157: if ($tip !== null) {
158: $message .= "\n 💡 " . $tip;
159: }
160:
161: return $message;
162: };
163:
164: usort($expectedErrors, static function ($a, $b) {
165: if ($a[1] !== $b[1]) {
166: return $a[1] <=> $b[1];
167: }
168:
169: if ($a[0] !== $b[0]) {
170: return strcmp($a[0], $b[0]);
171: }
172:
173: if (!isset($a[2])) {
174: if (!isset($b[2])) {
175: return 0;
176: }
177:
178: return 1;
179: } elseif (!isset($b[2])) {
180: return -1;
181: }
182:
183: return strcmp($a[2], $b[2]);
184: });
185:
186: $expectedErrors = array_map(
187: static fn (array $error): string => $strictlyTypedSprintf($error[1], $error[0], $error[2] ?? null),
188: $expectedErrors,
189: );
190:
191: usort($actualErrors, static function ($a, $b) {
192: if ($a->getLine() !== $b->getLine()) {
193: return $a->getLine() <=> $b->getLine();
194: }
195:
196: if ($a->getMessage() !== $b->getMessage()) {
197: return strcmp($a->getMessage(), $b->getMessage());
198: }
199:
200: if ($a->getTip() === null) {
201: if ($b->getTip() === null) {
202: return 0;
203: }
204:
205: return 1;
206: } elseif ($b->getTip() === null) {
207: return -1;
208: }
209:
210: return strcmp($a->getTip(), $b->getTip());
211: });
212:
213: $actualErrors = array_map(
214: static function (Error $error) use ($strictlyTypedSprintf): string {
215: $line = $error->getLine();
216: if ($line === null) {
217: return $strictlyTypedSprintf(-1, $error->getMessage(), $error->getTip());
218: }
219: return $strictlyTypedSprintf($line, $error->getMessage(), $error->getTip());
220: },
221: $actualErrors,
222: );
223:
224: $expectedErrorsString = implode("\n", $expectedErrors) . "\n";
225: $actualErrorsString = implode("\n", $actualErrors) . "\n";
226:
227: if (count($delayedErrors) === 0) {
228: $this->assertSame($expectedErrorsString, $actualErrorsString);
229: return;
230: }
231:
232: if ($expectedErrorsString === $actualErrorsString) {
233: $this->assertSame($expectedErrorsString, $actualErrorsString);
234: return;
235: }
236:
237: $actualErrorsString .= sprintf(
238: "\n%s might be reported because of the following misconfiguration %s:\n\n",
239: count($actualErrors) === 1 ? 'This error' : 'These errors',
240: count($delayedErrors) === 1 ? 'issue' : 'issues',
241: );
242:
243: foreach ($delayedErrors as $delayedError) {
244: $actualErrorsString .= sprintf("* %s\n", $delayedError->getMessage());
245: }
246:
247: $this->assertSame($expectedErrorsString, $actualErrorsString);
248: }
249:
250: /**
251: * Like `phpstan analyse --fix`, the fixed code is analysed again until nothing is left to fix,
252: * so fixes that overlap with other fixes and fixes of errors caused by other fixes are applied too.
253: * A fix that is fixable again fails the test, it would not finish with --fix either.
254: */
255: public function fix(string $file, string $expectedFile): void
256: {
257: $this->fixOtherFile($file, $file, $expectedFile);
258: }
259:
260: /**
261: * Analyses $file and $fixedFile together and asserts the fixes of $fixedFile,
262: * like a trait file or a file the rule points to with RuleErrorBuilder::file().
263: *
264: * Fixes in rounds like fix(). Later rounds analyse copies of the files in a temporary directory,
265: * so they do not fix traits, which are always read from their original file.
266: */
267: public function fixOtherFile(string $file, string $fixedFile, string $expectedFile): void
268: {
269: $fileHelper = $this->getFileHelper();
270: $fixedFile = $fileHelper->normalizePath($fixedFile);
271: // a trait is analysed only when its file is analysed too
272: $analysedFiles = array_values(array_unique([$fileHelper->normalizePath($file), $fixedFile]));
273: $contentsByFile = [$fixedFile => FileReader::read($fixedFile)];
274: // original path => path analysed in the current round
275: $roundPaths = array_combine($analysedFiles, $analysedFiles);
276: $patcher = self::getContainer()->getByType(Patcher::class);
277: $tmpDir = sys_get_temp_dir() . '/' . uniqid('phpstan-fix-', true);
278:
279: try {
280: for ($round = 1;; $round++) {
281: [$errors] = $this->gatherAnalyserErrorsWithDelayedErrors(array_values(array_intersect_key($roundPaths, array_flip($analysedFiles))));
282: $originalPaths = array_flip($roundPaths);
283: $diffGroups = [];
284: foreach ($errors as $error) {
285: $diffs = [];
286: foreach ($error->getFixedErrorDiffs() as $diff) {
287: // the fix of an error applies to all its files or none, all of them take part
288: $diffFile = $fileHelper->normalizePath($diff->file);
289: if ($round > 1) {
290: if (!array_key_exists($diffFile, $originalPaths)) {
291: // a trait read from its original file
292: continue 2;
293: }
294: $diffFile = $originalPaths[$diffFile];
295: }
296: $contentsByFile[$diffFile] ??= FileReader::read($diffFile);
297: $diffs[] = new FixedErrorDiff($diffFile, $diff->originalHash, $diff->diff);
298: }
299: if ($diffs === []) {
300: continue;
301: }
302:
303: $diffGroups[] = $diffs;
304: }
305:
306: if ($diffGroups === []) {
307: break;
308: }
309:
310: $patchResult = $patcher->apply($contentsByFile, $diffGroups);
311: $this->assertGreaterThan(0, $patchResult['appliedCount'], 'Some fixes overlap and could not be applied together.');
312: $this->assertLessThan(self::FIX_ROUNDS_LIMIT, $round, sprintf('Fixing did not finish after %d rounds.', $round));
313: $contentsByFile = $patchResult['contents'];
314:
315: // a new directory every round, so nothing cached for the contents of an earlier round is reused;
316: // files stay next to each other, unless their names clash
317: $roundDir = $tmpDir . '/' . $round;
318: $usedNames = [];
319: foreach ($contentsByFile as $originalPath => $contents) {
320: $name = basename($originalPath);
321: $roundPath = isset($usedNames[$name]) ? sprintf('%s/%d/%s', $roundDir, count($usedNames), $name) : $roundDir . '/' . $name;
322: $usedNames[$name] = true;
323: $roundPaths[$originalPath] = $fileHelper->normalizePath($roundPath);
324: FileSystem::write($roundPaths[$originalPath], $contents);
325: }
326: }
327: } finally {
328: FileSystem::delete($tmpDir);
329: }
330:
331: $fixedFileContents = FileReader::read($expectedFile);
332:
333: $this->assertSame($this->normalizeLineEndings($fixedFileContents), $this->normalizeLineEndings($contentsByFile[$fixedFile]));
334: }
335:
336: private function normalizeLineEndings(string $string): string
337: {
338: return str_replace("\r\n", "\n", $string);
339: }
340:
341: /**
342: * @param string[] $files
343: * @return list<Error>
344: */
345: public function gatherAnalyserErrors(array $files): array
346: {
347: return $this->gatherAnalyserErrorsWithDelayedErrors($files)[0];
348: }
349:
350: /**
351: * @param string[] $files
352: * @return array{list<Error>, list<IdentifierRuleError>}
353: */
354: private function gatherAnalyserErrorsWithDelayedErrors(array $files): array
355: {
356: $reflectionProvider = $this->createReflectionProvider();
357: $classRule = new DelayedRule(new NonexistentAnalysedClassRule($reflectionProvider));
358: $traitRule = new DelayedRule(new NonexistentAnalysedTraitRule($reflectionProvider));
359: $ruleRegistry = new DirectRuleRegistry([
360: $this->getRule(),
361: $classRule,
362: $traitRule,
363: ]);
364: $files = array_map([$this->getFileHelper(), 'normalizePath'], $files);
365: $analyserResult = $this->getAnalyser($ruleRegistry)->analyse(
366: $files,
367: null,
368: null,
369: true,
370: );
371: if (count($analyserResult->getInternalErrors()) > 0) {
372: $this->fail(implode("\n", array_map(static fn (InternalError $internalError) => $internalError->getMessage(), $analyserResult->getInternalErrors())));
373: }
374:
375: if ($this->shouldFailOnPhpErrors() && count($analyserResult->getAllPhpErrors()) > 0) {
376: $this->fail(implode("\n", array_map(
377: static fn (Error $error): string => sprintf('%s on %s:%d', $error->getMessage(), $error->getFile(), $error->getLine() ?? 0),
378: $analyserResult->getAllPhpErrors(),
379: )));
380: }
381:
382: $finalizer = new AnalyserResultFinalizer(
383: $ruleRegistry,
384: self::getContainer()->getExtensionsCollection(IgnoreErrorExtension::class),
385: self::getContainer()->getByType(RuleErrorTransformer::class),
386: self::createScopeFactory($reflectionProvider, self::getContainer()->getService('typeSpecifier')),
387: new LocalIgnoresProcessor(),
388: self::getContainer()->getByType(UnmatchedIgnoreFixer::class),
389: self::getContainer()->getByType(LineIgnoreFixer::class),
390: true,
391: self::getContainer()->getByType(ValueDependencyCollector::class),
392: false,
393: );
394:
395: return [
396: $finalizer->finalize($analyserResult, false, true)->getAnalyserResult()->getUnorderedErrors(),
397: array_merge($classRule->getDelayedErrors(), $traitRule->getDelayedErrors()),
398: ];
399: }
400:
401: /**
402: * No longer configures the analysis - set the polluteScopeWithLoopInitialAssignments
403: * parameter in a config file returned from getAdditionalConfigFiles() instead.
404: * Returning a different value than the parameter fails the test.
405: */
406: protected function shouldPolluteScopeWithLoopInitialAssignments(): bool
407: {
408: return self::getContainer()->getParameter('polluteScopeWithLoopInitialAssignments');
409: }
410:
411: /**
412: * No longer configures the analysis - set the polluteScopeWithAlwaysIterableForeach
413: * parameter in a config file returned from getAdditionalConfigFiles() instead.
414: * Returning a different value than the parameter fails the test.
415: */
416: protected function shouldPolluteScopeWithAlwaysIterableForeach(): bool
417: {
418: return self::getContainer()->getParameter('polluteScopeWithAlwaysIterableForeach');
419: }
420:
421: protected function shouldFailOnPhpErrors(): bool
422: {
423: return true;
424: }
425:
426: public static function getAdditionalConfigFiles(): array
427: {
428: return [
429: __DIR__ . '/../../conf/bleedingEdge.neon',
430: ];
431: }
432:
433: }
434: