\PHPStan\Rules\Rule
interface.getNodeType()
: Specifies the type of node to analyze (e.g., method calls, new instances).processNode()
: Contains logic for identifying and reporting errors.The goal is to enhance knowledge sharing by integrating company-specific standards and solutions directly into the codebase using PHPStan custom rules. This helps bridge the gap between documentation and practice, ensuring that crucial conventions and lessons are not forgotten during development.
Why Use PHPStan for Knowledge Sharing?
Traditional documentation requires developers to actively search for information, which may be overlooked or forgotten. PHPStan custom rules embed this knowledge directly into the development process by providing real-time feedback during static code analysis.
When adding a new PHPStan custom rule, it’s essential to prevent errors from legacy code from being flagged. This is where the baseline feature of PHPStan comes into play.
What is a Baseline?
A baseline is a snapshot of all errors currently present in your codebase. PHPStan uses this to ignore existing issues while still detecting new ones in updated or added code. This allows teams to adopt stricter rules without immediately needing to fix historical errors, making the transition smoother.
Steps to Add a Rule Without Affecting Legacy Code
run-stan-reset-baseline
defined in the project’s composer.json
file.By maintaining and updating the baseline, you can progressively enforce new standards without overwhelming the team with legacy issues. This approach allows for continuous improvement in code quality while keeping development workflows manageable.
Steps to Create a Custom Rule
\PHPStan\Rules\Rule
and bind the rule to a specific node type.RuleErrorBuilder::message()
to define error messages.Example: A rule to disallow var_dump()
:
public function processNode(Node $node, Scope $scope): array {
if ($node->name->toString() === 'var_dump') {
return [RuleErrorBuilder::message('var_dump is not allowed')->build()];
}
return [];
}
PHPStan\Testing\RuleTestCase
and implement getRule()
to return the custom rule instance.var_dump()
in a test file and confirm error reporting.phpstan analyse
to validate the implementation.For more detailed examples, refer to the sample implementations in PHPStan’s documentation on rules.
apply_filters
in favour of wpm_apply_filters_typed
update_option
in favour of Option
object, with the set()
method.get_subscribed_events
from a Subscriber
is a method that exists.