Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions e2e/fix-partial-paths/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/tmp
56 changes: 56 additions & 0 deletions e2e/fix-partial-paths/fix-partial-paths_test.sh
Original file line number Diff line number Diff line change
@@ -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() {

Check failure on line 14 in e2e/fix-partial-paths/fix-partial-paths_test.sh

View workflow job for this annotation

GitHub Actions / Result cache E2E tests (4/4)

Fix partial paths

✗ Failed: Fix partial paths Expected 'parameters:…' to not contain 'neverReported' [-parameters:-] [- level: 0-] [- phpVersion: 80300-] [- checkMissingOverrideMethodAttribute: true-] [- paths: [src, lib]-] [- tmpDir: tmp-] [- # every entry matches in src/ or through it, except #neverReported#-] [- ignoreErrors:-] [- --] [- message: '#undefinedTwo#'-] [- --] [- message: '#undefinedWildcard#'-] [- path: src/*-] [- --] [- message: '#undefinedInTrait#'-] [- path: src/T.php-] [- --] [- identifier: method.missingOverride-] [- --] [- message: '#undefinedList#'-] [- paths: [src/B.php]-] [- # once in src/ and once in lib/-] [- --] [- message: '#undefinedCounted#'-] [- path: '*'-] [- count: 2-] [- # once through a class in src/ and once through a class in lib/-] [- --] [- message: '#undefinedCountedInTrait#'-] [- path: src/C.php-] [- count: 2-]{+neverReported+} at e2e/fix-partial-paths/fix-partial-paths_test.sh:14
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"
}
14 changes: 14 additions & 0 deletions e2e/fix-partial-paths/lib/U.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php // lib/U.php

namespace Lib;

class U extends \App\P
{
use \App\T;
use \App\C;

public function m(): void
{
undefinedCounted();
}
}
34 changes: 34 additions & 0 deletions e2e/fix-partial-paths/phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
parameters:
level: 0
phpVersion: 80300
checkMissingOverrideMethodAttribute: true
paths: [src, lib]
tmpDir: tmp
# every entry matches in src/ or through it, except #neverReported#
ignoreErrors:
-
message: '#undefinedTwo#'
-
message: '#undefinedWildcard#'
path: src/*
-
message: '#undefinedInTrait#'
path: src/T.php
-
identifier: method.missingOverride
-
message: '#undefinedList#'
paths: [src/B.php]
# once in src/ and once in lib/
-
message: '#undefinedCounted#'
path: '*'
count: 2
# matched nowhere, a full analysis removes it
-
message: '#neverReported#'
# once through a class in src/ and once through a class in lib/
-
message: '#undefinedCountedInTrait#'
path: src/C.php
count: 2
11 changes: 11 additions & 0 deletions e2e/fix-partial-paths/src/B.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php // src/B.php

namespace App;

function b(): void
{
undefinedTwo();
undefinedWildcard();
undefinedList();
undefinedCounted();
}
16 changes: 16 additions & 0 deletions e2e/fix-partial-paths/src/C.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App;

trait C
{
public function c(): void
{
undefinedCountedInTrait();
}
}

class V
{
use C;
}
17 changes: 17 additions & 0 deletions e2e/fix-partial-paths/src/P.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php // src/P.php

namespace App;

class P
{
public function m(): void
{
}
}

class A extends P
{
public function m(): void
{
}
}
11 changes: 11 additions & 0 deletions e2e/fix-partial-paths/src/T.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php // src/T.php

namespace App;

trait T
{
public function t(): void
{
undefinedInTrait();
}
}
33 changes: 32 additions & 1 deletion src/Analyser/Ignore/IgnoredErrorHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
use function array_values;
use function is_array;
use function is_file;
use function rtrim;
use function sprintf;
use function str_starts_with;
use const DIRECTORY_SEPARATOR;

/**
* @phpstan-type IgnoredErrorData = array{
Expand All @@ -34,6 +37,8 @@ final class IgnoredErrorHelper

/**
* @param (string|IgnoredErrorData)[] $ignoreErrors
* @param string[] $analysedPaths
* @param string[] $analysedPathsFromConfig
*/
public function __construct(
private FileHelper $fileHelper,
Expand All @@ -42,6 +47,10 @@ public function __construct(
private array $ignoreErrors,
#[AutowiredParameter]
private bool $reportUnmatchedIgnoredErrors,
#[AutowiredParameter]
private array $analysedPaths,
#[AutowiredParameter]
private array $analysedPathsFromConfig,
)
{
}
Expand Down Expand Up @@ -171,7 +180,29 @@ public function initialize(): IgnoredErrorHelperResult
}
}

return new IgnoredErrorHelperResult($this->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;
}

}
22 changes: 18 additions & 4 deletions src/Analyser/Ignore/IgnoredErrorHelperResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public function __construct(
private array $ignoreErrorsByFile,
private array $ignoreErrors,
private bool $reportUnmatchedIgnoredErrors,
private bool $partialAnalysis,
)
{
}
Expand Down Expand Up @@ -108,14 +109,15 @@ public function process(
// offset writes — otherwise PHPStan widens it to `array<mixed>`.
$realCounts = [];
$matchedAt = [];
$matchedInTrait = [];

// Preserve configuration order while filtering out identifier-specific
// entries that cannot match, once per distinct error identifier.
$otherIgnoreErrorsByIdentifier = [];

$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);
Expand All @@ -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;
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand Down Expand Up @@ -396,7 +410,7 @@ public function process(
continue;
}

if ($onlyFiles) {
if ($partialAnalysis) {
continue;
}

Expand All @@ -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),
Expand Down
55 changes: 55 additions & 0 deletions tests/PHPStan/Analyser/AnalyserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,55 @@
$this->assertCount(0, $result);
}

/**
* @return iterable<string, array{list<string>, list<string>, 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<string> $analysedPaths
* @param list<string> $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);

Check failure on line 98 in tests/PHPStan/Analyser/AnalyserTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

Named arguments are supported only on PHP 8.0 and later.

Check failure on line 98 in tests/PHPStan/Analyser/AnalyserTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

Named arguments are supported only on PHP 8.0 and later.
$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']);

Check failure on line 114 in tests/PHPStan/Analyser/AnalyserTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

Named arguments are supported only on PHP 8.0 and later.

Check failure on line 114 in tests/PHPStan/Analyser/AnalyserTest.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

Named arguments are supported only on PHP 8.0 and later.
$this->assertNoErrors($result);
}

public function testFileWithAnIgnoredError(): void
{
$result = $this->runAnalyser(['#Fail\.#'], true, __DIR__ . '/data/bootstrap-error.php', false);
Expand Down Expand Up @@ -851,6 +900,8 @@
* @param string|string[] $filePaths
* @param list<Collector<Node, mixed>> $collectors
* @param list<Rule<CollectedDataNode>> $collectedDataRules
* @param string[] $analysedPaths
* @param string[] $analysedPathsFromConfig
* @return string[]|Error[]
*/
private function runAnalyser(
Expand All @@ -861,6 +912,8 @@
bool $reportIgnoresWithoutComments = false,
array $collectors = [],
array $collectedDataRules = [],
array $analysedPaths = [],
array $analysedPathsFromConfig = [],
): array
{
$analyser = $this->createAnalyser($reportIgnoresWithoutComments, $collectors);
Expand All @@ -874,6 +927,8 @@
self::getContainer()->getByType(IgnoreErrorsConfigFixer::class),
$ignoreErrors,
$reportUnmatchedIgnoredErrors,
$analysedPaths,
$analysedPathsFromConfig,
);
$ignoredErrorHelperResult = $ignoredErrorHelper->initialize();
if (count($ignoredErrorHelperResult->getErrors()) > 0) {
Expand Down
Loading
Loading