korbeil/phpstan-generic-rules
PHPStan extension that enforces and improves the use of PHP generics. Adds custom rules to catch missing or incorrect template types, invalid generic usages, and helps keep docblocks and type hints consistent for safer, more accurate static analysis.
Installation Add the package via Composer:
composer require --dev korbeil/phpstan-generic-rules
Ensure phpstan is installed and configured in your project.
Basic Configuration
Extend your phpstan.neon to include the rules:
includes:
- vendor/korbeil/phpstan-generic-rules/extension.neon
First Use Case Run PHPStan with the new rules:
vendor/bin/phpstan analyse src
Focus on catching generic type-related issues (e.g., array vs list, mixed misuse).
Strict Typing Enforcement
Use rules like Generic\Type\ArrayShapeRule to enforce strict array shapes:
// phpstan.neon
services:
PhpStan\Rules\Generic\Type\ArrayShapeRule:
parameters:
allowedTypes: ['string', 'int']
Generic Type Validation
Validate generic classes (e.g., Collection<T>) with Generic\Type\GenericClassRule:
// Example: Enforce Collection<string>
$collection = new Collection(['a', 'b']); // Valid
$collection = new Collection([1, 2]); // Fails (int not allowed)
Integration with Custom Rules
Combine with existing PHPStan rules (e.g., NoUnusedImportsRule) for layered validation.
level: 5 in phpstan.neon and gradually enable stricter rules.phpstan.neon for project-specific needs (e.g., allowed mixed types).Performance Overhead
Generic rules add analysis time. Run in CI with --memory-limit=1G if needed.
False Positives
Generic\Type\MixedTypeRule may flag legitimate mixed usage (e.g., dynamic APIs).Neon Configuration Conflicts
Ensure includes in phpstan.neon don’t duplicate or override rules unintentionally.
extension.neon.--error-format=github for actionable feedback.Custom Rules
Extend korbeil/phpstan-generic-rules by creating a child rule class (e.g., CustomGenericRule).
Example:
use PhpStan\Rules\Generic\GenericRule;
class CustomGenericRule extends GenericRule {
public function getNodeType(): string { return 'PhpStan\Node\GenericNode'; }
// ...
}
Parameter Tuning
Adjust rule parameters dynamically via environment variables (e.g., ALLOWED_GENERIC_TYPES).
Plugin Integration
Pair with phpstan/phpstan-doctrine for ORM-specific generic type checks.
How can I help you explore Laravel packages today?