Skip to content
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
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ lint:
--exclude tests/PHPStan/Rules/Constants/data/class-as-class-constant.php \
--exclude tests/PHPStan/Rules/Constants/data/value-assigned-to-class-constant-native-type.php \
--exclude tests/PHPStan/Rules/Constants/data/overriding-constant-native-types.php \
--exclude tests/PHPStan/Rules/Constants/data/constant-override-attr.php \
--exclude tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php \
--exclude tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php.fixed \
--exclude tests/PHPStan/Rules/Methods/data/bug-10043.php \
--exclude tests/PHPStan/Rules/Methods/data/bug-7859.php \
--exclude tests/PHPStan/Rules/Methods/data/bug-8081.php \
Expand Down Expand Up @@ -140,6 +143,9 @@ lint:
--exclude tests/PHPStan/Rules/Classes/data/bug-14250-promoted-properties.php \
--exclude tests/PHPStan/Rules/Operators/data/bug-3585.php \
--exclude tests/PHPStan/Rules/EnumCases/data/bug-14252.php \
--exclude tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr.php \
--exclude tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php \
--exclude tests/PHPStan/Rules/EnumCases/data/enum-case-override-native-types.php \
--exclude tests/PHPStan/Rules/Functions/data/bug-14241.php \
--exclude tests/PHPStan/Rules/Variables/data/bug-14349.php \
--exclude tests/PHPStan/Rules/Variables/data/bug-14352.php \
Expand Down
1 change: 1 addition & 0 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ parameters:
reportPossiblyNonexistentConstantArrayOffset: false
checkMissingOverrideMethodAttribute: false
checkMissingOverridePropertyAttribute: null
checkMissingOverrideConstantAttribute: null
mixinExcludeClasses: []
scanFiles: []
scanDirectories: []
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ parametersSchema:
reportPossiblyNonexistentConstantArrayOffset: bool()
checkMissingOverrideMethodAttribute: bool()
checkMissingOverridePropertyAttribute: schema(bool(), nullable())
checkMissingOverrideConstantAttribute: schema(bool(), nullable())
parallel: structure([
jobSize: int(),
processTimeout: float(),
Expand Down
5 changes: 5 additions & 0 deletions src/Php/PhpVersions.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ public function supportsOverrideAttributeOnProperty(): TrinaryLogic
return IntegerRangeType::fromInterval(80500, null)->isSuperTypeOf($this->phpVersions)->result;
}

public function supportsOverrideAttributeOnClassConstant(): TrinaryLogic
{
return IntegerRangeType::fromInterval(80600, null)->isSuperTypeOf($this->phpVersions)->result;
}

public function supportsAttributesOnGlobalConstants(): TrinaryLogic
{
return IntegerRangeType::fromInterval(80500, null)->isSuperTypeOf($this->phpVersions)->result;
Expand Down
18 changes: 18 additions & 0 deletions src/Rules/Classes/ClassConstantAttributesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\AttributesCheck;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
* @implements Rule<Node\Stmt\ClassConst>
Expand All @@ -29,6 +30,23 @@

public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
{
if (!$scope->getPhpVersion()->supportsOverrideAttributeOnClassConstant()->yes()) {

Check warning on line 33 in src/Rules/Classes/ClassConstantAttributesRule.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array { - if (!$scope->getPhpVersion()->supportsOverrideAttributeOnClassConstant()->yes()) { + if ($scope->getPhpVersion()->supportsOverrideAttributeOnClassConstant()->no()) { foreach ($node->attrGroups as $attrGroup) { foreach ($attrGroup->attrs as $attr) { if ($attr->name->toLowerString() !== 'override') {
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toLowerString() !== 'override') {
continue;
}

return [
RuleErrorBuilder::message('Attribute class Override can be used with class constants only on PHP 8.6 and later.')
->identifier('classConstant.overrideAttribute')
->nonIgnorable()
->build(),
];
}
}
}

return $this->attributesCheck->check(
$scope,
$node->attrGroups,
Expand Down
193 changes: 193 additions & 0 deletions src/Rules/Constants/OverrideAttributeOnClassConstantCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Constants;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\ClassConstantReflection;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;
use function count;
use function sprintf;

/**
* Checks the #[\Override] attribute on class constants and enum cases, shared by OverridingConstantRule and OverridingEnumCaseRule.
*/
#[AutowiredService]
final class OverrideAttributeOnClassConstantCheck
{

public function __construct(
#[AutowiredParameter]
private ?bool $checkMissingOverrideConstantAttribute,
#[AutowiredParameter]
private ?bool $checkMissingOverridePropertyAttribute,
#[AutowiredParameter]
private bool $checkMissingOverrideMethodAttribute,
)
{
}

public function findPrototype(ClassReflection $classReflection, string $constantName): ?ClassConstantReflection
{
foreach ($classReflection->getImmediateInterfaces() as $immediateInterface) {
if ($immediateInterface->hasConstant($constantName)) {
return $immediateInterface->getConstant($constantName);
}
}

$parentClass = $classReflection->getParentClass();
if ($parentClass === null) {
return null;
}

if (!$parentClass->hasConstant($constantName)) {
return null;
}

$constant = $parentClass->getConstant($constantName);
if ($constant->isPrivate()) {
return null;
}

return $constant;
}

/**
* @return list<IdentifierRuleError>
*/
public function check(
Scope $scope,
Node\Stmt\ClassConst|Node\Stmt\EnumCase $node,
string $constantName,
?ClassConstantReflection $prototype,
): array
{
if (!$scope->isInClass()) {
throw new ShouldNotHappenException();
}

if ($node instanceof Node\Stmt\EnumCase) {
$description = 'Enum case';
$overrideIdentifier = 'enum.caseOverride';
$missingOverrideIdentifier = 'enum.caseMissingOverride';
$isFixable = true;
} else {
$description = 'Constant';
$overrideIdentifier = 'classConstant.override';
$missingOverrideIdentifier = 'classConstant.missingOverride';
// the attribute applies to all constants declared in the statement
$isFixable = count($node->consts) === 1;
}

$className = $scope->getClassReflection()->getDisplayName(false);
$hasOverrideAttribute = $this->hasOverrideAttribute($node->attrGroups);

if ($prototype === null) {
if (!$hasOverrideAttribute) {
return [];
}

$builder = RuleErrorBuilder::message(sprintf(
'%s %s::%s has #[\Override] attribute but does not override any constant.',
$description,
$className,
$constantName,
))
->nonIgnorable()
->identifier($overrideIdentifier);
if ($isFixable) {
$builder->fixNode($node, function (Node\Stmt\ClassConst|Node\Stmt\EnumCase $node) {
$node->attrGroups = $this->filterOverrideAttribute($node->attrGroups);
return $node;
});
}

return [$builder->build()];
}

if (
$hasOverrideAttribute
|| $scope->isInTrait()
|| !$this->isMissingOverrideAttributeChecked($scope)
) {
return [];
}

$builder = RuleErrorBuilder::message(sprintf(
'%s %s::%s overrides constant %s::%s but is missing the #[\Override] attribute.',
$description,
$className,
$constantName,
$prototype->getDeclaringClass()->getDisplayName(false),
$prototype->getName(),
))->identifier($missingOverrideIdentifier);
if ($isFixable) {
$builder->fixNode($node, static function (Node\Stmt\ClassConst|Node\Stmt\EnumCase $node) {
$node->attrGroups[] = new Node\AttributeGroup([
new Node\Attribute(new Node\Name\FullyQualified('Override')),
]);

return $node;
});
}

return [$builder->build()];
}

private function isMissingOverrideAttributeChecked(Scope $scope): bool
{
if ($this->checkMissingOverrideConstantAttribute !== null) {
return $this->checkMissingOverrideConstantAttribute;
}

// every analysed PHP version must support the attribute, e.g. not with "php": "^8.5" in composer.json
return ($this->checkMissingOverridePropertyAttribute === true || $this->checkMissingOverrideMethodAttribute)
&& $scope->getPhpVersion()->supportsOverrideAttributeOnClassConstant()->yes();
}

/**
* @param Node\AttributeGroup[] $attrGroups
* @return Node\AttributeGroup[]
*/
private function filterOverrideAttribute(array $attrGroups): array
{
foreach ($attrGroups as $i => $attrGroup) {
foreach ($attrGroup->attrs as $j => $attr) {
if ($attr->name->toLowerString() !== 'override') {
continue;
}

unset($attrGroup->attrs[$j]);
if (count($attrGroup->attrs) !== 0) {
continue;
}

unset($attrGroups[$i]);
}
}

return $attrGroups;
}

/**
* @param Node\AttributeGroup[] $attrGroups
*/
private function hasOverrideAttribute(array $attrGroups): bool
{
foreach ($attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toLowerString() === 'override') {
return true;
}
}
}

return false;
}

}
36 changes: 8 additions & 28 deletions src/Rules/Constants/OverridingConstantRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ final class OverridingConstantRule implements Rule
public function __construct(
#[AutowiredParameter]
private bool $checkPhpDocMethodSignatures,
private OverrideAttributeOnClassConstantCheck $overrideAttributeCheck,
)
{
}
Expand All @@ -44,7 +45,12 @@ public function processNode(Node $node, Scope $scope): array
$errors = [];
foreach ($node->consts as $const) {
$constantName = $const->name->toString();
$errors = array_merge($errors, $this->processSingleConstant($scope->getClassReflection(), $constantName));
$prototype = $this->overrideAttributeCheck->findPrototype($scope->getClassReflection(), $constantName);
$errors = array_merge(
$errors,
$this->overrideAttributeCheck->check($scope, $node, $constantName, $prototype),
$this->processSingleConstant($scope->getClassReflection(), $constantName, $prototype),
);
}

return $errors;
Expand All @@ -53,9 +59,8 @@ public function processNode(Node $node, Scope $scope): array
/**
* @return list<IdentifierRuleError>
*/
private function processSingleConstant(ClassReflection $classReflection, string $constantName): array
private function processSingleConstant(ClassReflection $classReflection, string $constantName, ?ClassConstantReflection $prototype): array
{
$prototype = $this->findPrototype($classReflection, $constantName);
if ($prototype === null) {
return [];
}
Expand Down Expand Up @@ -148,29 +153,4 @@ private function processSingleConstant(ClassReflection $classReflection, string
return $errors;
}

private function findPrototype(ClassReflection $classReflection, string $constantName): ?ClassConstantReflection
{
foreach ($classReflection->getImmediateInterfaces() as $immediateInterface) {
if ($immediateInterface->hasConstant($constantName)) {
return $immediateInterface->getConstant($constantName);
}
}

$parentClass = $classReflection->getParentClass();
if ($parentClass === null) {
return null;
}

if (!$parentClass->hasConstant($constantName)) {
return null;
}

$constant = $parentClass->getConstant($constantName);
if ($constant->isPrivate()) {
return null;
}

return $constant;
}

}
18 changes: 18 additions & 0 deletions src/Rules/EnumCases/EnumCaseAttributesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Rules\AttributesCheck;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
* @implements Rule<Node\Stmt\EnumCase>
Expand All @@ -29,6 +30,23 @@ public function getNodeType(): string

public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array
{
if (!$scope->getPhpVersion()->supportsOverrideAttributeOnClassConstant()->yes()) {
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toLowerString() !== 'override') {
continue;
}

return [
RuleErrorBuilder::message('Attribute class Override can be used with enum cases only on PHP 8.6 and later.')
->identifier('enum.caseOverrideAttribute')
->nonIgnorable()
->build(),
];
}
}
}

return $this->attributesCheck->check(
$scope,
$node->attrGroups,
Expand Down
Loading
Loading