diff --git a/e2e/fix-partial-paths/.gitignore b/e2e/fix-partial-paths/.gitignore new file mode 100644 index 00000000000..ceeb05b4108 --- /dev/null +++ b/e2e/fix-partial-paths/.gitignore @@ -0,0 +1 @@ +/tmp diff --git a/e2e/fix-partial-paths/fix-partial-paths_test.sh b/e2e/fix-partial-paths/fix-partial-paths_test.sh new file mode 100644 index 00000000000..846bbe5230f --- /dev/null +++ b/e2e/fix-partial-paths/fix-partial-paths_test.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# @tags result-cache + +function set_up() { + e2e::set_up +} + +function tear_down() { + e2e::tear_down +} + +# paths: [src, lib] - analysing only one of them must not report or fix away +# the ignoreErrors entries that the other one still needs +function test_fix_partial_paths() { + rm -rf tmp && cp phpstan.neon phpstan-original.neon + + OUTPUT=$(AI_AGENT=1 ../../bin/phpstan analyse lib --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same "0" "$CODE" + assert_not_contains 'Ignored error' "$OUTPUT" + + OUTPUT=$(AI_AGENT=1 ../../bin/phpstan analyse src --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same "0" "$CODE" + assert_not_contains 'Ignored error' "$OUTPUT" + + for paths in lib src; do + OUTPUT=$(../../bin/phpstan analyse $paths --fix 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_contains 'No fixable errors found' "$OUTPUT" + diff -u phpstan-original.neon phpstan.neon + done + + OUTPUT=$(cd lib && ../../../bin/phpstan analyse . -c ../phpstan.neon --fix 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_contains 'No fixable errors found' "$OUTPUT" + diff -u phpstan-original.neon phpstan.neon + + # the ignored method.missingOverride is fixed in lib/, the entry stays for src/ + OUTPUT=$(../../bin/phpstan analyse lib --fix --fix-ignored 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same "0" "$CODE" + assert_contains '[OK] 1 error fixed in 1 file' "$OUTPUT" + assert_contains '#[\Override]' "$(cat lib/U.php)" + diff -u phpstan-original.neon phpstan.neon + + # a full analysis still removes the entry no path needs + OUTPUT=$(../../bin/phpstan analyse --fix 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same "0" "$CODE" + assert_contains '[OK] 1 error fixed in 1 file' "$OUTPUT" + assert_not_contains 'neverReported' "$(cat phpstan.neon)" + OUTPUT=$(AI_AGENT=1 ../../bin/phpstan analyse --error-format raw 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" + assert_same "0" "$CODE" +} diff --git a/e2e/fix-partial-paths/lib/U.php b/e2e/fix-partial-paths/lib/U.php new file mode 100644 index 00000000000..6e0cd6a788b --- /dev/null +++ b/e2e/fix-partial-paths/lib/U.php @@ -0,0 +1,14 @@ +fileHelper, $this->configFixer, $errors, $otherIgnoreErrors, $ignoreErrorsByFile, $expandedIgnoreErrors, $this->reportUnmatchedIgnoredErrors); + return new IgnoredErrorHelperResult($this->fileHelper, $this->configFixer, $errors, $otherIgnoreErrors, $ignoreErrorsByFile, $expandedIgnoreErrors, $this->reportUnmatchedIgnoredErrors, $this->isPartialAnalysis()); + } + + /** + * Whether the analysed paths leave out some of the configured `paths`, like `analyse lib` + * with `paths: [src, lib]`. Errors in what is left out are not reported, so the entries + * that may match them cannot be told unmatched. + */ + private function isPartialAnalysis(): bool + { + foreach ($this->analysedPathsFromConfig as $pathFromConfig) { + $pathFromConfig = $this->fileHelper->normalizePath($pathFromConfig); + foreach ($this->analysedPaths as $analysedPath) { + $analysedPath = $this->fileHelper->normalizePath($analysedPath); + if ($pathFromConfig === $analysedPath || str_starts_with($pathFromConfig, rtrim($analysedPath, '/\\') . DIRECTORY_SEPARATOR)) { + continue 2; + } + } + + return true; + } + + return false; } } diff --git a/src/Analyser/Ignore/IgnoredErrorHelperResult.php b/src/Analyser/Ignore/IgnoredErrorHelperResult.php index f1bed8885d9..e600f31b508 100644 --- a/src/Analyser/Ignore/IgnoredErrorHelperResult.php +++ b/src/Analyser/Ignore/IgnoredErrorHelperResult.php @@ -57,6 +57,7 @@ public function __construct( private array $ignoreErrorsByFile, private array $ignoreErrors, private bool $reportUnmatchedIgnoredErrors, + private bool $partialAnalysis, ) { } @@ -108,6 +109,7 @@ public function process( // offset writes — otherwise PHPStan widens it to `array`. $realCounts = []; $matchedAt = []; + $matchedInTrait = []; // Preserve configuration order while filtering out identifier-specific // entries that cannot match, once per distinct error identifier. @@ -115,7 +117,7 @@ public function process( $ignoreErrorsByFileAndIdentifier = []; - $processIgnoreError = function (Error $error, int $i, $ignore) use (&$unmatchedIgnoredErrors, &$stringErrors, &$realCounts, &$matchedAt): bool { + $processIgnoreError = function (Error $error, int $i, $ignore) use (&$unmatchedIgnoredErrors, &$stringErrors, &$realCounts, &$matchedAt, &$matchedInTrait): bool { $shouldBeIgnored = false; if (is_string($ignore)) { $shouldBeIgnored = IgnoredError::shouldIgnore($this->fileHelper, $error, ignoredErrorPattern: $ignore, ignoredErrorMessage: null, identifier: null, path: null); @@ -133,6 +135,9 @@ public function process( if (!isset($matchedAt[$i])) { $matchedAt[$i] = ['file' => $error->getFile(), 'line' => $error->getLine()]; } + if ($error->getTraitFilePath() !== null) { + $matchedInTrait[$i] = true; + } if ($realCount > $ignore['count']) { $shouldBeIgnored = false; @@ -356,6 +361,10 @@ public function process( $analysedFilesKeys = array_fill_keys($analysedFiles, true); + // on a list of files or on part of the configured paths, the errors outside them are not reported, + // and neither are the errors of a trait used by a class outside them + $partialAnalysis = $onlyFiles || $this->partialAnalysis; + if (!$hasInternalErrors) { foreach ($unmatchedIgnoredErrors as $i => $unmatchedIgnoredError) { $reportUnmatched = is_array($unmatchedIgnoredError) @@ -368,7 +377,12 @@ public function process( if ( isset($unmatchedIgnoredError['count']) && $realCount !== null - && (isset($unmatchedIgnoredError['realPath']) || !$onlyFiles) + && ( + !$partialAnalysis + // a partial analysis reports all errors of an analysed file, but not those of a trait in it + // that a class outside the analysed files uses + || (isset($unmatchedIgnoredError['realPath']) && !isset($matchedInTrait[$i])) + ) ) { if ($realCount < $unmatchedIgnoredError['count']) { $matchedFile = $matchedAt[$i]['file'] ?? null; @@ -396,7 +410,7 @@ public function process( continue; } - if ($onlyFiles) { + if ($partialAnalysis) { continue; } @@ -411,7 +425,7 @@ public function process( identifier: 'ignore.unmatched', fixedErrorDiffs: $this->configFixer->removeUnmatched($unmatchedIgnoredError), ); - } elseif (!$onlyFiles) { + } elseif (!$partialAnalysis) { $message = sprintf( '%s %s was not matched in reported errors.', IgnoredError::getIgnoredErrorLabel($unmatchedIgnoredError), diff --git a/tests/PHPStan/Analyser/AnalyserTest.php b/tests/PHPStan/Analyser/AnalyserTest.php index 3a800ea97a0..1f6dc5bc0e2 100644 --- a/tests/PHPStan/Analyser/AnalyserTest.php +++ b/tests/PHPStan/Analyser/AnalyserTest.php @@ -66,6 +66,55 @@ public function testDoNotReturnErrorIfIgnoredMessagesDoNotOccurWhileAnalysingInd $this->assertCount(0, $result); } + /** + * @return iterable, list, bool}> + */ + public static function dataReportUnmatchedIgnoredErrorsByAnalysedPaths(): iterable + { + $dir = __DIR__ . '/data/empty'; + + yield 'the configured paths' => [[$dir], [$dir], true]; + yield 'a parent of the configured paths' => [[__DIR__ . '/data'], [$dir], true]; + yield 'without configured paths' => [[$dir], [], true]; + yield 'part of the configured paths' => [[$dir], [$dir, __DIR__ . '/data/other'], false]; + yield 'a directory inside the configured paths' => [[$dir], [__DIR__ . '/data'], false]; + yield 'a sibling with the same prefix as the configured paths' => [[$dir], [$dir . '-other'], false]; + } + + /** + * @param list $analysedPaths + * @param list $analysedPathsFromConfig + */ + #[DataProvider('dataReportUnmatchedIgnoredErrorsByAnalysedPaths')] + public function testReportUnmatchedIgnoredErrorsByAnalysedPaths(array $analysedPaths, array $analysedPathsFromConfig, bool $expectReported): void + { + $ignoreErrors = [ + '#Unknown error#', + [ + 'message' => '#Unknown error in a path pattern#', + 'path' => __DIR__ . '/data/*', + ], + ]; + $result = $this->runAnalyser($ignoreErrors, true, __DIR__ . '/data/empty/empty.php', false, analysedPaths: $analysedPaths, analysedPathsFromConfig: $analysedPathsFromConfig); + $this->assertSame($expectReported ? [ + 'Ignored error pattern #Unknown error# was not matched in reported errors.', + 'Ignored error pattern #Unknown error in a path pattern# in path ' . __DIR__ . '/data/* was not matched in reported errors.', + ] : [], $result); + } + + public function testDoNotReportTooHighCountOfIgnoredErrorsFromTraitOnPartialAnalysis(): void + { + $ignoreErrors = [ + [ + 'message' => '#Fail\.#', + 'path' => __DIR__ . '/data/partial-analysis-trait.php', + 'count' => 2, + ], + ]; + $result = $this->runAnalyser($ignoreErrors, true, [__DIR__ . '/data/partial-analysis-trait.php'], false, analysedPaths: [__DIR__ . '/data'], analysedPathsFromConfig: [__DIR__ . '/data', __DIR__ . '/other']); + $this->assertNoErrors($result); + } + public function testFileWithAnIgnoredError(): void { $result = $this->runAnalyser(['#Fail\.#'], true, __DIR__ . '/data/bootstrap-error.php', false); @@ -851,6 +900,8 @@ public function testIgnoreErrorExplicitReportUnmatchedEnableMulti(): void * @param string|string[] $filePaths * @param list> $collectors * @param list> $collectedDataRules + * @param string[] $analysedPaths + * @param string[] $analysedPathsFromConfig * @return string[]|Error[] */ private function runAnalyser( @@ -861,6 +912,8 @@ private function runAnalyser( bool $reportIgnoresWithoutComments = false, array $collectors = [], array $collectedDataRules = [], + array $analysedPaths = [], + array $analysedPathsFromConfig = [], ): array { $analyser = $this->createAnalyser($reportIgnoresWithoutComments, $collectors); @@ -874,6 +927,8 @@ private function runAnalyser( self::getContainer()->getByType(IgnoreErrorsConfigFixer::class), $ignoreErrors, $reportUnmatchedIgnoredErrors, + $analysedPaths, + $analysedPathsFromConfig, ); $ignoredErrorHelperResult = $ignoredErrorHelper->initialize(); if (count($ignoredErrorHelperResult->getErrors()) > 0) { diff --git a/tests/PHPStan/Analyser/data/partial-analysis-trait.php b/tests/PHPStan/Analyser/data/partial-analysis-trait.php new file mode 100644 index 00000000000..a6730001d0f --- /dev/null +++ b/tests/PHPStan/Analyser/data/partial-analysis-trait.php @@ -0,0 +1,21 @@ +