From 55d8f740cba6367d4130e6545ebe797c6987bfd5 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Sun, 15 Nov 2026 14:46:32 +0000 Subject: [PATCH 1/3] Report void overriding mixed and dropped by-ref return in OverridingMethodRule Extract the checks shared with property hooks into OverridingMethodCheck and let MethodParameterComparisonHelper compare any method reflection, so OverridingPropertyRule can reuse them for hooks. Amp-Thread-ID: https://ampcode.com/threads/T-01a1df04-9cc5-7608-a3ae-ede0c3cf05e5 --- src/Reflection/Php/PhpMethodReflection.php | 28 ++ .../MethodParameterComparisonHelper.php | 156 ++++++------ src/Rules/Methods/OverridingMethodCheck.php | 241 ++++++++++++++++++ src/Rules/Methods/OverridingMethodRule.php | 153 +---------- ...thPossiblyRenamedNamedArgumentRuleTest.php | 1 + .../Rules/Methods/MethodSignatureRuleTest.php | 1 + .../OverridingMethodRuleConfigPhpTest.php | 1 + .../Methods/OverridingMethodRuleTest.php | 28 ++ .../data/overriding-method-return-by-ref.php | 63 +++++ .../data/overriding-method-void-mixed.php | 41 +++ ...omoteParameterRuleWithOriginalRuleTest.php | 2 + 11 files changed, 494 insertions(+), 221 deletions(-) create mode 100644 src/Rules/Methods/OverridingMethodCheck.php create mode 100644 tests/PHPStan/Rules/Methods/data/overriding-method-return-by-ref.php create mode 100644 tests/PHPStan/Rules/Methods/data/overriding-method-void-mixed.php diff --git a/src/Reflection/Php/PhpMethodReflection.php b/src/Reflection/Php/PhpMethodReflection.php index 1de8565b82b..e77a7b3a756 100644 --- a/src/Reflection/Php/PhpMethodReflection.php +++ b/src/Reflection/Php/PhpMethodReflection.php @@ -221,6 +221,34 @@ public function getOnlyVariant(): ExtendedParametersAcceptor return $this->getVariants()[0]; } + /** + * @phpstan-assert-if-true !null $this->getHookedPropertyName() + * @phpstan-assert-if-true !null $this->getPropertyHookName() + */ + public function isPropertyHook(): bool + { + return $this->reflection->getBetterReflection()->isHook(); + } + + public function getHookedPropertyName(): ?string + { + return $this->reflection->getBetterReflection()->getHookProperty()?->getName(); + } + + /** + * @return 'get'|'set'|null + */ + public function getPropertyHookName(): ?string + { + $betterReflection = $this->reflection->getBetterReflection(); + $hookProperty = $betterReflection->getHookProperty(); + if ($hookProperty === null) { + return null; + } + + return $hookProperty->getHook('get') === $betterReflection ? 'get' : 'set'; + } + public function getNamedArgumentsVariants(): ?array { return null; diff --git a/src/Rules/Methods/MethodParameterComparisonHelper.php b/src/Rules/Methods/MethodParameterComparisonHelper.php index c86a76cacfc..514fc780810 100644 --- a/src/Rules/Methods/MethodParameterComparisonHelper.php +++ b/src/Rules/Methods/MethodParameterComparisonHelper.php @@ -9,7 +9,6 @@ use PHPStan\Php\PhpVersion; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\ExtendedMethodReflection; -use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection; use PHPStan\Rules\IdentifierRuleError; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\ArrayType; @@ -24,6 +23,7 @@ use function array_slice; use function count; use function sprintf; +use function ucfirst; #[AutowiredService] final class MethodParameterComparisonHelper @@ -39,26 +39,25 @@ public function __construct(private PhpVersion $phpVersion) public function compare( ExtendedMethodReflection $prototype, ClassReflection $prototypeDeclaringClass, - PhpMethodFromParserNodeReflection $method, + ExtendedMethodReflection $method, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope, bool $ignorable, + ?int $line = null, ): array { /** @var list $messages */ $messages = []; $prototypeVariant = $prototype->getVariants()[0]; - $methodParameters = $method->getParameters(); + $methodParameters = $method->getOnlyVariant()->getParameters(); $prototypeAfterVariadic = false; foreach ($prototypeVariant->getParameters() as $i => $prototypeParameter) { if (!array_key_exists($i, $methodParameters)) { $error = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() overrides method %s::%s() but misses parameter #%d $%s.', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + '%s overrides %s but misses parameter #%d $%s.', + ucfirst(OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass())), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), $i + 1, $prototypeParameter->getName(), ))->identifier('parameter.missing'); @@ -67,7 +66,7 @@ public function compare( $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); continue; } @@ -87,41 +86,37 @@ public function compare( if ($prototypeParameter->passedByReference()->no()) { if (!$methodParameter->passedByReference()->no()) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is passed by reference but parameter #%d $%s of method %s::%s() is not passed by reference.', + 'Parameter #%d $%s of %s is passed by reference but parameter #%d $%s of %s is not passed by reference.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('parameter.byRef'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } } elseif ($methodParameter->passedByReference()->no()) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not passed by reference but parameter #%d $%s of method %s::%s() is passed by reference.', + 'Parameter #%d $%s of %s is not passed by reference but parameter #%d $%s of %s is passed by reference.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('parameter.notByRef'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } if ($prototypeParameter->isVariadic()) { @@ -130,55 +125,51 @@ public function compare( if (!$methodParameter->isOptional()) { if (count($methodParameters) !== $i + 1) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not optional.', + 'Parameter #%d $%s of %s is not optional.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), ))->identifier('parameter.notOptional'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); continue; } $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not variadic but parameter #%d $%s of method %s::%s() is variadic.', + 'Parameter #%d $%s of %s is not variadic but parameter #%d $%s of %s is variadic.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('parameter.notVariadic'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); continue; } elseif (count($methodParameters) === $i + 1) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not variadic.', + 'Parameter #%d $%s of %s is not variadic.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), ))->identifier('parameter.notVariadic'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } } } elseif ($methodParameter->isVariadic()) { @@ -190,66 +181,60 @@ public function compare( } $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d ...$%s (%s) of method %s::%s() is not contravariant with parameter #%d $%s (%s) of method %s::%s().', + 'Parameter #%d ...$%s (%s) of %s is not contravariant with parameter #%d $%s (%s) of %s.', $i + 1, $methodParameter->getName(), $methodParameter->getNativeType()->describe(VerbosityLevel::typeOnly()), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + $j + 1, $remainingPrototypeParameter->getName(), $remainingPrototypeParameter->getNativeType()->describe(VerbosityLevel::typeOnly()), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('method.childParameterType'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } break; } $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is variadic but parameter #%d $%s of method %s::%s() is not variadic.', + 'Parameter #%d $%s of %s is variadic but parameter #%d $%s of %s is not variadic.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('parameter.variadic'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); continue; } if ($prototypeParameter->isOptional() && !$methodParameter->isOptional()) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is required but parameter #%d $%s of method %s::%s() is optional.', + 'Parameter #%d $%s of %s is required but parameter #%d $%s of %s is optional.', $i + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('parameter.notOptional'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } $methodParameterType = $methodParameter->getNativeType(); @@ -258,24 +243,22 @@ public function compare( if (!$this->phpVersion->supportsParameterTypeWidening()) { if (!$methodParameterType->equals($prototypeParameterType)) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s (%s) of method %s::%s() does not match parameter #%d $%s (%s) of method %s::%s().', + 'Parameter #%d $%s (%s) of %s does not match parameter #%d $%s (%s) of %s.', $i + 1, $methodParameter->getName(), $methodParameterType->describe(VerbosityLevel::typeOnly()), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), $prototypeParameterType->describe(VerbosityLevel::typeOnly()), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('method.childParameterType'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } continue; } @@ -286,44 +269,40 @@ public function compare( if ($this->phpVersion->supportsParameterContravariance()) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s (%s) of method %s::%s() is not contravariant with parameter #%d $%s (%s) of method %s::%s().', + 'Parameter #%d $%s (%s) of %s is not contravariant with parameter #%d $%s (%s) of %s.', $i + 1, $methodParameter->getName(), $methodParameterType->describe(VerbosityLevel::typeOnly()), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), $prototypeParameterType->describe(VerbosityLevel::typeOnly()), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('method.childParameterType'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } else { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s (%s) of method %s::%s() is not compatible with parameter #%d $%s (%s) of method %s::%s().', + 'Parameter #%d $%s (%s) of %s is not compatible with parameter #%d $%s (%s) of %s.', $i + 1, $methodParameter->getName(), $methodParameterType->describe(VerbosityLevel::typeOnly()), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), $i + 1, $prototypeParameter->getName(), $prototypeParameterType->describe(VerbosityLevel::typeOnly()), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), + OverridingMethodCheck::describeMethod($prototype, $prototypeDeclaringClass, true), ))->identifier('method.childParameterType'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } } @@ -342,18 +321,17 @@ public function compare( && !$methodParameter->isVariadic() ) { $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not variadic.', + 'Parameter #%d $%s of %s is not variadic.', $j + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), ))->identifier('parameter.notVariadic'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); continue; } @@ -363,18 +341,17 @@ public function compare( } $error = RuleErrorBuilder::message(sprintf( - 'Parameter #%d $%s of method %s::%s() is not optional.', + 'Parameter #%d $%s of %s is not optional.', $j + 1, $methodParameter->getName(), - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), + OverridingMethodCheck::describeMethod($method, $method->getDeclaringClass()), ))->identifier('parameter.notOptional'); if (! $ignorable) { $error->nonIgnorable(); } - $messages[] = $error->build(); + $messages[] = $this->buildError($error, $line); } return $messages; @@ -385,8 +362,29 @@ private function isParameterTypeCompatible(Type $methodParameterType, Type $prot return $this->isTypeCompatible($methodParameterType, $prototypeParameterType, $supportsContravariance, false); } + /** + * @param RuleErrorBuilder $error + */ + private function buildError(RuleErrorBuilder $error, ?int $line): IdentifierRuleError + { + if ($line !== null) { + $error->line($line); + } + + return $error->build(); + } + public function isReturnTypeCompatible(Type $methodParameterType, Type $prototypeParameterType, bool $supportsCovariance): bool { + // void can only override void or a missing return type, mixed does not include it + if ( + $methodParameterType instanceof MixedType + && $methodParameterType->isExplicitMixed() + && $prototypeParameterType->isVoid()->yes() + ) { + return false; + } + return $this->isTypeCompatible($methodParameterType, $prototypeParameterType, $supportsCovariance, true); } diff --git a/src/Rules/Methods/OverridingMethodCheck.php b/src/Rules/Methods/OverridingMethodCheck.php new file mode 100644 index 00000000000..bc778980a2a --- /dev/null +++ b/src/Rules/Methods/OverridingMethodCheck.php @@ -0,0 +1,241 @@ + + */ + public function checkOverrideAttributeWithoutPrototype( + ExtendedMethodReflection $method, + Node\Stmt\ClassMethod|Node\PropertyHook $node, + ): array + { + if (!self::hasOverrideAttribute($node->attrGroups)) { + return []; + } + + return [ + RuleErrorBuilder::message(sprintf( + '%s has #[\Override] attribute but does not override any %s.', + ucfirst(self::describeMethod($method, $method->getDeclaringClass())), + self::isPropertyHook($method) ? sprintf('%s hook', $method->getPropertyHookName()) : 'method', + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.override') + ->fixNode($node, static function (Node\Stmt\ClassMethod|Node\PropertyHook $method) { + $method->attrGroups = self::filterOverrideAttribute($method->attrGroups); + return $method; + }) + ->build(), + ]; + } + + /** + * Checks the parts of overriding that do not depend on the signature: + * the #[\Override] attribute, final, static, and abstract modifiers, and returning by reference. + * + * @param ExtendedMethodReflection $prototype the method the signature is checked against + * @param ExtendedMethodReflection $inheritancePrototype the method the final keyword and the #[\Override] attribute are checked against + * @return list + */ + public function checkInheritance( + ExtendedMethodReflection $method, + Node\Stmt\ClassMethod|Node\PropertyHook $node, + ExtendedMethodReflection $prototype, + ClassReflection $prototypeDeclaringClass, + ExtendedMethodReflection $inheritancePrototype, + ClassReflection $inheritancePrototypeDeclaringClass, + bool $reportMissingOverrideAttribute, + ): array + { + $messages = []; + if ( + $reportMissingOverrideAttribute + && !self::hasOverrideAttribute($node->attrGroups) + ) { + $messages[] = RuleErrorBuilder::message(sprintf( + '%s overrides %s but is missing the #[\Override] attribute.', + ucfirst(self::describeMethod($method, $method->getDeclaringClass())), + self::describeMethod($inheritancePrototype, $inheritancePrototypeDeclaringClass, true), + )) + ->line($node->getStartLine()) + ->identifier('method.missingOverride') + ->fixNode($node, static function (Node\Stmt\ClassMethod|Node\PropertyHook $method) { + $method->attrGroups[] = new Node\AttributeGroup([ + new Attribute(new Node\Name\FullyQualified('Override')), + ]); + + return $method; + }) + ->build(); + } + if ($inheritancePrototype->isFinalByKeyword()->yes()) { + $messages[] = RuleErrorBuilder::message(sprintf( + '%s overrides final %s.', + ucfirst(self::describeMethod($method, $method->getDeclaringClass())), + self::describeMethod($inheritancePrototype, $inheritancePrototypeDeclaringClass, true), + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.parentMethodFinal') + ->build(); + } elseif ($inheritancePrototype->isFinal()->yes()) { + $messages[] = RuleErrorBuilder::message(sprintf( + '%s overrides @final %s.', + ucfirst(self::describeMethod($method, $method->getDeclaringClass())), + self::describeMethod($inheritancePrototype, $inheritancePrototypeDeclaringClass, true), + )) + ->line($node->getStartLine()) + ->identifier('method.parentMethodFinalByPhpDoc') + ->build(); + } + + if ($prototype->isStatic()) { + if (!$method->isStatic()) { + $messages[] = RuleErrorBuilder::message(sprintf( + 'Non-static method %s::%s() overrides static method %s::%s().', + $method->getDeclaringClass()->getDisplayName(), + $method->getName(), + $prototypeDeclaringClass->getDisplayName(true), + $prototype->getName(), + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.nonStatic') + ->build(); + } + } elseif ($method->isStatic()) { + $messages[] = RuleErrorBuilder::message(sprintf( + 'Static method %s::%s() overrides non-static method %s::%s().', + $method->getDeclaringClass()->getDisplayName(), + $method->getName(), + $prototypeDeclaringClass->getDisplayName(true), + $prototype->getName(), + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.static') + ->build(); + } + + $methodAbstract = $method->isAbstract(); + $prototypeAbstract = $prototype->isAbstract(); + if ( + (is_bool($methodAbstract) ? $methodAbstract : $methodAbstract->yes()) + && !(is_bool($prototypeAbstract) ? $prototypeAbstract : $prototypeAbstract->yes()) + ) { + $messages[] = RuleErrorBuilder::message(sprintf( + 'Cannot make non-abstract %s abstract in class %s.', + self::describeMethod($prototype, $prototypeDeclaringClass, true), + $method->getDeclaringClass()->getDisplayName(), + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.abstractOverridingNonAbstract') + ->build(); + } + + if ($prototype->returnsByReference()->yes() && !$method->returnsByReference()->yes()) { + $messages[] = RuleErrorBuilder::message(sprintf( + '%s overriding %s that returns by reference should also return by reference.', + ucfirst(self::describeMethod($method, $method->getDeclaringClass())), + self::describeMethod($prototype, $prototypeDeclaringClass, true), + )) + ->line($node->getStartLine()) + ->nonIgnorable() + ->identifier('method.returnByRef') + ->build(); + } + + return $messages; + } + + /** + * Describes a method as "method Foo::bar()" and a property hook as "get hook for property Foo::$bar". + */ + public static function describeMethod(ExtendedMethodReflection $method, ClassReflection $declaringClass, bool $displayGenerics = false): string + { + if (self::isPropertyHook($method)) { + return sprintf( + '%s hook for property %s::$%s', + $method->getPropertyHookName(), + $declaringClass->getDisplayName($displayGenerics), + $method->getHookedPropertyName(), + ); + } + + return sprintf('method %s::%s()', $declaringClass->getDisplayName($displayGenerics), $method->getName()); + } + + /** + * @phpstan-assert-if-true PhpMethodReflection|PhpMethodFromParserNodeReflection $method + */ + private static function isPropertyHook(ExtendedMethodReflection $method): bool + { + return ($method instanceof PhpMethodReflection || $method instanceof PhpMethodFromParserNodeReflection) + && $method->isPropertyHook(); + } + + /** + * @param Node\AttributeGroup[] $attrGroups + */ + public static function hasOverrideAttribute(array $attrGroups): bool + { + foreach ($attrGroups as $attrGroup) { + foreach ($attrGroup->attrs as $attr) { + if ($attr->name->toLowerString() === 'override') { + return true; + } + } + } + + return false; + } + + /** + * @param Node\AttributeGroup[] $attrGroups + * @return Node\AttributeGroup[] + */ + public static 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; + } + +} diff --git a/src/Rules/Methods/OverridingMethodRule.php b/src/Rules/Methods/OverridingMethodRule.php index 02d1a3447f2..9e46f1f9f83 100644 --- a/src/Rules/Methods/OverridingMethodRule.php +++ b/src/Rules/Methods/OverridingMethodRule.php @@ -3,7 +3,6 @@ namespace PHPStan\Rules\Methods; use PhpParser\Node; -use PhpParser\Node\Attribute; use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\NodeCallbackInvoker; @@ -42,6 +41,7 @@ public function __construct( private MethodParameterComparisonHelper $methodParameterComparisonHelper, private MethodVisibilityComparisonHelper $methodVisibilityComparisonHelper, private MethodPrototypeFinder $methodPrototypeFinder, + private OverridingMethodCheck $overridingMethodCheck, #[AutowiredParameter] private bool $checkMissingOverrideMethodAttribute, #[AutowiredParameter(ref: '%featureToggles.checkWholePhpVersionRange%')] @@ -115,24 +115,7 @@ public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataE } } - if ($this->hasOverrideAttribute($node->getOriginalNode())) { - return [ - RuleErrorBuilder::message(sprintf( - 'Method %s::%s() has #[\Override] attribute but does not override any method.', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - )) - ->nonIgnorable() - ->identifier('method.override') - ->fixNode($node->getOriginalNode(), function (Node\Stmt\ClassMethod $method) { - $method->attrGroups = $this->filterOverrideAttribute($method->attrGroups); - return $method; - }) - ->build(), - ]; - } - - return []; + return $this->overridingMethodCheck->checkOverrideAttributeWithoutPrototype($method, $node->getOriginalNode()); } [ @@ -143,92 +126,15 @@ public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataE $inheritancePrototypeDeclaringClass, ] = $prototypeData; - $messages = []; - if ( - $this->checkMissingOverrideMethodAttribute - && !$scope->isInTrait() - && !$this->hasOverrideAttribute($node->getOriginalNode()) - ) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() overrides method %s::%s() but is missing the #[\Override] attribute.', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $inheritancePrototypeDeclaringClass->getDisplayName(true), - $inheritancePrototype->getName(), - )) - ->identifier('method.missingOverride') - ->fixNode($node->getOriginalNode(), static function (Node\Stmt\ClassMethod $method) { - $method->attrGroups[] = new Node\AttributeGroup([ - new Attribute(new Node\Name\FullyQualified('Override')), - ]); - - return $method; - }) - ->build(); - } - if ($inheritancePrototype->isFinalByKeyword()->yes()) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() overrides final method %s::%s().', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $inheritancePrototypeDeclaringClass->getDisplayName(true), - $inheritancePrototype->getName(), - )) - ->nonIgnorable() - ->identifier('method.parentMethodFinal') - ->build(); - } elseif ($inheritancePrototype->isFinal()->yes()) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() overrides @final method %s::%s().', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $inheritancePrototypeDeclaringClass->getDisplayName(true), - $inheritancePrototype->getName(), - ))->identifier('method.parentMethodFinalByPhpDoc') - ->build(); - } - - if ($prototype->isStatic()) { - if (!$method->isStatic()) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Non-static method %s::%s() overrides static method %s::%s().', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), - )) - ->nonIgnorable() - ->identifier('method.nonStatic') - ->build(); - } - } elseif ($method->isStatic()) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Static method %s::%s() overrides non-static method %s::%s().', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), - )) - ->nonIgnorable() - ->identifier('method.static') - ->build(); - } - - $prototypeAbstract = $prototype->isAbstract(); - if ( - $method->isAbstract()->yes() - && !(is_bool($prototypeAbstract) ? $prototypeAbstract : $prototypeAbstract->yes()) - ) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Cannot make non-abstract method %s::%s() abstract in class %s.', - $prototypeDeclaringClass->getDisplayName(true), - $prototype->getName(), - $method->getDeclaringClass()->getDisplayName(), - )) - ->nonIgnorable() - ->identifier('method.abstractOverridingNonAbstract') - ->build(); - } + $messages = $this->overridingMethodCheck->checkInheritance( + $method, + $node->getOriginalNode(), + $prototype, + $prototypeDeclaringClass, + $inheritancePrototype, + $inheritancePrototypeDeclaringClass, + $this->checkMissingOverrideMethodAttribute && !$scope->isInTrait(), + ); if ($checkVisibility) { $messages = array_merge($messages, $this->methodVisibilityComparisonHelper->compare($prototype, $prototypeDeclaringClass, $method, $node->getOriginalNode())); @@ -351,30 +257,6 @@ public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataE return $this->addErrors($messages, $node, $scope); } - /** - * @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 list $errors * @return list @@ -409,17 +291,4 @@ private function hasReturnTypeWillChangeAttribute(Node\Stmt\ClassMethod $method) return false; } - private function hasOverrideAttribute(Node\Stmt\ClassMethod $method): bool - { - foreach ($method->attrGroups as $attrGroup) { - foreach ($attrGroup->attrs as $attr) { - if ($attr->name->toLowerString() === 'override') { - return true; - } - } - } - - return false; - } - } diff --git a/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php b/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php index 48d04bc3b1c..cabf932276e 100644 --- a/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php @@ -44,6 +44,7 @@ protected function getRule(): Rule new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), new MethodPrototypeFinder($phpVersion, $phpClassReflectionExtension), + new OverridingMethodCheck(), false, true, ), diff --git a/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php b/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php index 9aae88076b4..e4038a73cf2 100644 --- a/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php @@ -34,6 +34,7 @@ protected function getRule(): Rule new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), new MethodPrototypeFinder($phpVersion, $phpClassReflectionExtension), + new OverridingMethodCheck(), false, true, ); diff --git a/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php b/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php index cc3721f3792..3c80b439609 100644 --- a/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php +++ b/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php @@ -26,6 +26,7 @@ protected function getRule(): Rule new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), new MethodPrototypeFinder($phpVersion, $phpClassReflectionExtension), + new OverridingMethodCheck(), false, true, ); diff --git a/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php b/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php index 1d307c840c6..04968069694 100644 --- a/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php +++ b/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php @@ -35,6 +35,7 @@ protected function getRule(): Rule new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), new MethodPrototypeFinder($phpVersion, $phpClassReflectionExtension), + new OverridingMethodCheck(), $this->checkMissingOverrideMethodAttribute, true, ); @@ -900,4 +901,31 @@ public function testEngineProvidedEnumMethodsWinOverTraitMethods(): void $this->analyse([__DIR__ . '/data/backed-enum-from-trait.php'], []); } + public function testReturnByRef(): void + { + $this->phpVersionId = PHP_VERSION_ID; + $this->analyse([__DIR__ . '/data/overriding-method-return-by-ref.php'], [ + [ + 'Method OverridingMethodReturnByRef\Bar::byRef() overriding method OverridingMethodReturnByRef\Foo::byRef() that returns by reference should also return by reference.', + 24, + ], + [ + 'Method OverridingMethodReturnByRef\ImplementsByRefInterface::get() overriding method OverridingMethodReturnByRef\ByRefInterface::get() that returns by reference should also return by reference.', + 58, + ], + ]); + } + + #[RequiresPhp('>= 8.1.0')] + public function testVoidOverridingMixed(): void + { + $this->phpVersionId = PHP_VERSION_ID; + $this->analyse([__DIR__ . '/data/overriding-method-void-mixed.php'], [ + [ + 'Return type void of method OverridingMethodVoidMixed\Bar::explicitMixed() is not covariant with return type mixed of method OverridingMethodVoidMixed\Foo::explicitMixed().', + 28, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Methods/data/overriding-method-return-by-ref.php b/tests/PHPStan/Rules/Methods/data/overriding-method-return-by-ref.php new file mode 100644 index 00000000000..9b9cb4ffd77 --- /dev/null +++ b/tests/PHPStan/Rules/Methods/data/overriding-method-return-by-ref.php @@ -0,0 +1,63 @@ += 8.0 + +namespace OverridingMethodVoidMixed; + +class Foo +{ + + public function explicitMixed(): mixed + { + return 1; + } + + public function noReturnType() + { + return 1; + } + + public function explicitMixedToNever(): mixed + { + return 1; + } + +} + +class Bar extends Foo +{ + + public function explicitMixed(): void + { + } + + public function noReturnType(): void + { + } + + public function explicitMixedToNever(): never + { + throw new \Exception(); + } + +} diff --git a/tests/PHPStan/Rules/Playground/PromoteParameterRuleWithOriginalRuleTest.php b/tests/PHPStan/Rules/Playground/PromoteParameterRuleWithOriginalRuleTest.php index ed158dfa17f..3f391486a69 100644 --- a/tests/PHPStan/Rules/Playground/PromoteParameterRuleWithOriginalRuleTest.php +++ b/tests/PHPStan/Rules/Playground/PromoteParameterRuleWithOriginalRuleTest.php @@ -8,6 +8,7 @@ use PHPStan\Rules\Methods\MethodPrototypeFinder; use PHPStan\Rules\Methods\MethodSignatureRule; use PHPStan\Rules\Methods\MethodVisibilityComparisonHelper; +use PHPStan\Rules\Methods\OverridingMethodCheck; use PHPStan\Rules\Methods\OverridingMethodRule; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; @@ -30,6 +31,7 @@ protected function getRule(): Rule $container->getByType(MethodParameterComparisonHelper::class), $container->getByType(MethodVisibilityComparisonHelper::class), $container->getByType(MethodPrototypeFinder::class), + $container->getByType(OverridingMethodCheck::class), true, true, ), From c2cca4b46a651bb294cfa9e8814d6ba3eb7afe79 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Sun, 15 Nov 2026 14:46:32 +0000 Subject: [PATCH 2/3] Check overridden property hooks and asymmetric visibility in OverridingPropertyRule - set visibility can't be narrowed - hooks are checked against the overridden hooks: final, by-ref get, set parameter contravariance, abstract, #[\Override] (missing one reported with checkMissingOverrideMethodAttribute) - backed property can't implement a wider abstract set hook - get hook of a property backed by its parent can't return by reference when there's a set hook - the property is checked against every interface declaring it - iterable is the same type as array|Traversable Hooks wrong by themselves are not compared with the overridden hooks. Amp-Thread-ID: https://ampcode.com/threads/T-01a1df04-9cc5-7608-a3ae-ede0c3cf05e5 --- Makefile | 4 + .../Properties/OverridingPropertyRule.php | 339 ++++++++++++++---- .../OverridingPropertyRuleConfigPhpTest.php | 8 +- .../Properties/OverridingPropertyRuleTest.php | 164 ++++++++- .../overriding-property-equivalent-types.php | 36 ++ ...ing-property-hooks-invalid-declaration.php | 53 +++ ...riding-property-hooks-missing-override.php | 54 +++ .../data/overriding-property-hooks.php | 231 ++++++++++++ ...verriding-property-multiple-prototypes.php | 94 +++++ .../overriding-property-set-visibility.php | 79 ++++ .../data/property-hook-override-attr.php | 26 ++ .../property-hook-override-attr.php.fixed | 26 ++ 12 files changed, 1035 insertions(+), 79 deletions(-) create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-equivalent-types.php create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-hooks-invalid-declaration.php create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-hooks-missing-override.php create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-hooks.php create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-multiple-prototypes.php create mode 100644 tests/PHPStan/Rules/Properties/data/overriding-property-set-visibility.php create mode 100644 tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php create mode 100644 tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php.fixed diff --git a/Makefile b/Makefile index ddeae1f5772..32ae3cd51f9 100644 --- a/Makefile +++ b/Makefile @@ -57,6 +57,10 @@ lint: --exclude tests/PHPStan/Rules/Properties/data/read-only-property-phpdoc-and-native.php \ --exclude tests/PHPStan/Rules/Properties/data/read-only-property-readonly-class.php \ --exclude tests/PHPStan/Rules/Properties/data/overriding-property.php \ + --exclude tests/PHPStan/Rules/Properties/data/overriding-property-hooks.php \ + --exclude tests/PHPStan/Rules/Properties/data/overriding-property-hooks-invalid-declaration.php \ + --exclude tests/PHPStan/Rules/Properties/data/overriding-property-set-visibility.php \ + --exclude tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php \ --exclude tests/PHPStan/Rules/Constants/data/overriding-final-constant.php \ --exclude tests/PHPStan/Rules/Properties/data/intersection-types.php \ --exclude tests/PHPStan/Rules/Classes/data/first-class-instantiation-callable.php \ diff --git a/src/Rules/Properties/OverridingPropertyRule.php b/src/Rules/Properties/OverridingPropertyRule.php index d3f54c38a50..2009ca10241 100644 --- a/src/Rules/Properties/OverridingPropertyRule.php +++ b/src/Rules/Properties/OverridingPropertyRule.php @@ -4,13 +4,19 @@ use PhpParser\Node; use PhpParser\Node\Attribute; +use PHPStan\Analyser\CollectedDataEmitter; +use PHPStan\Analyser\NodeCallbackInvoker; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Node\ClassPropertyNode; use PHPStan\Php\PhpVersion; use PHPStan\Reflection\ClassReflection; +use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Reflection\Php\PhpPropertyReflection; +use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Rules\Methods\MethodParameterComparisonHelper; +use PHPStan\Rules\Methods\OverridingMethodCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\VerbosityLevel; @@ -25,8 +31,14 @@ final class OverridingPropertyRule implements Rule { + private const VISIBILITY_PUBLIC = 0; + private const VISIBILITY_PROTECTED = 1; + private const VISIBILITY_PRIVATE = 2; + public function __construct( private PhpVersion $phpVersion, + private OverridingMethodCheck $overridingMethodCheck, + private MethodParameterComparisonHelper $methodParameterComparisonHelper, #[AutowiredParameter] private bool $checkPhpDocMethodSignatures, #[AutowiredParameter(ref: '%reportMaybesInPropertyPhpDocTypes%')] @@ -44,37 +56,49 @@ public function getNodeType(): string return ClassPropertyNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&NodeCallbackInvoker&CollectedDataEmitter $scope): array { $classReflection = $node->getClassReflection(); - $prototype = $this->findPrototype($classReflection, $node->getName()); - if ($prototype === null) { - if ($this->hasOverrideAttribute($node->getAttrGroups())) { + $propertyReflection = $classReflection->getNativeProperty($node->getName()); + $prototypes = $this->findPrototypes($classReflection, $node->getName()); + + $errors = []; + foreach ($this->getDeclaredHooks($node) as $hookName => $hookNode) { + // a backed property has a get operation, and a set operation unless it's readonly, even without hooks + foreach ($prototypes as $prototype) { + if ($hookName === 'get' ? $prototype->isReadable() : $prototype->isWritable()) { + continue 2; + } + } + + $errors = array_merge($errors, $this->overridingMethodCheck->checkOverrideAttributeWithoutPrototype($propertyReflection->getHook($hookName), $hookNode)); + } + + if (count($prototypes) === 0) { + if (OverridingMethodCheck::hasOverrideAttribute($node->getAttrGroups())) { $originalNode = $node->getOriginalNode(); if ($originalNode instanceof Node\Stmt\Property) { /** @var Node\Stmt\Property $originalNode */ $originalNode = $originalNode->getAttribute('originalPropertyStmt'); } - return [ - RuleErrorBuilder::message(sprintf( - 'Property %s::$%s has #[\Override] attribute but does not override any property.', - $node->getClassReflection()->getDisplayName(), - $node->getName(), - )) - ->nonIgnorable() - ->identifier('property.override') - ->fixNode($originalNode, function ($property) { - $property->attrGroups = $this->filterOverrideAttribute($property->attrGroups); - return $property; - }) - ->build(), - ]; + $errors[] = RuleErrorBuilder::message(sprintf( + 'Property %s::$%s has #[\Override] attribute but does not override any property.', + $node->getClassReflection()->getDisplayName(), + $node->getName(), + )) + ->nonIgnorable() + ->identifier('property.override') + ->fixNode($originalNode, static function ($property) { + $property->attrGroups = OverridingMethodCheck::filterOverrideAttribute($property->attrGroups); + return $property; + }) + ->build(); } - return []; + + return $errors; } - $errors = []; if ( ( $this->checkMissingOverridePropertyAttribute === true @@ -85,7 +109,7 @@ public function processNode(Node $node, Scope $scope): array ) ) && !$scope->isInTrait() - && !$this->hasOverrideAttribute($node->getAttrGroups()) + && !OverridingMethodCheck::hasOverrideAttribute($node->getAttrGroups()) ) { $originalNode = $node->getOriginalNode(); if ($originalNode instanceof Node\Stmt\Property) { @@ -96,8 +120,8 @@ public function processNode(Node $node, Scope $scope): array 'Property %s::$%s overrides property %s::$%s but is missing the #[\Override] attribute.', $node->getClassReflection()->getDisplayName(), $node->getName(), - $prototype->getDeclaringClass()->getDisplayName(), - $prototype->getName(), + $prototypes[0]->getDeclaringClass()->getDisplayName(), + $prototypes[0]->getName(), )) ->identifier('property.missingOverride') ->fixNode($originalNode, static function ($property) { @@ -109,6 +133,46 @@ public function processNode(Node $node, Scope $scope): array }) ->build(); } + + $getHookNode = $this->getDeclaredHooks($node)['get'] ?? null; + if ( + $this->phpVersion->supportsPropertyHooks() + && $getHookNode !== null + && $getHookNode->byRef + && $propertyReflection->isVirtual()->no() + && $propertyReflection->hasHook('set') + ) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'Get hook of backed property %s::$%s with set hook cannot return by reference.', + $classReflection->getDisplayName(), + $node->getName(), + )) + ->line($getHookNode->getStartLine()) + ->nonIgnorable() + ->identifier('property.backedGetHookByRef') + ->build(); + } + + foreach ($prototypes as $prototype) { + $errors = array_merge($errors, $this->processPrototype($node, $prototype, $prototypes, $scope)); + } + + return $errors; + } + + /** + * @param list $prototypes + * @return list + */ + private function processPrototype( + ClassPropertyNode $node, + PhpPropertyReflection $prototype, + array $prototypes, + Scope&NodeCallbackInvoker&CollectedDataEmitter $scope, + ): array + { + $classReflection = $node->getClassReflection(); + $errors = []; if ($prototype->isStatic()) { if (!$node->isStatic()) { $errors[] = RuleErrorBuilder::message(sprintf( @@ -155,6 +219,7 @@ public function processNode(Node $node, Scope $scope): array } $propertyReflection = $classReflection->getNativeProperty($node->getName()); + $setHookParameterErrors = []; if ($this->phpVersion->supportsPropertyHooks()) { if ($prototype->isReadable()) { if (!$propertyReflection->isReadable()) { @@ -178,22 +243,55 @@ public function processNode(Node $node, Scope $scope): array ))->identifier('property.notWritable')->nonIgnorable()->build(); } } - if ($node->isAbstract() && $prototype->isAbstract()->no()) { - foreach (['get', 'set'] as $hookType) { - if (!$propertyReflection->hasHook($hookType) || !$prototype->hasHook($hookType)) { - continue; - } + + foreach ($this->getDeclaredHooks($node) as $hookName => $hookNode) { + if (!$prototype->hasHook($hookName)) { + continue; + } + + $hook = $propertyReflection->getHook($hookName); + $prototypeHook = $prototype->getHook($hookName); + + // BetterReflection does not mark hooks of abstract properties abstract, + // so OverridingMethodCheck::checkInheritance() does not see this + if ($hookNode->body === null && $node->isAbstract() && $prototype->isAbstract()->no()) { $errors[] = RuleErrorBuilder::message(sprintf( - 'Cannot make non-abstract method %s::$%s::%s() abstract in class %s.', - $prototype->getDeclaringClass()->getDisplayName(true), - $node->getName(), - $hookType, + 'Cannot make non-abstract %s abstract in class %s.', + OverridingMethodCheck::describeMethod($prototypeHook, $prototypeHook->getDeclaringClass(), true), $classReflection->getDisplayName(), )) + ->line($hookNode->getStartLine()) ->nonIgnorable() ->identifier('property.abstractOverridingNonAbstractHook') ->build(); } + + // visibility is the visibility of the property, compared below + $errors = array_merge($errors, $this->overridingMethodCheck->checkInheritance( + $hook, + $hookNode, + $prototypeHook, + $prototypeHook->getDeclaringClass(), + $prototypeHook, + $prototypeHook->getDeclaringClass(), + $this->checkMissingOverrideMethodAttribute + && !$scope->isInTrait() + && $this->findFirstPrototypeWithHook($prototypes, $hookName) === $prototype, + )); + + // the get hook returns the property type, compared below + if ( + $hookName !== 'set' + || !$this->isSetHookDeclarationValid($propertyReflection, $hook) + || !$this->isSetHookDeclarationValid($prototype, $prototypeHook) + ) { + continue; + } + + $setHookParameterErrors = array_merge( + $setHookParameterErrors, + $this->methodParameterComparisonHelper->compare($prototypeHook, $prototypeHook->getDeclaringClass(), $hook, $scope, false, $hookNode->getStartLine()), + ); } } @@ -218,6 +316,29 @@ public function processNode(Node $node, Scope $scope): array ))->identifier('property.visibility')->nonIgnorable()->build(); } + if ( + ($propertyReflection->isPrivateSet() || $propertyReflection->isProtectedSet()) + // a get-only virtual property does not have set visibility to respect + && !($prototype->isVirtual()->yes() && !$prototype->hasHook('set')) + // already reported as readonly property overriding readwrite property + && !($node->isReadOnly() && !$prototype->isReadOnly()) + ) { + $prototypeSetVisibility = $this->getSetVisibility($prototype); + $setVisibility = $this->getSetVisibility($propertyReflection); + if ($setVisibility > $prototypeSetVisibility) { + $errors[] = RuleErrorBuilder::message(sprintf( + '%s(set) property %s::$%s overriding %s(set) property %s::$%s should %s.', + $setVisibility === self::VISIBILITY_PRIVATE ? 'Private' : 'Protected', + $classReflection->getDisplayName(), + $node->getName(), + $prototypeSetVisibility === self::VISIBILITY_PUBLIC ? 'public' : 'protected', + $prototype->getDeclaringClass()->getDisplayName(), + $node->getName(), + $prototypeSetVisibility === self::VISIBILITY_PUBLIC ? 'also be public(set)' : 'be protected(set) or public(set)', + ))->identifier('property.setVisibility')->nonIgnorable()->build(); + } + } + if ($prototype->isFinalByKeyword()->yes()) { $errors[] = RuleErrorBuilder::message(sprintf( 'Property %s::$%s overrides final property %s::$%s.', @@ -253,7 +374,11 @@ public function processNode(Node $node, Scope $scope): array $prototype->getNativeType()->describe(VerbosityLevel::typeOnly()), ))->identifier('property.missingNativeType')->nonIgnorable()->build(); } else { - if (!$prototype->getNativeType()->equals($nativeType)) { + if ( + // iterable is the same type as array|Traversable + !$prototype->getNativeType()->isSuperTypeOf($nativeType)->yes() + || !$nativeType->isSuperTypeOf($prototype->getNativeType())->yes() + ) { if ( $this->phpVersion->supportsPropertyHooks() && ($prototype->isVirtual()->yes() || $prototype->isAbstract()->yes()) @@ -306,6 +431,34 @@ public function processNode(Node $node, Scope $scope): array ))->identifier('property.extraNativeType')->nonIgnorable()->build(); } + if (count($typeErrors) === 0) { + // an implicit set hook parameter has the property type, so it's already reported + $typeErrors = $setHookParameterErrors; + } + + if ( + count($typeErrors) === 0 + && $this->phpVersion->supportsPropertyHooks() + && $prototype->isAbstract()->yes() + && $prototype->hasHook('set') + && $propertyReflection->isVirtual()->no() + && !isset($this->getDeclaredHooks($node)['set']) + ) { + // the backed property itself implements the abstract set hook, so it has to accept everything the hook does + $prototypeSetType = $prototype->getHook('set')->getOnlyVariant()->getParameters()[0]->getNativeType(); + if (!$propertyReflection->getNativeType()->isSuperTypeOf($prototypeSetType)->yes()) { + $typeErrors[] = RuleErrorBuilder::message(sprintf( + 'Type %s of property %s::$%s is not contravariant with set hook parameter type %s of overridden property %s::$%s.', + $propertyReflection->getNativeType()->describe(VerbosityLevel::typeOnly()), + $classReflection->getDisplayName(), + $node->getName(), + $prototypeSetType->describe(VerbosityLevel::typeOnly()), + $prototype->getDeclaringClass()->getDisplayName(), + $node->getName(), + ))->identifier('property.nativeType')->nonIgnorable()->build(); + } + } + $errors = array_merge($errors, $typeErrors); if (!$this->checkPhpDocMethodSignatures) { @@ -316,7 +469,10 @@ public function processNode(Node $node, Scope $scope): array return $errors; } - if ($prototype->getReadableType()->equals($propertyReflection->getReadableType())) { + if ( + $prototype->getReadableType()->isSuperTypeOf($propertyReflection->getReadableType())->yes() + && $propertyReflection->getReadableType()->isSuperTypeOf($prototype->getReadableType())->yes() + ) { return $errors; } @@ -402,76 +558,113 @@ public function processNode(Node $node, Scope $scope): array return $errors; } - private function findPrototype(ClassReflection $classReflection, string $propertyName): ?PhpPropertyReflection + /** + * @return self::VISIBILITY_* + */ + private function getSetVisibility(PhpPropertyReflection $property): int { - $parentClass = $classReflection->getParentClass(); - if ($parentClass === null) { - return $this->findPrototypeInInterfaces($classReflection, $propertyName); - } - - if (!$parentClass->hasNativeProperty($propertyName)) { - return $this->findPrototypeInInterfaces($classReflection, $propertyName); + if ($property->isPrivateSet() || $property->isPrivate()) { + return self::VISIBILITY_PRIVATE; } - $property = $parentClass->getNativeProperty($propertyName); - if ($property->isPrivate()) { - return $this->findPrototypeInInterfaces($classReflection, $propertyName); + if ($property->isProtectedSet() || !$property->isPublic()) { + return self::VISIBILITY_PROTECTED; } - return $property; + return self::VISIBILITY_PUBLIC; } - private function findPrototypeInInterfaces(ClassReflection $classReflection, string $propertyName): ?PhpPropertyReflection + /** + * Every property the declared property has to be compatible with: the parent class property, + * and the properties of interfaces the parent class does not already implement. + * + * @return list + */ + private function findPrototypes(ClassReflection $classReflection, string $propertyName): array { - foreach ($classReflection->getInterfaces() as $interface) { + $prototypes = []; + $parentInterfaces = []; + $parentClass = $classReflection->getParentClass(); + if ($parentClass !== null) { + $parentInterfaces = $parentClass->getInterfaces(); + if ($parentClass->hasNativeProperty($propertyName)) { + $property = $parentClass->getNativeProperty($propertyName); + if (!$property->isPrivate()) { + $prototypes[] = $property; + } + } + } + + foreach ($classReflection->getInterfaces() as $interfaceName => $interface) { + if (isset($parentInterfaces[$interfaceName])) { + continue; + } if (!$interface->hasNativeProperty($propertyName)) { continue; } - return $interface->getNativeProperty($propertyName); + $property = $interface->getNativeProperty($propertyName); + if ($property->getDeclaringClass()->getName() !== $interface->getName()) { + // inherited from a parent interface which is checked separately + continue; + } + + $prototypes[] = $property; } - return null; + return $prototypes; } /** - * @param Node\AttributeGroup[] $attrGroups - * @return Node\AttributeGroup[] + * @return array<'get'|'set', Node\PropertyHook> */ - private function filterOverrideAttribute(array $attrGroups): array + private function getDeclaredHooks(ClassPropertyNode $node): array { - foreach ($attrGroups as $i => $attrGroup) { - foreach ($attrGroup->attrs as $j => $attr) { - if ($attr->name->toLowerString() !== 'override') { - continue; - } + $hooks = []; + foreach ($node->getHooks() as $hook) { + $hookName = $hook->name->toLowerString(); + if ($hookName !== 'get' && $hookName !== 'set') { + continue; + } - unset($attrGroup->attrs[$j]); - if (count($attrGroup->attrs) !== 0) { - continue; - } + $hooks[$hookName] = $hook; + } - unset($attrGroups[$i]); + return $hooks; + } + + /** + * @param list $prototypes + * @param 'get'|'set' $hookName + */ + private function findFirstPrototypeWithHook(array $prototypes, string $hookName): ?PhpPropertyReflection + { + foreach ($prototypes as $prototype) { + if ($prototype->hasHook($hookName)) { + return $prototype; } } - return $attrGroups; + return null; } /** - * @param Node\AttributeGroup[] $attrGroups + * A set hook wrong by itself is reported by other rules like SetPropertyHookParameterRule, + * comparing it with the overridden hook would report the same mistake again. */ - private function hasOverrideAttribute(array $attrGroups): bool + private function isSetHookDeclarationValid(PhpPropertyReflection $property, ExtendedMethodReflection $setHook): bool { - foreach ($attrGroups as $attrGroup) { - foreach ($attrGroup->attrs as $attr) { - if ($attr->name->toLowerString() === 'override') { - return true; - } - } + $parameters = $setHook->getOnlyVariant()->getParameters(); + if (count($parameters) !== 1) { + return false; + } + + $parameter = $parameters[0]; + if ($parameter->isOptional() || $parameter->isVariadic() || !$parameter->passedByReference()->no()) { + return false; } - return false; + return $parameter->getNativeType()->isSuperTypeOf($property->getNativeType())->yes(); } } diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php index 89986fbc3cc..42ccfe9d1f9 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php @@ -3,6 +3,8 @@ namespace PHPStan\Rules\Properties; use PHPStan\Php\PhpVersion; +use PHPStan\Rules\Methods\MethodParameterComparisonHelper; +use PHPStan\Rules\Methods\OverridingMethodCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; @@ -16,8 +18,12 @@ class OverridingPropertyRuleConfigPhpTest extends RuleTestCase protected function getRule(): Rule { + $phpVersion = self::getContainer()->getByType(PhpVersion::class); + return new OverridingPropertyRule( - self::getContainer()->getByType(PhpVersion::class), + $phpVersion, + new OverridingMethodCheck(), + new MethodParameterComparisonHelper($phpVersion), true, true, $this->checkMissingOverridePropertyAttribute, diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php index c56e405651f..9bbe1e77446 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php @@ -3,6 +3,8 @@ namespace PHPStan\Rules\Properties; use PHPStan\Php\PhpVersion; +use PHPStan\Rules\Methods\MethodParameterComparisonHelper; +use PHPStan\Rules\Methods\OverridingMethodCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -25,8 +27,12 @@ class OverridingPropertyRuleTest extends RuleTestCase protected function getRule(): Rule { + $phpVersion = self::getContainer()->getByType(PhpVersion::class); + return new OverridingPropertyRule( - self::getContainer()->getByType(PhpVersion::class), + $phpVersion, + new OverridingMethodCheck(), + new MethodParameterComparisonHelper($phpVersion), true, $this->reportMaybes, $this->checkMissingOverridePropertyAttribute, @@ -344,22 +350,170 @@ public function testBug14457(): void $this->reportMaybes = true; $this->analyse([__DIR__ . '/data/bug-14457.php'], [ [ - 'Cannot make non-abstract method Bug14457Property\ParentClass::$bar::get() abstract in class Bug14457Property\ChildClass.', + 'Cannot make non-abstract get hook for property Bug14457Property\ParentClass::$bar abstract in class Bug14457Property\ChildClass.', 10, ], [ - 'Cannot make non-abstract method Bug14457Property\SetParent::$setProp::set() abstract in class Bug14457Property\SetChild.', + 'Cannot make non-abstract set hook for property Bug14457Property\SetParent::$setProp abstract in class Bug14457Property\SetChild.', 42, ], [ - 'Cannot make non-abstract method Bug14457Property\BothParent::$bothProp::get() abstract in class Bug14457Property\BothChild.', + 'Cannot make non-abstract get hook for property Bug14457Property\BothParent::$bothProp abstract in class Bug14457Property\BothChild.', + 54, + ], + [ + 'Cannot make non-abstract set hook for property Bug14457Property\BothParent::$bothProp abstract in class Bug14457Property\BothChild.', 54, ], + ]); + } + + public function testEquivalentTypes(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/overriding-property-equivalent-types.php'], []); + } + + #[RequiresPhp('>= 8.4.0')] + public function testMultiplePrototypes(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/overriding-property-multiple-prototypes.php'], [ + [ + 'Property OverridingPropertyMultiplePrototypes\GetOnly::$prop overriding writable property OverridingPropertyMultiplePrototypes\HasSet::$prop also has to be writable.', + 29, + ], + [ + 'Type int of property OverridingPropertyMultiplePrototypes\WrongType::$prop is not covariant with type string of overridden property OverridingPropertyMultiplePrototypes\HasStringGet::$prop.', + 38, + ], [ - 'Cannot make non-abstract method Bug14457Property\BothParent::$bothProp::set() abstract in class Bug14457Property\BothChild.', + 'Property OverridingPropertyMultiplePrototypes\ChildImplementingInterface::$prop overriding writable property OverridingPropertyMultiplePrototypes\HasSet::$prop also has to be writable.', 54, ], + [ + 'Property OverridingPropertyMultiplePrototypes\ImplementsExtendsBoth::$prop overriding readable property OverridingPropertyMultiplePrototypes\HasGet::$prop also has to be readable.', + 82, + ], + ]); + } + + #[RequiresPhp('>= 8.4.0')] + public function testSetVisibility(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/overriding-property-set-visibility.php'], [ + [ + 'Private(set) property OverridingPropertySetVisibility\B::$protectedSetToPrivateSet overriding protected(set) property OverridingPropertySetVisibility\A::$protectedSetToPrivateSet should be protected(set) or public(set).', + 37, + ], + [ + 'Private(set) property OverridingPropertySetVisibility\B::$publicToPrivateSet overriding public(set) property OverridingPropertySetVisibility\A::$publicToPrivateSet should also be public(set).', + 39, + ], + [ + 'Protected(set) property OverridingPropertySetVisibility\B::$publicToProtectedSet overriding public(set) property OverridingPropertySetVisibility\A::$publicToProtectedSet should also be public(set).', + 41, + ], + [ + 'Private(set) property OverridingPropertySetVisibility\B::$protectedToProtectedPrivateSet overriding protected(set) property OverridingPropertySetVisibility\A::$protectedToProtectedPrivateSet should be protected(set) or public(set).', + 45, + ], + [ + 'Private(set) property OverridingPropertySetVisibility\B::$protectedToPublicPrivateSet overriding protected(set) property OverridingPropertySetVisibility\A::$protectedToPublicPrivateSet should be protected(set) or public(set).', + 49, + ], + [ + 'Private(set) property OverridingPropertySetVisibility\B::$readonlyToPrivateSetReadonly overriding protected(set) property OverridingPropertySetVisibility\A::$readonlyToPrivateSetReadonly should be protected(set) or public(set).', + 53, + ], + [ + 'Private(set) property OverridingPropertySetVisibility\ImplementsGetOnly::$getAndSet overriding public(set) property OverridingPropertySetVisibility\GetOnly::$getAndSet should also be public(set).', + 77, + ], + ]); + } + + #[RequiresPhp('>= 8.4.0')] + public function testHooks(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/overriding-property-hooks.php'], [ + [ + 'Get hook for property OverridingPropertyHooks\FinalHookChild::$prop overrides final get hook for property OverridingPropertyHooks\FinalHookParent::$prop.', + 26, + ], + [ + 'Set hook for property OverridingPropertyHooks\FinalHookChild::$setProp overrides final set hook for property OverridingPropertyHooks\FinalHookParent::$setProp.', + 30, + ], + [ + 'Get hook for property OverridingPropertyHooks\ImplementsByRefGetByValue::$prop overriding get hook for property OverridingPropertyHooks\ByRefGet::$prop that returns by reference should also return by reference.', + 52, + ], + [ + 'Get hook of backed property OverridingPropertyHooks\BackedChild::$prop with set hook cannot return by reference.', + 100, + ], + [ + 'Type string of property OverridingPropertyHooks\ImplementsSetWider::$prop is not contravariant with set hook parameter type int|string of overridden property OverridingPropertyHooks\SetWider::$prop.', + 128, + ], + [ + 'Parameter #1 $prop (OverridingPropertyHooks\Y) of set hook for property OverridingPropertyHooks\SetParameterChild::$prop is not contravariant with parameter #1 $prop (OverridingPropertyHooks\X) of set hook for property OverridingPropertyHooks\SetParameterParent::$prop.', + 178, + ], + [ + 'Get hook for property OverridingPropertyHooks\OverrideChild::$setOnly has #[\Override] attribute but does not override any get hook.', + 208, + ], + [ + 'Set hook for property OverridingPropertyHooks\OverrideChild::$getOnly has #[\Override] attribute but does not override any set hook.', + 215, + ], + [ + 'Get hook for property OverridingPropertyHooks\OverrideChild::$notInParent has #[\Override] attribute but does not override any get hook.', + 227, + ], ]); } + #[RequiresPhp('>= 8.4.0')] + public function testHookDeclarationErrorsAreNotRepeated(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/overriding-property-hooks-invalid-declaration.php'], []); + } + + #[RequiresPhp('>= 8.4.0')] + public function testHooksMissingOverride(): void + { + $this->reportMaybes = true; + $this->checkMissingOverridePropertyAttribute = false; + $this->checkMissingOverrideMethodAttribute = true; + $this->analyse([__DIR__ . '/data/overriding-property-hooks-missing-override.php'], [ + [ + 'Set hook for property OverridingPropertyHooksMissingOverride\Child::$both overrides set hook for property OverridingPropertyHooksMissingOverride\ParentClass::$both but is missing the #[\Override] attribute.', + 27, + ], + [ + 'Get hook for property OverridingPropertyHooksMissingOverride\Child::$getOnly overrides get hook for property OverridingPropertyHooksMissingOverride\ParentClass::$getOnly but is missing the #[\Override] attribute.', + 31, + ], + [ + 'Get hook for property OverridingPropertyHooksMissingOverride\ImplementsInterface::$prop overrides get hook for property OverridingPropertyHooksMissingOverride\HasHook::$prop but is missing the #[\Override] attribute.', + 51, + ], + ]); + } + + #[RequiresPhp('>= 8.4.0')] + public function testFixHookOverrideAttribute(): void + { + $this->reportMaybes = true; + $this->checkMissingOverridePropertyAttribute = false; + $this->checkMissingOverrideMethodAttribute = true; + $this->fix(__DIR__ . '/data/property-hook-override-attr.php', __DIR__ . '/data/property-hook-override-attr.php.fixed'); + } + } diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-equivalent-types.php b/tests/PHPStan/Rules/Properties/data/overriding-property-equivalent-types.php new file mode 100644 index 00000000000..744b872711d --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-equivalent-types.php @@ -0,0 +1,36 @@ += 8.0 + +namespace OverridingPropertyEquivalentTypes; + +class X {} +class Y extends X {} + +class A +{ + + public X|Y $prop; + + public iterable $iterable; + + public object|iterable $objectOrIterable; + + public object|array $objectOrArray; + + public array|\Traversable $arrayOrTraversable; + +} + +class B extends A +{ + + public X $prop; + + public array|\Traversable $iterable; + + public object|array $objectOrIterable; + + public object|iterable $objectOrArray; + + public iterable $arrayOrTraversable; + +} diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-invalid-declaration.php b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-invalid-declaration.php new file mode 100644 index 00000000000..72c217661f0 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-invalid-declaration.php @@ -0,0 +1,53 @@ += 8.4 + +namespace OverridingPropertyHooksInvalidDeclaration; + +class ParentClass +{ + + public int $wrongParameterType { + set(int|string $value) { + } + } + + public int $tooManyParameters { + set(int|string $value) { + } + } + +} + +class Child extends ParentClass +{ + + public int $wrongParameterType { + set(string $value) { + } + } + + public int $tooManyParameters { + set(int|string $value, $extra) { + } + } + +} + +class InvalidParent +{ + + public int $prop { + set(int $value, $extra) { + } + } + +} + +class ChildOfInvalidParent extends InvalidParent +{ + + public int $prop { + set(int $value) { + } + } + +} diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-missing-override.php b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-missing-override.php new file mode 100644 index 00000000000..effeb1a70bc --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks-missing-override.php @@ -0,0 +1,54 @@ += 8.4 + +namespace OverridingPropertyHooksMissingOverride; + +class ParentClass +{ + + public int $both { + get => 1; + set => $value; + } + + public int $getOnly { + get => 1; + } + + public int $backed = 1; + +} + +class Child extends ParentClass +{ + + public int $both { + #[\Override] + get => 2; + set => $value; + } + + public int $getOnly { + get => 2; + } + + public int $backed { + get => 2; + } + +} + +interface HasHook +{ + + public int $prop { get; } + +} + +class ImplementsInterface implements HasHook +{ + + public int $prop { + get => 1; + } + +} diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-hooks.php b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks.php new file mode 100644 index 00000000000..3e4da370b9a --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-hooks.php @@ -0,0 +1,231 @@ += 8.4 + +namespace OverridingPropertyHooks; + +class FinalHookParent +{ + + public int $prop { + final get => 42; + } + + public int $setProp { + final set => $value; + } + + public int $notFinal { + get => 42; + } + +} + +class FinalHookChild extends FinalHookParent +{ + + public int $prop { + get => 24; + } + + public int $setProp { + set => $value; + } + + public int $notFinal { + get => 24; + } + +} + +interface ByRefGet +{ + + public int $prop { &get; } + + public int $byValue { get; } + +} + +class ImplementsByRefGetByValue implements ByRefGet +{ + + public int $prop { + get => 1; + } + + public int $byValue { + get => 1; + } + +} + +class ImplementsByRefGetByRef implements ByRefGet +{ + + private int $storage = 1; + + public int $prop { + &get => $this->storage; + } + + public int $byValue { + &get => $this->storage; + } + +} + +class ImplementsByRefGetBacked implements ByRefGet +{ + + public int $prop = 1; + + public int $byValue = 1; + +} + +class BackedParent +{ + + public int $prop = 1; + + public int $onlyGet = 1; + +} + +class BackedChild extends BackedParent +{ + + private int $storage = 1; + + public int $prop { + &get => $this->storage; + set { + $this->storage = $value; + } + } + + public int $onlyGet { + &get => $this->storage; + } + +} + +interface SetWider +{ + + public string $prop { + set(int|string $value); + } + + public string $sameType { + set(string $value); + } + +} + +class ImplementsSetWider implements SetWider +{ + + public string $prop; + + public string $sameType; + +} + +class ImplementsSetWiderWithWideType implements SetWider +{ + + public int|string $prop; + + public string $sameType; + +} + +class ImplementsSetWiderWithHook implements SetWider +{ + + public string $prop { + set(int|string $value) { + $this->prop = (string) $value; + } + } + + public string $sameType; + +} + +interface X {} +interface Y extends X {} + +class SetParameterParent +{ + + public Y $prop { + set(X $prop) { + } + } + + public Y $other { + set(Y $value) { + } + } + +} + +class SetParameterChild extends SetParameterParent +{ + + public Y $prop { + set(Y $prop) { + } + } + + public Y $other { + set(X $value) { + } + } + +} + +class OverrideParent +{ + + public $setOnly { + set {} + } + + public $getOnly { + get => 1; + } + + public $backed; + +} + +class OverrideChild extends OverrideParent +{ + + public $setOnly { + #[\Override] + get => 1; + } + + public $getOnly { + #[\Override] + get => 2; + #[\Override] + set {} + } + + public $backed { + #[\Override] + get => $this->backed; + #[\Override] + set => $value; + } + + public $notInParent { + #[\Override] + get => 1; + } + +} diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-multiple-prototypes.php b/tests/PHPStan/Rules/Properties/data/overriding-property-multiple-prototypes.php new file mode 100644 index 00000000000..99c80706dc8 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-multiple-prototypes.php @@ -0,0 +1,94 @@ += 8.4 + +namespace OverridingPropertyMultiplePrototypes; + +interface HasGet +{ + + public int $prop { get; } + +} + +interface HasSet +{ + + public int $prop { set; } + +} + +interface HasStringGet +{ + + public string $prop { get; } + +} + +class GetOnly implements HasGet, HasSet +{ + + public int $prop { + get => 1; + } + +} + +class WrongType implements HasGet, HasStringGet +{ + + public int $prop; + +} + +class ParentWithProperty +{ + + public int $prop { + get => 1; + } + +} + +class ChildImplementingInterface extends ParentWithProperty implements HasSet +{ + + public int $prop { + get => 2; + } + +} + +class ParentImplementingInterface implements HasGet +{ + + public int $prop = 1; + +} + +class ChildOfParentImplementingInterface extends ParentImplementingInterface +{ + + public int $prop = 2; + +} + +interface ExtendsBoth extends HasGet, HasSet +{ + +} + +class ImplementsExtendsBoth implements ExtendsBoth +{ + + public int $prop { + set { + } + } + +} + +class Valid implements HasGet, HasSet +{ + + public int $prop; + +} diff --git a/tests/PHPStan/Rules/Properties/data/overriding-property-set-visibility.php b/tests/PHPStan/Rules/Properties/data/overriding-property-set-visibility.php new file mode 100644 index 00000000000..0b88c4e5409 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/overriding-property-set-visibility.php @@ -0,0 +1,79 @@ += 8.4 + +namespace OverridingPropertySetVisibility; + +class A +{ + + public protected(set) string $protectedSetToPrivateSet; + + public string $publicToPrivateSet; + + public string $publicToProtectedSet; + + public protected(set) string $protectedSetToProtectedSet; + + protected string $protectedToProtectedPrivateSet; + + protected string $protectedToPublicProtectedSet; + + protected string $protectedToPublicPrivateSet; + + public readonly string $readonlyToReadonly; + + public readonly string $readonlyToPrivateSetReadonly; + + public function __construct() + { + $this->readonlyToReadonly = ''; + $this->readonlyToPrivateSetReadonly = ''; + } + +} + +class B extends A +{ + + public private(set) string $protectedSetToPrivateSet; + + public private(set) string $publicToPrivateSet; + + public protected(set) string $publicToProtectedSet; + + public protected(set) string $protectedSetToProtectedSet; + + protected private(set) string $protectedToProtectedPrivateSet; + + public protected(set) string $protectedToPublicProtectedSet; + + public private(set) string $protectedToPublicPrivateSet; + + public readonly string $readonlyToReadonly; + + public private(set) readonly string $readonlyToPrivateSetReadonly; + + public function __construct() + { + $this->readonlyToReadonly = ''; + $this->readonlyToPrivateSetReadonly = ''; + } + +} + +interface GetOnly +{ + + public string $getOnly { get; } + + public string $getAndSet { get; set; } + +} + +class ImplementsGetOnly implements GetOnly +{ + + public private(set) string $getOnly; + + public private(set) string $getAndSet; + +} diff --git a/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php b/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php new file mode 100644 index 00000000000..090d183ae9d --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php @@ -0,0 +1,26 @@ += 8.4 + +namespace PropertyHookOverrideAttr; + +class ParentClass +{ + + public int $prop { + get => 1; + } + +} + +class Child extends ParentClass +{ + + public int $prop { + get => 2; + } + + public int $notInParent { + #[\Override] + get => 3; + } + +} diff --git a/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php.fixed b/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php.fixed new file mode 100644 index 00000000000..941592245a0 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/property-hook-override-attr.php.fixed @@ -0,0 +1,26 @@ += 8.4 + +namespace PropertyHookOverrideAttr; + +class ParentClass +{ + + public int $prop { + get => 1; + } + +} + +class Child extends ParentClass +{ + + public int $prop { + #[\Override] + get => 2; + } + + public int $notInParent { + get => 3; + } + +} From 27520abb31d387106180664e14cf09625ed05cf3 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Sun, 15 Nov 2026 14:46:32 +0000 Subject: [PATCH 3/3] Check overriding constant against all prototypes and always check native types Native type of an overriding constant is a fatal error in PHP, so it's no longer behind checkPhpDocMethodSignatures. Amp-Thread-ID: https://ampcode.com/threads/T-01a1df04-9cc5-7608-a3ae-ede0c3cf05e5 --- .../Constants/OverridingConstantRule.php | 66 ++++++++++++-- .../Constants/OverridingConstantRuleTest.php | 37 +++++++- ...verriding-constant-multiple-prototypes.php | 87 +++++++++++++++++++ 3 files changed, 179 insertions(+), 11 deletions(-) create mode 100644 tests/PHPStan/Rules/Constants/data/overriding-constant-multiple-prototypes.php diff --git a/src/Rules/Constants/OverridingConstantRule.php b/src/Rules/Constants/OverridingConstantRule.php index 783b4411409..7d305c7be52 100644 --- a/src/Rules/Constants/OverridingConstantRule.php +++ b/src/Rules/Constants/OverridingConstantRule.php @@ -49,7 +49,7 @@ public function processNode(Node $node, Scope $scope): array $errors = array_merge( $errors, $this->overrideAttributeCheck->check($scope, $node, $constantName, $prototype), - $this->processSingleConstant($scope->getClassReflection(), $constantName, $prototype), + $this->processSingleConstant($scope->getClassReflection(), $constantName), ); } @@ -59,13 +59,21 @@ public function processNode(Node $node, Scope $scope): array /** * @return list */ - private function processSingleConstant(ClassReflection $classReflection, string $constantName, ?ClassConstantReflection $prototype): array + private function processSingleConstant(ClassReflection $classReflection, string $constantName): array { - if ($prototype === null) { - return []; + $errors = []; + foreach ($this->findPrototypes($classReflection, $constantName) as $prototype) { + $errors = array_merge($errors, $this->processPrototype($classReflection, $classReflection->getConstant($constantName), $prototype)); } - $constantReflection = $classReflection->getConstant($constantName); + return $errors; + } + + /** + * @return list + */ + private function processPrototype(ClassReflection $classReflection, ClassConstantReflection $constantReflection, ClassConstantReflection $prototype): array + { $errors = []; if ($prototype->isFinal()) { $errors[] = RuleErrorBuilder::message(sprintf( @@ -98,10 +106,6 @@ private function processSingleConstant(ClassReflection $classReflection, string ))->identifier('classConstant.visibility')->nonIgnorable()->build(); } - if (!$this->checkPhpDocMethodSignatures) { - return $errors; - } - $prototypeNativeType = $prototype->getNativeType(); $constantNativeType = $constantReflection->getNativeType(); if ($prototypeNativeType !== null) { @@ -130,6 +134,10 @@ private function processSingleConstant(ClassReflection $classReflection, string } } + if (!$this->checkPhpDocMethodSignatures) { + return $errors; + } + if (!$prototype->hasPhpDocType()) { return $errors; } @@ -153,4 +161,44 @@ private function processSingleConstant(ClassReflection $classReflection, string return $errors; } + /** + * Every constant the declared constant has to be compatible with: the parent class constant, + * and the constants of interfaces the parent class does not already implement. + * + * @return list + */ + private function findPrototypes(ClassReflection $classReflection, string $constantName): array + { + $prototypes = []; + $parentClass = $classReflection->getParentClass(); + $parentInterfaces = $parentClass !== null ? $parentClass->getInterfaces() : []; + foreach ($classReflection->getInterfaces() as $interfaceName => $interface) { + if (isset($parentInterfaces[$interfaceName])) { + continue; + } + if (!$interface->hasConstant($constantName)) { + continue; + } + + $constant = $interface->getConstant($constantName); + if ($constant->getDeclaringClass()->getName() !== $interface->getName()) { + // inherited from a parent interface which is checked separately + continue; + } + + $prototypes[] = $constant; + } + + if ($parentClass === null || !$parentClass->hasConstant($constantName)) { + return $prototypes; + } + + $constant = $parentClass->getConstant($constantName); + if (!$constant->isPrivate()) { + $prototypes[] = $constant; + } + + return $prototypes; + } + } diff --git a/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php b/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php index 127f60490e0..65d745b31f4 100644 --- a/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php +++ b/tests/PHPStan/Rules/Constants/OverridingConstantRuleTest.php @@ -14,6 +14,8 @@ class OverridingConstantRuleTest extends RuleTestCase { + private bool $checkPhpDocMethodSignatures = true; + private ?bool $checkMissingOverrideConstantAttribute = null; private ?bool $checkMissingOverridePropertyAttribute = null; @@ -23,7 +25,7 @@ class OverridingConstantRuleTest extends RuleTestCase protected function getRule(): Rule { return new OverridingConstantRule( - true, + $this->checkPhpDocMethodSignatures, new OverrideAttributeOnClassConstantCheck( $this->checkMissingOverrideConstantAttribute, $this->checkMissingOverridePropertyAttribute, @@ -107,9 +109,17 @@ public function testFinal(): void $this->analyse([__DIR__ . '/data/overriding-final-constant.php'], $errors); } + public static function dataNativeTypes(): iterable + { + yield [true]; + yield [false]; + } + #[RequiresPhp('>= 8.3.0')] - public function testNativeTypes(): void + #[DataProvider('dataNativeTypes')] + public function testNativeTypes(bool $checkPhpDocMethodSignatures): void { + $this->checkPhpDocMethodSignatures = $checkPhpDocMethodSignatures; $this->analyse([__DIR__ . '/data/overriding-constant-native-types.php'], [ [ 'Native type int|string of constant OverridingConstantNativeTypes\Bar::D is not covariant with native type int of constant OverridingConstantNativeTypes\Foo::D.', @@ -224,4 +234,27 @@ public function testFixOverrideAttribute(): void $this->fix(__DIR__ . '/data/constant-override-attr-fix.php', __DIR__ . '/data/constant-override-attr-fix.php.fixed'); } + #[RequiresPhp('>= 8.1.0')] + public function testMultiplePrototypes(): void + { + $this->analyse([__DIR__ . '/data/overriding-constant-multiple-prototypes.php'], [ + [ + 'Constant OverridingConstantMultiplePrototypes\ImplementsBoth::C overrides final constant OverridingConstantMultiplePrototypes\IsFinal::C.', + 22, + ], + [ + 'Constant OverridingConstantMultiplePrototypes\ExtendsAndImplementsFinal::C overrides final constant OverridingConstantMultiplePrototypes\IsFinal::C.', + 38, + ], + [ + 'Protected constant OverridingConstantMultiplePrototypes\ExtendsAndImplementsPublic::D overriding public constant OverridingConstantMultiplePrototypes\PublicD::D should also be public.', + 52, + ], + [ + 'Constant OverridingConstantMultiplePrototypes\ExtendsFinalAndImplements::E overrides final constant OverridingConstantMultiplePrototypes\ParentWithFinal::E.', + 85, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Constants/data/overriding-constant-multiple-prototypes.php b/tests/PHPStan/Rules/Constants/data/overriding-constant-multiple-prototypes.php new file mode 100644 index 00000000000..54daecf8a16 --- /dev/null +++ b/tests/PHPStan/Rules/Constants/data/overriding-constant-multiple-prototypes.php @@ -0,0 +1,87 @@ += 8.1 + +namespace OverridingConstantMultiplePrototypes; + +interface NotFinal +{ + + const C = 1; + +} + +interface IsFinal +{ + + final const C = 2; + +} + +class ImplementsBoth implements NotFinal, IsFinal +{ + + const C = 3; + +} + +class ParentClass +{ + + const C = 1; + + protected const D = 1; + +} + +class ExtendsAndImplementsFinal extends ParentClass implements IsFinal +{ + + const C = 2; + +} + +interface PublicD +{ + + const D = 1; + +} + +class ExtendsAndImplementsPublic extends ParentClass implements PublicD +{ + + protected const D = 2; + +} + +class ParentImplementingNotFinal implements NotFinal +{ + +} + +class ChildOfParentImplementingNotFinal extends ParentImplementingNotFinal +{ + + const C = 4; + +} + +class ParentWithFinal +{ + + final const E = 1; + +} + +interface HasE +{ + + const E = 1; + +} + +class ExtendsFinalAndImplements extends ParentWithFinal implements HasE +{ + + const E = 2; + +}