diff --git a/Makefile b/Makefile index 9d5cff7a01a..ddeae1f5772 100644 --- a/Makefile +++ b/Makefile @@ -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 \ @@ -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 \ diff --git a/conf/config.neon b/conf/config.neon index 84b5b277ef4..32ea19804ba 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -112,6 +112,7 @@ parameters: reportPossiblyNonexistentConstantArrayOffset: false checkMissingOverrideMethodAttribute: false checkMissingOverridePropertyAttribute: null + checkMissingOverrideConstantAttribute: null mixinExcludeClasses: [] scanFiles: [] scanDirectories: [] diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index 01674de1d6a..70db3760586 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -116,6 +116,7 @@ parametersSchema: reportPossiblyNonexistentConstantArrayOffset: bool() checkMissingOverrideMethodAttribute: bool() checkMissingOverridePropertyAttribute: schema(bool(), nullable()) + checkMissingOverrideConstantAttribute: schema(bool(), nullable()) parallel: structure([ jobSize: int(), processTimeout: float(), diff --git a/src/Php/PhpVersions.php b/src/Php/PhpVersions.php index 2fc76b8b3d8..ee830d16bee 100644 --- a/src/Php/PhpVersions.php +++ b/src/Php/PhpVersions.php @@ -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; diff --git a/src/Rules/Classes/ClassConstantAttributesRule.php b/src/Rules/Classes/ClassConstantAttributesRule.php index a6c0506443f..71ad5f50de8 100644 --- a/src/Rules/Classes/ClassConstantAttributesRule.php +++ b/src/Rules/Classes/ClassConstantAttributesRule.php @@ -10,6 +10,7 @@ use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Rules\AttributesCheck; use PHPStan\Rules\Rule; +use PHPStan\Rules\RuleErrorBuilder; /** * @implements Rule @@ -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 class constants only on PHP 8.6 and later.') + ->identifier('classConstant.overrideAttribute') + ->nonIgnorable() + ->build(), + ]; + } + } + } + return $this->attributesCheck->check( $scope, $node->attrGroups, diff --git a/src/Rules/Constants/OverrideAttributeOnClassConstantCheck.php b/src/Rules/Constants/OverrideAttributeOnClassConstantCheck.php new file mode 100644 index 00000000000..7e625a0e9d7 --- /dev/null +++ b/src/Rules/Constants/OverrideAttributeOnClassConstantCheck.php @@ -0,0 +1,193 @@ +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 + */ + 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; + } + +} diff --git a/src/Rules/Constants/OverridingConstantRule.php b/src/Rules/Constants/OverridingConstantRule.php index ad538c34688..783b4411409 100644 --- a/src/Rules/Constants/OverridingConstantRule.php +++ b/src/Rules/Constants/OverridingConstantRule.php @@ -26,6 +26,7 @@ final class OverridingConstantRule implements Rule public function __construct( #[AutowiredParameter] private bool $checkPhpDocMethodSignatures, + private OverrideAttributeOnClassConstantCheck $overrideAttributeCheck, ) { } @@ -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; @@ -53,9 +59,8 @@ public function processNode(Node $node, Scope $scope): array /** * @return list */ - 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 []; } @@ -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; - } - } diff --git a/src/Rules/EnumCases/EnumCaseAttributesRule.php b/src/Rules/EnumCases/EnumCaseAttributesRule.php index b0e670af317..009cee3674c 100644 --- a/src/Rules/EnumCases/EnumCaseAttributesRule.php +++ b/src/Rules/EnumCases/EnumCaseAttributesRule.php @@ -10,6 +10,7 @@ use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Rules\AttributesCheck; use PHPStan\Rules\Rule; +use PHPStan\Rules\RuleErrorBuilder; /** * @implements Rule @@ -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, diff --git a/src/Rules/EnumCases/OverridingEnumCaseRule.php b/src/Rules/EnumCases/OverridingEnumCaseRule.php new file mode 100644 index 00000000000..891ff3aff62 --- /dev/null +++ b/src/Rules/EnumCases/OverridingEnumCaseRule.php @@ -0,0 +1,98 @@ + + */ +#[RegisteredRule(level: 0)] +final class OverridingEnumCaseRule implements Rule +{ + + public function __construct( + #[AutowiredParameter] + private bool $checkPhpDocMethodSignatures, + private OverrideAttributeOnClassConstantCheck $overrideAttributeCheck, + ) + { + } + + public function getNodeType(): string + { + return Node\Stmt\EnumCase::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $classReflection = $scope->getClassReflection(); + if ($classReflection === null || !$classReflection->isEnum()) { + return []; + } + + $caseName = $node->name->toString(); + $prototype = $this->overrideAttributeCheck->findPrototype($classReflection, $caseName); + $errors = $this->overrideAttributeCheck->check($scope, $node, $caseName, $prototype); + if ($prototype === null) { + return $errors; + } + + if ($prototype->isFinal()) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'Enum case %s::%s overrides final constant %s::%s.', + $classReflection->getDisplayName(false), + $caseName, + $prototype->getDeclaringClass()->getDisplayName(false), + $prototype->getName(), + ))->identifier('enum.caseOverridesFinal')->nonIgnorable()->build(); + } + + if (!$this->checkPhpDocMethodSignatures) { + return $errors; + } + + $prototypeNativeType = $prototype->getNativeType(); + if ($prototypeNativeType !== null) { + // an enum case is an untyped constant, PHP rejects it even when the type accepts its value + $errors[] = RuleErrorBuilder::message(sprintf( + 'Enum case %s::%s is not compatible with native type %s of constant %s::%s.', + $classReflection->getDisplayName(false), + $caseName, + $prototypeNativeType->describe(VerbosityLevel::typeOnly()), + $prototype->getDeclaringClass()->getDisplayName(false), + $prototype->getName(), + ))->identifier('enum.caseNativeType')->nonIgnorable()->build(); + + return $errors; + } + + if ( + $prototype->hasPhpDocType() + && !$prototype->getValueType()->isSuperTypeOf(new EnumCaseObjectType($classReflection->getName(), $caseName))->yes() + ) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'Enum case %s::%s is not compatible with type %s of constant %s::%s.', + $classReflection->getDisplayName(false), + $caseName, + $prototype->getValueType()->describe(VerbosityLevel::value()), + $prototype->getDeclaringClass()->getDisplayName(false), + $prototype->getName(), + ))->identifier('enum.caseType')->build(); + } + + return $errors; + } + +} diff --git a/src/Rules/Properties/OverridingPropertyRule.php b/src/Rules/Properties/OverridingPropertyRule.php index 40a76de3d26..d3f54c38a50 100644 --- a/src/Rules/Properties/OverridingPropertyRule.php +++ b/src/Rules/Properties/OverridingPropertyRule.php @@ -81,7 +81,7 @@ public function processNode(Node $node, Scope $scope): array || ( $this->checkMissingOverridePropertyAttribute === null && $this->checkMissingOverrideMethodAttribute - && $this->phpVersion->supportsOverrideAttributeOnProperty() + && $scope->getPhpVersion()->supportsOverrideAttributeOnProperty()->yes() ) ) && !$scope->isInTrait() diff --git a/tests/PHPStan/Rules/Classes/ClassConstantAttributesRuleTest.php b/tests/PHPStan/Rules/Classes/ClassConstantAttributesRuleTest.php index 2364e67704d..253fd257e61 100644 --- a/tests/PHPStan/Rules/Classes/ClassConstantAttributesRuleTest.php +++ b/tests/PHPStan/Rules/Classes/ClassConstantAttributesRuleTest.php @@ -17,6 +17,7 @@ use PHPStan\Rules\Rule; use PHPStan\Rules\RuleLevelHelper; use PHPStan\Testing\RuleTestCase; +use const PHP_VERSION_ID; /** * @extends RuleTestCase @@ -74,4 +75,23 @@ public function testRule(): void ]); } + public function testOverrideAttributePhpVersionNarrowedScope(): void + { + $errors = []; + if (PHP_VERSION_ID < 80300) { + $errors[] = [ + 'Attribute class Override does not have the class constant target.', + 18, + ]; + } + if (PHP_VERSION_ID < 80600) { + $errors[] = [ + 'Attribute class Override can be used with class constants only on PHP 8.6 and later.', + 27, + ]; + } + + $this->analyse([__DIR__ . '/data/class-constant-override-attr-php-versions.php'], $errors); + } + } diff --git a/tests/PHPStan/Rules/Classes/data/class-constant-override-attr-php-versions.php b/tests/PHPStan/Rules/Classes/data/class-constant-override-attr-php-versions.php new file mode 100644 index 00000000000..31ffb9da708 --- /dev/null +++ b/tests/PHPStan/Rules/Classes/data/class-constant-override-attr-php-versions.php @@ -0,0 +1,30 @@ += 8.6 + +namespace ClassConstantOverrideAttrPhpVersions; + +use Override; + +class Base +{ + + public const FOO = 1; + +} + +if (PHP_VERSION_ID >= 80600) { + class SupportedInBranch extends Base + { + + #[Override] + public const FOO = 1; + + } +} + +class AlwaysUnsupported extends Base +{ + + #[Override] + public const FOO = 1; + +} diff --git a/tests/PHPStan/Rules/Constants/OverridingConstantRuleConfigPhpTest.php b/tests/PHPStan/Rules/Constants/OverridingConstantRuleConfigPhpTest.php new file mode 100644 index 00000000000..6dc9df6b816 --- /dev/null +++ b/tests/PHPStan/Rules/Constants/OverridingConstantRuleConfigPhpTest.php @@ -0,0 +1,60 @@ + + */ +class OverridingConstantRuleConfigPhpTest extends RuleTestCase +{ + + private ?bool $checkMissingOverrideConstantAttribute = null; + + protected function getRule(): Rule + { + return new OverridingConstantRule( + true, + new OverrideAttributeOnClassConstantCheck( + $this->checkMissingOverrideConstantAttribute, + true, + true, + ), + ); + } + + public function testDefaultReportsOnlyWhenEveryPhpVersionSupportsAttribute(): void + { + $this->analyse([__DIR__ . '/data/constant-missing-override-attr-php-versions.php'], [ + [ + 'Constant ConstantMissingOverrideAttrPhpVersions\SupportedInBranch::FOO overrides constant ConstantMissingOverrideAttrPhpVersions\Foo::FOO but is missing the #[\Override] attribute.', + 16, + ], + ]); + } + + public function testEnabledReportsOnEveryPhpVersion(): void + { + $this->checkMissingOverrideConstantAttribute = true; + $this->analyse([__DIR__ . '/data/constant-missing-override-attr-php-versions.php'], [ + [ + 'Constant ConstantMissingOverrideAttrPhpVersions\SupportedInBranch::FOO overrides constant ConstantMissingOverrideAttrPhpVersions\Foo::FOO but is missing the #[\Override] attribute.', + 16, + ], + [ + 'Constant ConstantMissingOverrideAttrPhpVersions\DependsOnPhpVersion::FOO overrides constant ConstantMissingOverrideAttrPhpVersions\Foo::FOO but is missing the #[\Override] attribute.', + 24, + ], + ]); + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/data/constant-missing-override-attr-php-versions.neon', + ]; + } + +} diff --git a/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php b/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php index ef17e188446..127f60490e0 100644 --- a/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php +++ b/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php @@ -4,16 +4,32 @@ use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhp; +use function array_merge; +use function usort; use const PHP_VERSION_ID; /** @extends RuleTestCase */ class OverridingConstantRuleTest extends RuleTestCase { + private ?bool $checkMissingOverrideConstantAttribute = null; + + private ?bool $checkMissingOverridePropertyAttribute = null; + + private bool $checkMissingOverrideMethodAttribute = false; + protected function getRule(): Rule { - return new OverridingConstantRule(true); + return new OverridingConstantRule( + true, + new OverrideAttributeOnClassConstantCheck( + $this->checkMissingOverrideConstantAttribute, + $this->checkMissingOverridePropertyAttribute, + $this->checkMissingOverrideMethodAttribute, + ), + ); } public function testRule(): void @@ -114,4 +130,98 @@ public function testNativeTypes(): void ]); } + public static function dataOverrideAttribute(): iterable + { + $missingErrors = [ + [ + 'Constant ConstantOverrideAttr\PP::C2 overrides constant ConstantOverrideAttr\P::C2 but is missing the #[\Override] attribute.', + 36, + ], + [ + 'Constant ConstantOverrideAttr\C::C3 overrides constant ConstantOverrideAttr\PP::C3 but is missing the #[\Override] attribute.', + 49, + ], + ]; + + // the default follows the other options only when the analysed PHP version supports the attribute, + // OverridingConstantRuleConfigPhpTest covers PHP version ranges + $defaultErrors = PHP_VERSION_ID >= 80600 ? $missingErrors : []; + + // checkMissingOverrideConstantAttribute, checkMissingOverridePropertyAttribute, checkMissingOverrideMethodAttribute + yield [null, null, false, []]; + yield [null, null, true, $defaultErrors]; + yield [null, true, false, $defaultErrors]; + yield [null, false, true, $defaultErrors]; + yield [null, false, false, []]; + yield [true, null, false, $missingErrors]; + yield [true, false, false, $missingErrors]; + yield [false, null, true, []]; + yield [false, true, true, []]; + } + + /** + * @param list $expectedErrors + */ + #[RequiresPhp('>= 8.2.0')] + #[DataProvider('dataOverrideAttribute')] + public function testOverrideAttribute( + ?bool $checkMissingOverrideConstantAttribute, + ?bool $checkMissingOverridePropertyAttribute, + bool $checkMissingOverrideMethodAttribute, + array $expectedErrors, + ): void + { + $this->checkMissingOverrideConstantAttribute = $checkMissingOverrideConstantAttribute; + $this->checkMissingOverridePropertyAttribute = $checkMissingOverridePropertyAttribute; + $this->checkMissingOverrideMethodAttribute = $checkMissingOverrideMethodAttribute; + + $errors = array_merge([ + [ + 'Constant ConstantOverrideAttr\Unrelated::U has #[\Override] attribute but does not override any constant.', + 18, + ], + [ + 'Constant ConstantOverrideAttr\C::PRIVATE has #[\Override] attribute but does not override any constant.', + 55, + ], + [ + 'Constant ConstantOverrideAttr\C::NOTHING has #[\Override] attribute but does not override any constant.', + 57, + ], + [ + 'Constant ConstantOverrideAttr\C::C5 has #[\Override] attribute but does not override any constant.', + 59, + ], + [ + 'Constant ConstantOverrideAttr\C::C6 has #[\Override] attribute but does not override any constant.', + 59, + ], + [ + 'Constant ConstantOverrideAttr\E::C has #[\Override] attribute but does not override any constant.', + 67, + ], + [ + 'Constant ConstantOverrideAttr\UsesTraitWithoutParent::C1 has #[\Override] attribute but does not override any constant.', + 73, + ], + [ + 'Constant ConstantOverrideAttr\RedeclaresTraitConstant::T has #[\Override] attribute but does not override any constant.', + 106, + ], + [ + 'Constant class@anonymous/tests/PHPStan/Rules/Constants/data/constant-override-attr.php:115::I has #[\Override] attribute but does not override any constant.', + 116, + ], + ], $expectedErrors); + usort($errors, static fn (array $a, array $b): int => $a[1] <=> $b[1]); + + $this->analyse([__DIR__ . '/data/constant-override-attr.php'], $errors); + } + + public function testFixOverrideAttribute(): void + { + $this->checkMissingOverrideConstantAttribute = true; + $this->fix(__DIR__ . '/data/constant-override-attr-fix.php', __DIR__ . '/data/constant-override-attr-fix.php.fixed'); + } + } diff --git a/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.neon b/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.neon new file mode 100644 index 00000000000..37a89190078 --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: + min: 80500 + max: 80600 diff --git a/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.php b/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.php new file mode 100644 index 00000000000..2d940c1bdda --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/constant-missing-override-attr-php-versions.php @@ -0,0 +1,26 @@ += 80600) { + class SupportedInBranch extends Foo + { + + public const FOO = 1; + + } +} + +class DependsOnPhpVersion extends Foo +{ + + public const FOO = 1; + +} diff --git a/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php b/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php new file mode 100644 index 00000000000..87dfd2d0f8d --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php @@ -0,0 +1,43 @@ += 8.6 + +namespace ConstantOverrideAttrFix; + +class Foo +{ + + public const FOO = 1; + + public const BAR = 2; + + public const BAZ = 3; + +} + +class Bar extends Foo +{ + + public const FOO = 1; + + /** @var int */ + public const BAR = 2; + + public const BAZ = 3, LOREM = 4; + +} + +class Baz extends Foo +{ + + #[\Override] + public const FOO = 1; + + #[\Override] + public const IPSUM = 5; + + #[\Deprecated, \Override] + public const DOLOR = 6; + + #[\Override] + public const SIT = 7, AMET = 8; + +} diff --git a/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php.fixed b/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php.fixed new file mode 100644 index 00000000000..88787376bcf --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/constant-override-attr-fix.php.fixed @@ -0,0 +1,44 @@ += 8.6 + +namespace ConstantOverrideAttrFix; + +class Foo +{ + + public const FOO = 1; + + public const BAR = 2; + + public const BAZ = 3; + +} + +class Bar extends Foo +{ + + #[\Override] + public const FOO = 1; + + /** @var int */ + #[\Override] + public const BAR = 2; + + public const BAZ = 3, LOREM = 4; + +} + +class Baz extends Foo +{ + + #[\Override] + public const FOO = 1; + + public const IPSUM = 5; + + #[\Deprecated] + public const DOLOR = 6; + + #[\Override] + public const SIT = 7, AMET = 8; + +} diff --git a/tests/PHPStan/Rules/Constants/data/constant-override-attr.php b/tests/PHPStan/Rules/Constants/data/constant-override-attr.php new file mode 100644 index 00000000000..c6351fe50d3 --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/constant-override-attr.php @@ -0,0 +1,119 @@ += 8.6 + +namespace ConstantOverrideAttr; + +interface I +{ + public const I = 'I'; +} + +interface II extends I +{ + #[\Override] + public const I = 'I'; +} + +interface Unrelated +{ + #[\Override] + public const U = 'U'; +} + +class P +{ + public const C1 = 'C1'; + public const C2 = 'C2'; + public const C3 = 'C3'; + public const C4 = 'C4'; + protected const PROTECTED = 'P'; + private const PRIVATE = 'P'; +} + +class PP extends P +{ + #[\Override] + public const C1 = 'C1'; + public const C2 = 'C2'; + #[\Override] + public const C3 = 'C3'; +} + +class C extends PP implements I +{ + #[\Override] + public const I = 'I'; + #[\Override] + public const C1 = 'C1'; + #[\Override] + public const C2 = 'C2'; + public const C3 = 'C3'; + #[\Override] + public const C4 = 'C4'; + public const C = 'C'; + #[\Override] + public const PROTECTED = 'P'; + #[\Override] + public const PRIVATE = 'P'; + #[\Override] + public const NOTHING = 'N'; + #[\Override] + public const C5 = 'C5', C6 = 'C6'; +} + +enum E implements I +{ + #[\Override] + public const I = 'I'; + #[\Override] + public const C = 'C'; +} + +trait DemoTrait +{ + #[\Override] + public const C1 = 'C1'; +} + +class UsesTraitWithParent extends P +{ + use DemoTrait; +} + +class UsesTraitWithoutParent +{ + use DemoTrait; +} + +trait TraitWithoutAttribute +{ + public const C2 = 'C2'; +} + +class UsesTraitWithoutAttribute extends P +{ + use TraitWithoutAttribute; +} + +trait RedeclaredTrait +{ + public const T = 'T'; +} + +class RedeclaresTraitConstant +{ + use RedeclaredTrait; + + #[\Override] + public const T = 'T'; +} + +function (): void { + new class () implements I { + #[\Override] + public const I = 'I'; + }; + new class () { + #[\Override] + public const I = 'I'; + }; +}; diff --git a/tests/PHPStan/Rules/EnumCases/EnumCaseAttributesRuleTest.php b/tests/PHPStan/Rules/EnumCases/EnumCaseAttributesRuleTest.php index 164068291e5..5d3e505d2c4 100644 --- a/tests/PHPStan/Rules/EnumCases/EnumCaseAttributesRuleTest.php +++ b/tests/PHPStan/Rules/EnumCases/EnumCaseAttributesRuleTest.php @@ -18,6 +18,7 @@ use PHPStan\Rules\RuleLevelHelper; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; +use const PHP_VERSION_ID; /** * @extends RuleTestCase @@ -76,4 +77,24 @@ public function testRule(): void ]); } + #[RequiresPhp('>= 8.1.0')] + public function testOverrideAttributePhpVersionNarrowedScope(): void + { + $errors = []; + if (PHP_VERSION_ID < 80300) { + $errors[] = [ + 'Attribute class Override does not have the class constant target.', + 18, + ]; + } + if (PHP_VERSION_ID < 80600) { + $errors[] = [ + 'Attribute class Override can be used with enum cases only on PHP 8.6 and later.', + 27, + ]; + } + + $this->analyse([__DIR__ . '/data/enum-case-override-attr-php-versions.php'], $errors); + } + } diff --git a/tests/PHPStan/Rules/EnumCases/OverridingEnumCaseRuleTest.php b/tests/PHPStan/Rules/EnumCases/OverridingEnumCaseRuleTest.php new file mode 100644 index 00000000000..4794af83fb5 --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/OverridingEnumCaseRuleTest.php @@ -0,0 +1,88 @@ + + */ +class OverridingEnumCaseRuleTest extends RuleTestCase +{ + + private bool $checkMissingOverrideConstantAttribute = false; + + protected function getRule(): Rule + { + return new OverridingEnumCaseRule( + true, + new OverrideAttributeOnClassConstantCheck( + $this->checkMissingOverrideConstantAttribute, + null, + false, + ), + ); + } + + #[RequiresPhp('>= 8.1.0')] + public function testRule(): void + { + $this->checkMissingOverrideConstantAttribute = true; + $this->analyse([__DIR__ . '/data/enum-case-override-attr.php'], [ + [ + 'Enum case EnumCaseOverrideAttr\WithCase::J overrides constant EnumCaseOverrideAttr\I::J but is missing the #[\Override] attribute.', + 19, + ], + [ + 'Enum case EnumCaseOverrideAttr\ViaParentInterface::K has #[\Override] attribute but does not override any constant.', + 26, + ], + [ + 'Enum case EnumCaseOverrideAttr\NoInterface::C has #[\Override] attribute but does not override any constant.', + 32, + ], + [ + 'Enum case EnumCaseOverrideAttr\OverridesFinal::F overrides final constant EnumCaseOverrideAttr\WithFinal::F.', + 44, + ], + [ + 'Enum case EnumCaseOverrideAttr\PhpDocTypedEnum::INT is not compatible with type int of constant EnumCaseOverrideAttr\PhpDocTyped::INT.', + 66, + ], + [ + 'Enum case EnumCaseOverrideAttr\IntBackedPhpDocTypedEnum::INT is not compatible with type int of constant EnumCaseOverrideAttr\PhpDocTyped::INT.', + 76, + ], + ]); + } + + #[RequiresPhp('>= 8.3.0')] + public function testNativeTypes(): void + { + $this->analyse([__DIR__ . '/data/enum-case-override-native-types.php'], [ + [ + 'Enum case EnumCaseOverrideNativeTypes\Foo::INT is not compatible with native type int of constant EnumCaseOverrideNativeTypes\NativeTyped::INT.', + 23, + ], + [ + 'Enum case EnumCaseOverrideNativeTypes\Foo::UNIT_ENUM is not compatible with native type UnitEnum of constant EnumCaseOverrideNativeTypes\NativeTyped::UNIT_ENUM.', + 24, + ], + [ + 'Enum case EnumCaseOverrideNativeTypes\Foo::MIXED is not compatible with native type mixed of constant EnumCaseOverrideNativeTypes\NativeTyped::MIXED.', + 25, + ], + ]); + } + + #[RequiresPhp('>= 8.1.0')] + public function testFixOverrideAttribute(): void + { + $this->checkMissingOverrideConstantAttribute = true; + $this->fix(__DIR__ . '/data/enum-case-override-attr-fix.php', __DIR__ . '/data/enum-case-override-attr-fix.php.fixed'); + } + +} diff --git a/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php new file mode 100644 index 00000000000..a07f4d4c8fa --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php @@ -0,0 +1,25 @@ += 8.6 + +namespace EnumCaseOverrideAttrFix; + +interface I +{ + public const I = 'I'; +} + +enum Foo implements I +{ + case I; + + #[\Override] + case J; +} + +enum Bar implements I +{ + /** Some description */ + case I; + + #[\Deprecated, \Override] + case J; +} diff --git a/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php.fixed b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php.fixed new file mode 100644 index 00000000000..f097eb49d9b --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-fix.php.fixed @@ -0,0 +1,26 @@ += 8.6 + +namespace EnumCaseOverrideAttrFix; + +interface I +{ + public const I = 'I'; +} + +enum Foo implements I +{ + #[\Override] + case I; + + case J; +} + +enum Bar implements I +{ + /** Some description */ + #[\Override] + case I; + + #[\Deprecated] + case J; +} diff --git a/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-php-versions.php b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-php-versions.php new file mode 100644 index 00000000000..8bec958fdeb --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr-php-versions.php @@ -0,0 +1,30 @@ += 8.6 + +namespace EnumCaseOverrideAttrPhpVersions; + +use Override; + +interface Base +{ + + public const FOO = 1; + +} + +if (PHP_VERSION_ID >= 80600) { + enum SupportedInBranch implements Base + { + + #[Override] + case FOO; + + } +} + +enum AlwaysUnsupported implements Base +{ + + #[Override] + case FOO; + +} diff --git a/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr.php b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr.php new file mode 100644 index 00000000000..de41257ece7 --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-attr.php @@ -0,0 +1,82 @@ += 8.6 + +namespace EnumCaseOverrideAttr; + +interface I +{ + public const I = 'I'; + public const J = 'J'; +} + +interface II extends I +{ +} + +enum WithCase implements I +{ + #[\Override] + case I; + case J; +} + +enum ViaParentInterface: string implements II +{ + #[\Override] + case I = 'i'; + #[\Override] + case K = 'k'; +} + +enum NoInterface +{ + #[\Override] + case C; + case D; +} + +interface WithFinal +{ + final public const F = 1; +} + +enum OverridesFinal implements WithFinal +{ + #[\Override] + case F; +} + +enum Other +{ + case A; +} + +interface PhpDocTyped +{ + /** @var int */ + public const INT = 1; + + /** @var \UnitEnum */ + public const UNIT_ENUM = Other::A; + + public const UNTYPED = 1; +} + +enum PhpDocTypedEnum implements PhpDocTyped +{ + #[\Override] + case INT; + #[\Override] + case UNIT_ENUM; + #[\Override] + case UNTYPED; +} + +enum IntBackedPhpDocTypedEnum: int implements PhpDocTyped +{ + #[\Override] + case INT = 1; + #[\Override] + case UNIT_ENUM = 2; + #[\Override] + case UNTYPED = 3; +} diff --git a/tests/PHPStan/Rules/EnumCases/data/enum-case-override-native-types.php b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-native-types.php new file mode 100644 index 00000000000..cc5309f89d1 --- /dev/null +++ b/tests/PHPStan/Rules/EnumCases/data/enum-case-override-native-types.php @@ -0,0 +1,27 @@ += 8.3 + +namespace EnumCaseOverrideNativeTypes; + +enum Other +{ + case A; +} + +interface NativeTyped +{ + public const int INT = 1; + + public const \UnitEnum UNIT_ENUM = Other::A; + + public const mixed MIXED = 1; + + public const UNTYPED = 1; +} + +enum Foo implements NativeTyped +{ + case INT; + case UNIT_ENUM; + case MIXED; + case UNTYPED; +} diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php new file mode 100644 index 00000000000..89986fbc3cc --- /dev/null +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php @@ -0,0 +1,60 @@ + + */ +class OverridingPropertyRuleConfigPhpTest extends RuleTestCase +{ + + private ?bool $checkMissingOverridePropertyAttribute = null; + + protected function getRule(): Rule + { + return new OverridingPropertyRule( + self::getContainer()->getByType(PhpVersion::class), + true, + true, + $this->checkMissingOverridePropertyAttribute, + true, + ); + } + + public function testDefaultReportsOnlyWhenEveryPhpVersionSupportsAttribute(): void + { + $this->analyse([__DIR__ . '/data/property-missing-override-attr-php-versions.php'], [ + [ + 'Property PropertyMissingOverrideAttrPhpVersions\SupportedInBranch::$foo overrides property PropertyMissingOverrideAttrPhpVersions\Foo::$foo but is missing the #[\Override] attribute.', + 16, + ], + ]); + } + + public function testEnabledReportsOnEveryPhpVersion(): void + { + $this->checkMissingOverridePropertyAttribute = true; + $this->analyse([__DIR__ . '/data/property-missing-override-attr-php-versions.php'], [ + [ + 'Property PropertyMissingOverrideAttrPhpVersions\SupportedInBranch::$foo overrides property PropertyMissingOverrideAttrPhpVersions\Foo::$foo but is missing the #[\Override] attribute.', + 16, + ], + [ + 'Property PropertyMissingOverrideAttrPhpVersions\DependsOnPhpVersion::$foo overrides property PropertyMissingOverrideAttrPhpVersions\Foo::$foo but is missing the #[\Override] attribute.', + 24, + ], + ]); + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/data/property-missing-override-attr-php-versions.neon', + ]; + } + +} diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php index beb16f6cf80..c56e405651f 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php @@ -23,12 +23,10 @@ class OverridingPropertyRuleTest extends RuleTestCase private bool $checkMissingOverrideMethodAttribute = false; - private int $phpVersionId = PHP_VERSION_ID; - protected function getRule(): Rule { return new OverridingPropertyRule( - new PhpVersion($this->phpVersionId), + self::getContainer()->getByType(PhpVersion::class), true, $this->reportMaybes, $this->checkMissingOverridePropertyAttribute, @@ -301,29 +299,24 @@ public static function dataOverrideAttribute(): iterable 44, ], ]; - yield [null, false, 80400, []]; - yield [null, false, 80500, []]; - yield [null, true, 80400, []]; - yield [null, true, 80500, $errors]; - yield [true, false, 80400, $errors]; - yield [true, false, 80500, $errors]; - yield [true, true, 80400, $errors]; - yield [true, true, 80500, $errors]; - yield [false, false, 80400, []]; - yield [false, false, 80500, []]; - yield [false, true, 80400, []]; - yield [false, true, 80500, []]; + // the default follows checkMissingOverrideMethodAttribute only when the analysed PHP version supports the attribute, + // OverridingPropertyRuleConfigPhpTest covers PHP version ranges + yield [null, false, []]; + yield [null, true, PHP_VERSION_ID >= 80500 ? $errors : []]; + yield [true, false, $errors]; + yield [true, true, $errors]; + yield [false, false, []]; + yield [false, true, []]; } /** * @param list $expectedErrors */ #[DataProvider('dataOverrideAttribute')] - public function testOverrideAttribute(?bool $checkMissingOverridePropertyAttribute, bool $checkMissingOverrideMethodAttribute, int $phpVersionId, array $expectedErrors): void + public function testOverrideAttribute(?bool $checkMissingOverridePropertyAttribute, bool $checkMissingOverrideMethodAttribute, array $expectedErrors): void { $this->checkMissingOverridePropertyAttribute = $checkMissingOverridePropertyAttribute; $this->checkMissingOverrideMethodAttribute = $checkMissingOverrideMethodAttribute; - $this->phpVersionId = $phpVersionId; $this->reportMaybes = true; $errors = [ [ diff --git a/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.neon b/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.neon new file mode 100644 index 00000000000..2b09be89487 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: + min: 80400 + max: 80500 diff --git a/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.php b/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.php new file mode 100644 index 00000000000..79a572d676b --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/property-missing-override-attr-php-versions.php @@ -0,0 +1,26 @@ += 80500) { + class SupportedInBranch extends Foo + { + + public int $foo = 1; + + } +} + +class DependsOnPhpVersion extends Foo +{ + + public int $foo = 1; + +}