Skip to content

Commit

Permalink
Internal PHPStan rule - class must be abstract or final
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jul 29, 2024
1 parent 5baa146 commit d631120
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
64 changes: 64 additions & 0 deletions build/PHPStan/Build/FinalClassRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php declare(strict_types = 1);

namespace PHPStan\Build;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassNode;
use PHPStan\Reflection\FunctionVariant;
use PHPStan\Reflection\FunctionVariantWithPhpDocs;
use PHPStan\Reflection\Php\DummyParameter;
use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Type;
use function in_array;
use function sprintf;

/**
* @implements Rule<InClassNode>
*/
final class FinalClassRule implements Rule
{

public function getNodeType(): string
{
return InClassNode::class;
}

public function processNode(Node $node, Scope $scope): array
{
$classReflection = $node->getClassReflection();
if (!$classReflection->isClass()) {
return [];
}
if ($classReflection->isAbstract()) {
return [];
}
if ($classReflection->isFinal()) {
return [];
}
if ($classReflection->isSubclassOf(Type::class)) {
return [];
}

// exceptions
if (in_array($classReflection->getName(), [
FunctionVariant::class,
FunctionVariantWithPhpDocs::class,
DummyParameter::class,
PhpFunctionFromParserNodeReflection::class,
], true)) {
return [];
}

return [
RuleErrorBuilder::message(
sprintf('Class %s must be abstract or final.', $classReflection->getDisplayName()),
)
->identifier('phpstan.finalClass')
->build(),
];
}

}
4 changes: 4 additions & 0 deletions build/phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ includes:
- ../phpstan-baseline.php
- ignore-by-php-version.neon.php
- ignore-by-architecture.neon.php

parameters:
level: 8
paths:
Expand Down Expand Up @@ -98,6 +99,9 @@ parameters:
- stubs/NetteDIContainer.stub
- stubs/PhpParserName.stub

rules:
- PHPStan\Build\FinalClassRule

services:
-
class: PHPStan\Build\ServiceLocatorDynamicReturnTypeExtension
Expand Down

0 comments on commit d631120

Please sign in to comment.