Skip to content

Introduce IgnoreErrorExtension #3783

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Feb 21, 2025
Merged
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
4 changes: 4 additions & 0 deletions .github/workflows/e2e-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ jobs:
cd e2e/bug-12606
export CONFIGTEST=test
../../bin/phpstan
- script: |
cd e2e/ignore-error-extension
composer install
../../bin/phpstan
steps:
- name: "Checkout"
Expand Down
3 changes: 3 additions & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,9 @@ services:
arguments:
parser: @defaultAnalysisParser

-
class: PHPStan\Analyser\IgnoreErrorExtensionProvider

-
class: PHPStan\Analyser\LocalIgnoresProcessor

Expand Down
2 changes: 2 additions & 0 deletions e2e/ignore-error-extension/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/vendor
/composer.lock
7 changes: 7 additions & 0 deletions e2e/ignore-error-extension/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
44 changes: 44 additions & 0 deletions e2e/ignore-error-extension/phpstan-baseline.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
parameters:
ignoreErrors:
-
message: '#^This is an error from a rule that uses a collector$#'
identifier: class.name
count: 1
path: src/ClassCollector.php

-
message: '#^This is an error from a rule that uses a collector$#'
identifier: class.name
count: 1
path: src/ClassRule.php

-
message: '#^This is an error from a rule that uses a collector$#'
identifier: class.name
count: 1
path: src/ControllerActionReturnTypeIgnoreExtension.php

-
message: '#^This is an error from a rule that uses a collector$#'
identifier: class.name
count: 1
path: src/ControllerClassNameIgnoreExtension.php

-
message: '#^Method App\\HomepageController\:\:contactAction\(\) has parameter \$someUnrelatedError with no type specified\.$#'
identifier: missingType.parameter
count: 1
path: src/HomepageController.php

-
message: '#^Method App\\HomepageController\:\:getSomething\(\) return type has no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
count: 1
path: src/HomepageController.php

-
message: '#^Method App\\HomepageController\:\:homeAction\(\) has parameter \$someUnrelatedError with no type specified\.$#'
identifier: missingType.parameter
count: 1
path: src/HomepageController.php

25 changes: 25 additions & 0 deletions e2e/ignore-error-extension/phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
includes:
- phpstan-baseline.neon

parameters:
level: 9
paths:
- src

services:
-
class: App\ClassCollector
tags:
- phpstan.collector
-
class: App\ClassRule
tags:
- phpstan.rules.rule
-
class: App\ControllerActionReturnTypeIgnoreExtension
tags:
- phpstan.ignoreErrorExtension
-
class: App\ControllerClassNameIgnoreExtension
tags:
- phpstan.ignoreErrorExtension
29 changes: 29 additions & 0 deletions e2e/ignore-error-extension/src/ClassCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types = 1);

namespace App;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Collectors\Collector;

/**
* @implements Collector<Node\Stmt\Class_, array{string, int}>
*/
final class ClassCollector implements Collector
{
public function getNodeType(): string
{
return Node\Stmt\Class_::class;
}

public function processNode(Node $node, Scope $scope) : ?array
{
if ($node->name === null) {
return null;
}

return [$node->name->name, $node->getStartLine()];
}
}
43 changes: 43 additions & 0 deletions e2e/ignore-error-extension/src/ClassRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace App;

use Override;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\CollectedDataNode;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
* @implements Rule<CollectedDataNode>
*/
final class ClassRule implements Rule
{
#[Override]
public function getNodeType() : string
{
return CollectedDataNode::class;
}

#[Override]
public function processNode(Node $node, Scope $scope) : array
{
$errors = [];

foreach ($node->get(ClassCollector::class) as $file => $data) {
foreach ($data as [$className, $line]) {
$errors[] = RuleErrorBuilder::message('This is an error from a rule that uses a collector')
->file($file)
->line($line)
->identifier('class.name')
->build();
}
}

return $errors;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace App;

use PhpParser\Node;
use PHPStan\Analyser\Error;
use PHPStan\Analyser\IgnoreErrorExtension;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassMethodNode;

// This extension will ignore "missingType.iterableValue" errors for public Action methods inside Controller classes.
final class ControllerActionReturnTypeIgnoreExtension implements IgnoreErrorExtension
{
public function shouldIgnore(Error $error, Node $node, Scope $scope) : bool
{
if ($error->getIdentifier() !== 'missingType.iterableValue') {
return false;
}

// @phpstan-ignore phpstanApi.instanceofAssumption
if (! $node instanceof InClassMethodNode) {
return false;
}

if (! str_ends_with($node->getClassReflection()->getName(), 'Controller')) {
return false;
}

if (! str_ends_with($node->getMethodReflection()->getName(), 'Action')) {
return false;
}

if (! $node->getMethodReflection()->isPublic()) {
return false;
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App;

use PhpParser\Node;
use PHPStan\Analyser\Error;
use PHPStan\Analyser\IgnoreErrorExtension;
use PHPStan\Analyser\Scope;
use PHPStan\Node\CollectedDataNode;

// This extension will ignore "class.name" errors for classes with names ending with "Controller".
// These errors are reported by the ClassRule which triggers on CollectedDataNode coming from ClassCollector.
final class ControllerClassNameIgnoreExtension implements IgnoreErrorExtension
{
public function shouldIgnore(Error $error, Node $node, Scope $scope) : bool
{
if ($error->getIdentifier() !== 'class.name') {
return false;
}

// @phpstan-ignore phpstanApi.instanceofAssumption
if (!$node instanceof CollectedDataNode) {
return false;
}

if (!str_ends_with($error->getFile(), 'Controller.php')) {
return false;
}

return true;
}
}
29 changes: 29 additions & 0 deletions e2e/ignore-error-extension/src/HomepageController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace App;

final class HomepageController
{
public function homeAction($someUnrelatedError = false): array
{
return [
'title' => 'Homepage',
'something' => $this->getSomething(),
];
}

public function contactAction($someUnrelatedError): array
{
return [
'title' => 'Contact',
'something' => $this->getSomething(),
];
}

private function getSomething(): array
{
return [];
}
}
13 changes: 12 additions & 1 deletion src/Analyser/AnalyserResultFinalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ final class AnalyserResultFinalizer

public function __construct(
private RuleRegistry $ruleRegistry,
private IgnoreErrorExtensionProvider $ignoreErrorExtensionProvider,
private RuleErrorTransformer $ruleErrorTransformer,
private ScopeFactory $scopeFactory,
private LocalIgnoresProcessor $localIgnoresProcessor,
Expand Down Expand Up @@ -88,7 +89,17 @@ public function finalize(AnalyserResult $analyserResult, bool $onlyFiles, bool $
}

foreach ($ruleErrors as $ruleError) {
$tempCollectorErrors[] = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getStartLine());
$error = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getStartLine());

if ($error->canBeIgnored()) {
foreach ($this->ignoreErrorExtensionProvider->getExtensions() as $ignoreErrorExtension) {
if ($ignoreErrorExtension->shouldIgnore($error, $node, $scope)) {
continue 2;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if I comment this change, all tests are passing. Please add a collector + CollectedDataNode rule with an error to the E2E test, and ignore it with an extension, so we can verify this code does what it should.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I added the tests. While doing it, I wonder, what the value of this would be. Since the Node points to the CollectedDataNode, that contains all data.

I think in real world scenario's, this is not interesting, but maybe I don't see it yet.

}
}
}

$tempCollectorErrors[] = $error;
}
}

Expand Down
13 changes: 12 additions & 1 deletion src/Analyser/FileAnalyser.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function __construct(
private NodeScopeResolver $nodeScopeResolver,
private Parser $parser,
private DependencyResolver $dependencyResolver,
private IgnoreErrorExtensionProvider $ignoreErrorExtensionProvider,
private RuleErrorTransformer $ruleErrorTransformer,
private LocalIgnoresProcessor $localIgnoresProcessor,
)
Expand Down Expand Up @@ -142,7 +143,17 @@ public function analyseFile(
}

foreach ($ruleErrors as $ruleError) {
$temporaryFileErrors[] = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getStartLine());
$error = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getStartLine());

if ($error->canBeIgnored()) {
foreach ($this->ignoreErrorExtensionProvider->getExtensions() as $ignoreErrorExtension) {
if ($ignoreErrorExtension->shouldIgnore($error, $node, $scope)) {
continue 2;
}
}
}

$temporaryFileErrors[] = $error;
}
}

Expand Down
32 changes: 32 additions & 0 deletions src/Analyser/IgnoreErrorExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace PHPStan\Analyser;

use PhpParser\Node;

/**
* This is the extension interface to implement if you want to ignore errors
* based on the node and scope.
*
* To register it in the configuration file use the `phpstan.ignoreErrorExtension` service tag:
*
* ```
* services:
* -
* class: App\PHPStan\MyExtension
* tags:
* - phpstan.ignoreErrorExtension
* ```
*
* Learn more: https://phpstan.org
*
* @api
*/
interface IgnoreErrorExtension
{

public const EXTENSION_TAG = 'phpstan.ignoreErrorExtension';

public function shouldIgnore(Error $error, Node $node, Scope $scope): bool;

}
22 changes: 22 additions & 0 deletions src/Analyser/IgnoreErrorExtensionProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php declare(strict_types = 1);

namespace PHPStan\Analyser;

use PHPStan\DependencyInjection\Container;

final class IgnoreErrorExtensionProvider
{

public function __construct(private Container $container)
{
}

/**
* @return IgnoreErrorExtension[]
*/
public function getExtensions(): array
{
return $this->container->getServicesByTag(IgnoreErrorExtension::EXTENSION_TAG);
}

}
Loading
Loading