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 || $expectedErrorsString === $actualErrorsString) {
228: $this->assertSame($expectedErrorsString, $actualErrorsString);
229: return;
230: }
231:
232: $actualErrorsString .= sprintf(
233: "\n%s might be reported because of the following misconfiguration %s:\n\n",
234: count($actualErrors) === 1 ? 'This error' : 'These errors',
235: count($delayedErrors) === 1 ? 'issue' : 'issues',
236: );
237:
238: foreach ($delayedErrors as $delayedError) {
239: $actualErrorsString .= sprintf("* %s\n", $delayedError->getMessage());
240: }
241:
242: $this->assertSame($expectedErrorsString, $actualErrorsString);
243: }
244:
245: /**
246: * Like `phpstan analyse --fix`, the fixed code is analysed again until nothing is left to fix,
247: * so fixes that overlap with other fixes and fixes of errors caused by other fixes are applied too.
248: * A fix that is fixable again fails the test, it would not finish with --fix either.
249: */
250: public function fix(string $file, string $expectedFile): void
251: {
252: $this->fixOtherFile($file, $file, $expectedFile);
253: }
254:
255: /**
256: * Analyses $file and $fixedFile together and asserts the fixes of $fixedFile,
257: * like a trait file or a file the rule points to with RuleErrorBuilder::file().
258: *
259: * Fixes in rounds like fix(). Later rounds analyse copies of the files in a temporary directory,
260: * so they do not fix traits, which are always read from their original file.
261: */
262: public function fixOtherFile(string $file, string $fixedFile, string $expectedFile): void
263: {
264: $fileHelper = $this->getFileHelper();
265: $fixedFile = $fileHelper->normalizePath($fixedFile);
266: // a trait is analysed only when its file is analysed too
267: $analysedFiles = array_values(array_unique([$fileHelper->normalizePath($file), $fixedFile]));
268: $contentsByFile = [$fixedFile => FileReader::read($fixedFile)];
269: // original path => path analysed in the current round
270: $roundPaths = array_combine($analysedFiles, $analysedFiles);
271: $patcher = self::getContainer()->getByType(Patcher::class);
272: $tmpDir = sys_get_temp_dir() . '/' . uniqid('phpstan-fix-', true);
273:
274: try {
275: for ($round = 1;; $round++) {
276: [$errors] = $this->gatherAnalyserErrorsWithDelayedErrors(array_values(array_intersect_key($roundPaths, array_flip($analysedFiles))));
277: $originalPaths = array_flip($roundPaths);
278: $diffGroups = [];
279: foreach ($errors as $error) {
280: $diffs = [];
281: foreach ($error->getFixedErrorDiffs() as $diff) {
282: // the fix of an error applies to all its files or none, all of them take part
283: $diffFile = $fileHelper->normalizePath($diff->file);
284: if ($round > 1) {
285: if (!array_key_exists($diffFile, $originalPaths)) {
286: // a trait read from its original file
287: continue 2;
288: }
289: $diffFile = $originalPaths[$diffFile];
290: }
291: $contentsByFile[$diffFile] ??= FileReader::read($diffFile);
292: $diffs[] = new FixedErrorDiff($diffFile, $diff->originalHash, $diff->diff);
293: }
294: if ($diffs === []) {
295: continue;
296: }
297:
298: $diffGroups[] = $diffs;
299: }
300:
301: if ($diffGroups === []) {
302: break;
303: }
304:
305: $patchResult = $patcher->apply($contentsByFile, $diffGroups);
306: $this->assertGreaterThan(0, $patchResult['appliedCount'], 'Some fixes overlap and could not be applied together.');
307: $this->assertLessThan(self::FIX_ROUNDS_LIMIT, $round, sprintf('Fixing did not finish after %d rounds.', $round));
308: $contentsByFile = $patchResult['contents'];
309:
310: // a new directory every round, so nothing cached for the contents of an earlier round is reused;
311: // files stay next to each other, unless their names clash
312: $roundDir = $tmpDir . '/' . $round;
313: $usedNames = [];
314: foreach ($contentsByFile as $originalPath => $contents) {
315: $name = basename($originalPath);
316: $roundPath = isset($usedNames[$name]) ? sprintf('%s/%d/%s', $roundDir, count($usedNames), $name) : $roundDir . '/' . $name;
317: $usedNames[$name] = true;
318: $roundPaths[$originalPath] = $fileHelper->normalizePath($roundPath);
319: FileSystem::write($roundPaths[$originalPath], $contents);
320: }
321: }
322: } finally {
323: FileSystem::delete($tmpDir);
324: }
325:
326: $fixedFileContents = FileReader::read($expectedFile);
327:
328: $this->assertSame($this->normalizeLineEndings($fixedFileContents), $this->normalizeLineEndings($contentsByFile[$fixedFile]));
329: }
330:
331: private function normalizeLineEndings(string $string): string
332: {
333: return str_replace("\r\n", "\n", $string);
334: }
335:
336: /**
337: * @param string[] $files
338: * @return list<Error>
339: */
340: public function gatherAnalyserErrors(array $files): array
341: {
342: return $this->gatherAnalyserErrorsWithDelayedErrors($files)[0];
343: }
344:
345: /**
346: * @param string[] $files
347: * @return array{list<Error>, list<IdentifierRuleError>}
348: */
349: private function gatherAnalyserErrorsWithDelayedErrors(array $files): array
350: {
351: $reflectionProvider = $this->createReflectionProvider();
352: $classRule = new DelayedRule(new NonexistentAnalysedClassRule($reflectionProvider));
353: $traitRule = new DelayedRule(new NonexistentAnalysedTraitRule($reflectionProvider));
354: $ruleRegistry = new DirectRuleRegistry([
355: $this->getRule(),
356: $classRule,
357: $traitRule,
358: ]);
359: $files = array_map([$this->getFileHelper(), 'normalizePath'], $files);
360: $analyserResult = $this->getAnalyser($ruleRegistry)->analyse(
361: $files,
362: null,
363: null,
364: true,
365: );
366: if (count($analyserResult->getInternalErrors()) > 0) {
367: $this->fail(implode("\n", array_map(static fn (InternalError $internalError) => $internalError->getMessage(), $analyserResult->getInternalErrors())));
368: }
369:
370: if ($this->shouldFailOnPhpErrors() && count($analyserResult->getAllPhpErrors()) > 0) {
371: $this->fail(implode("\n", array_map(
372: static fn (Error $error): string => sprintf('%s on %s:%d', $error->getMessage(), $error->getFile(), $error->getLine() ?? 0),
373: $analyserResult->getAllPhpErrors(),
374: )));
375: }
376:
377: $finalizer = new AnalyserResultFinalizer(
378: $ruleRegistry,
379: self::getContainer()->getExtensionsCollection(IgnoreErrorExtension::class),
380: self::getContainer()->getByType(RuleErrorTransformer::class),
381: self::createScopeFactory($reflectionProvider, self::getContainer()->getService('typeSpecifier')),
382: new LocalIgnoresProcessor(),
383: self::getContainer()->getByType(UnmatchedIgnoreFixer::class),
384: self::getContainer()->getByType(LineIgnoreFixer::class),
385: true,
386: self::getContainer()->getByType(ValueDependencyCollector::class),
387: false,
388: );
389:
390: return [
391: $finalizer->finalize($analyserResult, false, true)->getAnalyserResult()->getUnorderedErrors(),
392: array_merge($classRule->getDelayedErrors(), $traitRule->getDelayedErrors()),
393: ];
394: }
395:
396: /**
397: * No longer configures the analysis - set the polluteScopeWithLoopInitialAssignments
398: * parameter in a config file returned from getAdditionalConfigFiles() instead.
399: * Returning a different value than the parameter fails the test.
400: */
401: protected function shouldPolluteScopeWithLoopInitialAssignments(): bool
402: {
403: return self::getContainer()->getParameter('polluteScopeWithLoopInitialAssignments');
404: }
405:
406: /**
407: * No longer configures the analysis - set the polluteScopeWithAlwaysIterableForeach
408: * parameter in a config file returned from getAdditionalConfigFiles() instead.
409: * Returning a different value than the parameter fails the test.
410: */
411: protected function shouldPolluteScopeWithAlwaysIterableForeach(): bool
412: {
413: return self::getContainer()->getParameter('polluteScopeWithAlwaysIterableForeach');
414: }
415:
416: protected function shouldFailOnPhpErrors(): bool
417: {
418: return true;
419: }
420:
421: public static function getAdditionalConfigFiles(): array
422: {
423: return [
424: __DIR__ . '/../../conf/bleedingEdge.neon',
425: ];
426: }
427:
428: }
429: