From 433bbb20a17eabe7f6f5ebb5134e17042444b2ff Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 13:25:08 +0000 Subject: [PATCH 01/24] Report missing return types of functions and methods with a body on their return statements node The missing return type and the missing iterable value type of the return type are reported on FunctionReturnStatementsNode and MethodReturnStatementsNode, so that the rules have access to the types the function returns. Methods without a body, which have no return statements node, are still reported on InClassMethodNode. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- ...trollerActionReturnTypeIgnoreExtension.php | 7 +- .../MissingFunctionReturnTypehintRule.php | 6 +- ...ingImplementedMethodReturnTypehintRule.php | 74 ++++++++++++ .../MissingMethodReturnTypehintRule.php | 28 +++-- ...mplementedMethodReturnTypehintRuleTest.php | 111 ++++++++++++++++++ .../MissingMethodReturnTypehintRuleTest.php | 30 +---- 6 files changed, 212 insertions(+), 44 deletions(-) create mode 100644 src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php create mode 100644 tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php diff --git a/e2e/ignore-error-extension/src/ControllerActionReturnTypeIgnoreExtension.php b/e2e/ignore-error-extension/src/ControllerActionReturnTypeIgnoreExtension.php index dc7b0dab5af..6a080b1d606 100644 --- a/e2e/ignore-error-extension/src/ControllerActionReturnTypeIgnoreExtension.php +++ b/e2e/ignore-error-extension/src/ControllerActionReturnTypeIgnoreExtension.php @@ -9,6 +9,7 @@ use PHPStan\Analyser\IgnoreErrorExtension; use PHPStan\Analyser\Scope; use PHPStan\Node\InClassMethodNode; +use PHPStan\Node\MethodReturnStatementsNode; // This extension will ignore "missingType.iterableValue" errors for public Action methods inside Controller classes. final class ControllerActionReturnTypeIgnoreExtension implements IgnoreErrorExtension @@ -19,8 +20,10 @@ public function shouldIgnore(Error $error, Node $node, Scope $scope) : bool return false; } - // @phpstan-ignore phpstanApi.instanceofAssumption - if (! $node instanceof InClassMethodNode) { + // Methods with a body report missing return types on MethodReturnStatementsNode, + // abstract methods and methods in interfaces on InClassMethodNode. + // @phpstan-ignore phpstanApi.instanceofAssumption, phpstanApi.instanceofAssumption + if (! $node instanceof InClassMethodNode && ! $node instanceof MethodReturnStatementsNode) { return false; } diff --git a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php index 09c276a9b49..cfa44a4b618 100644 --- a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php +++ b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php @@ -6,7 +6,7 @@ use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; -use PHPStan\Node\InFunctionNode; +use PHPStan\Node\FunctionReturnStatementsNode; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; @@ -15,7 +15,7 @@ use function sprintf; /** - * @implements Rule + * @implements Rule */ #[RegisteredRule(level: 6)] #[ValidatesStubFiles] @@ -30,7 +30,7 @@ public function __construct( public function getNodeType(): string { - return InFunctionNode::class; + return FunctionReturnStatementsNode::class; } public function processNode(Node $node, Scope $scope): array diff --git a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php new file mode 100644 index 00000000000..547f45a8986 --- /dev/null +++ b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php @@ -0,0 +1,74 @@ + + */ +#[RegisteredRule(level: 6)] +#[ValidatesStubFiles] +final class MissingImplementedMethodReturnTypehintRule implements Rule +{ + + public function __construct(private MissingTypehintCheck $missingTypehintCheck) + { + } + + public function getNodeType(): string + { + return MethodReturnStatementsNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if ( + $scope->isInTrait() + && $node->getClassMethod()->getAttribute('originalTraitMethodName') === '__construct' + ) { + return []; + } + + $methodReflection = $node->getMethodReflection(); + $returnType = $methodReflection->getReturnType(); + + if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + return [ + RuleErrorBuilder::message(sprintf( + 'Method %s::%s() has no return type specified.', + $methodReflection->getDeclaringClass()->getDisplayName(), + $methodReflection->getName(), + ))->identifier('missingType.return')->build(), + ]; + } + + $messages = []; + foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { + $messages[] = RuleErrorBuilder::message(sprintf( + 'Method %s::%s() return type has no value type specified in %s.', + $methodReflection->getDeclaringClass()->getDisplayName(), + $methodReflection->getName(), + $iterableTypeDescription, + )) + ->tip(MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP) + ->identifier('missingType.iterableValue') + ->build(); + } + + return $messages; + } + +} diff --git a/src/Rules/Methods/MissingMethodReturnTypehintRule.php b/src/Rules/Methods/MissingMethodReturnTypehintRule.php index ea40b006706..a0974a7c158 100644 --- a/src/Rules/Methods/MissingMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingMethodReturnTypehintRule.php @@ -43,7 +43,13 @@ public function processNode(Node $node, Scope $scope): array } $returnType = $methodReflection->getReturnType(); + // MissingImplementedMethodReturnTypehintRule reports these for methods with a body + $hasBody = $node->getOriginalNode()->stmts !== null; if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + if ($hasBody) { + return []; + } + return [ RuleErrorBuilder::message(sprintf( 'Method %s::%s() has no return type specified.', @@ -54,16 +60,18 @@ public function processNode(Node $node, Scope $scope): array } $messages = []; - foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() return type has no value type specified in %s.', - $methodReflection->getDeclaringClass()->getDisplayName(), - $methodReflection->getName(), - $iterableTypeDescription, - )) - ->tip(MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP) - ->identifier('missingType.iterableValue') - ->build(); + if (!$hasBody) { + foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { + $messages[] = RuleErrorBuilder::message(sprintf( + 'Method %s::%s() return type has no value type specified in %s.', + $methodReflection->getDeclaringClass()->getDisplayName(), + $methodReflection->getName(), + $iterableTypeDescription, + )) + ->tip(MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP) + ->identifier('missingType.iterableValue') + ->build(); + } } foreach ($this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($returnType) as [$name, $genericTypeNames]) { diff --git a/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php b/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php new file mode 100644 index 00000000000..73a978b5a12 --- /dev/null +++ b/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php @@ -0,0 +1,111 @@ + + */ +class MissingImplementedMethodReturnTypehintRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + return new MissingImplementedMethodReturnTypehintRule(new MissingTypehintCheck(true, [], true)); + } + + public function testRule(): void + { + $this->analyse([__DIR__ . '/data/missing-method-return-typehint.php'], [ + [ + 'Method MissingMethodReturnTypehint\FooParent::getBar() has no return type specified.', + 15, + ], + [ + 'Method MissingMethodReturnTypehint\Foo::getFoo() has no return type specified.', + 25, + ], + [ + 'Method MissingMethodReturnTypehint\Foo::getBar() has no return type specified.', + 33, + ], + [ + 'Method MissingMethodReturnTypehint\Foo::unionTypeWithUnknownArrayValueTypehint() return type has no value type specified in iterable type array.', + 46, + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ], + [ + 'Method MissingMethodReturnTypehint\IterableIntersection::doFoo() return type has no value type specified in iterable type Traversable.', + 110, + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ], + ]); + } + + public function testIndirectInheritanceBug2740(): void + { + $this->analyse([__DIR__ . '/data/bug2740.php'], []); + } + + public function testArrayTypehintWithoutNullInPhpDoc(): void + { + $this->analyse([__DIR__ . '/../../Analyser/nsrt/array-typehint-without-null-in-phpdoc.php'], []); + } + + public function testBug4415(): void + { + $this->analyse([__DIR__ . '/data/bug-4415.php'], []); + } + + public function testBug5089(): void + { + $this->analyse([__DIR__ . '/data/bug-5089.php'], []); + } + + public function testBug5436(): void + { + $this->analyse([__DIR__ . '/data/bug-5436.php'], []); + } + + public function testBug4758(): void + { + $this->analyse([__DIR__ . '/data/bug-4758.php'], []); + } + + public function testBug9571(): void + { + $this->analyse([__DIR__ . '/data/bug-9571.php'], []); + } + + public function testBug9571PhpDocs(): void + { + $this->analyse([__DIR__ . '/data/bug-9571-phpdocs.php'], []); + } + + public function testGenericStatic(): void + { + $this->analyse([__DIR__ . '/data/missing-return-type-generic-static.php'], [ + [ + 'Method MissingReturnTypeGenericStatic\Foo::doFoo() return type has no value type specified in iterable type array.', + 12, + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ], + ]); + } + + #[RequiresPhp('>= 8.0.0')] + public function testBug9657(): void + { + $this->analyse([__DIR__ . '/data/bug-9657.php'], []); + } + + public function testInheritPhpDocReturnTypeWithNarrowerNativeReturnType(): void + { + $this->analyse([__DIR__ . '/data/inherit-phpdoc-return-type-with-narrower-native-return-type.php'], []); + } + +} diff --git a/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php b/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php index ffbf4bded52..84a8a82a3b5 100644 --- a/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php @@ -25,23 +25,6 @@ public function testRule(): void 'Method MissingMethodReturnTypehint\FooInterface::getFoo() has no return type specified.', 8, ], - [ - 'Method MissingMethodReturnTypehint\FooParent::getBar() has no return type specified.', - 15, - ], - [ - 'Method MissingMethodReturnTypehint\Foo::getFoo() has no return type specified.', - 25, - ], - [ - 'Method MissingMethodReturnTypehint\Foo::getBar() has no return type specified.', - 33, - ], - [ - 'Method MissingMethodReturnTypehint\Foo::unionTypeWithUnknownArrayValueTypehint() return type has no value type specified in iterable type array.', - 46, - MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, - ], [ 'Method MissingMethodReturnTypehint\Bar::returnsGenericInterface() return type with generic interface MissingMethodReturnTypehint\GenericInterface does not specify its types: T, U', 79, @@ -54,11 +37,6 @@ public function testRule(): void 'Method MissingMethodReturnTypehint\CallableSignature::doFoo() return type has no signature specified for callable.', 99, ], - [ - 'Method MissingMethodReturnTypehint\IterableIntersection::doFoo() return type has no value type specified in iterable type Traversable.', - 110, - MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, - ], [ 'Method MissingMethodReturnTypehint\Baz::returnsGenericWithSomeDefaults() return type with generic class MissingMethodReturnTypehint\GenericClassWithSomeDefaults does not specify its types: T, U (1-2 required)', 142, @@ -108,13 +86,7 @@ public function testBug9571PhpDocs(): void public function testGenericStatic(): void { - $this->analyse([__DIR__ . '/data/missing-return-type-generic-static.php'], [ - [ - 'Method MissingReturnTypeGenericStatic\Foo::doFoo() return type has no value type specified in iterable type array.', - 12, - MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, - ], - ]); + $this->analyse([__DIR__ . '/data/missing-return-type-generic-static.php'], []); } #[RequiresPhp('>= 8.0.0')] From 0b8e403081597d7ac5fe7c03f8aecab4dc90a7a6 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 13:25:27 +0000 Subject: [PATCH 02/24] Add projectType parameter An open project, the default, is a library or a framework other code extends, so its classes can be extended and its methods overridden by code PHPStan does not see. A closed project is an application whose code is all analysed. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- conf/config.neon | 1 + conf/parametersSchema.neon | 1 + 2 files changed, 2 insertions(+) diff --git a/conf/config.neon b/conf/config.neon index 2a9f2e621ae..aaae7ff73cf 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -97,6 +97,7 @@ parameters: checkPhpDocMethodSignatures: false checkExtraArguments: false checkMissingTypehints: false + projectType: open checkTooWideParameterOutInProtectedAndPublicMethods: false checkTooWideReturnTypesInProtectedAndPublicMethods: false checkTooWideThrowTypesInProtectedAndPublicMethods: false diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index eb2014cf8eb..769b6be85d9 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -94,6 +94,7 @@ parametersSchema: checkPhpDocMethodSignatures: bool() checkExtraArguments: bool() checkMissingTypehints: bool() + projectType: anyOf('open', 'closed') checkTooWideParameterOutInProtectedAndPublicMethods: bool() checkTooWideReturnTypesInProtectedAndPublicMethods: bool() checkTooWideThrowTypesInProtectedAndPublicMethods: bool() From 2c5836326a68d00597b8c48e2a6be9f283ea7afa Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 13:39:24 +0000 Subject: [PATCH 03/24] Report too-wide types of overridable methods in a closed project with regard to the overriding methods With projectType: closed, the too-wide return, @param-out and @throws types of public and protected methods in non-final classes are reported regardless of the checkTooWide*InProtectedAndPublicMethods options. Such a method and the methods overriding it emit which members of the type they use, and TooWideTypeInOverridableMemberRule reports the members none of them uses, so that removing them keeps the overriding methods covariant. The type of a method that nothing overrides is reported like the type of a private method. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../Exceptions/TooWideMethodThrowTypeRule.php | 96 ++++- .../TooWidePropertyHookThrowTypeRule.php | 73 +++- .../Exceptions/TooWideThrowTypeCheck.php | 48 ++- .../OverridableMemberHelper.php | 187 ++++++++ .../TooWideMethodParameterOutTypeRule.php | 52 ++- .../TooWideMethodReturnTypehintRule.php | 64 ++- .../TooWideParameterOutTypeCheck.php | 219 ++++++++-- .../TooWideTypehints/TooWideTypeCheck.php | 408 ++++++++++++++---- ...ooWideTypeInOverridableMemberCollector.php | 28 ++ .../TooWideTypeInOverridableMemberRule.php | 99 +++++ .../TypeUsedInOverridingMemberCollector.php | 28 ++ .../TooWideMethodThrowTypeRuleTest.php | 42 +- .../TooWidePropertyHookThrowTypeRuleTest.php | 28 +- .../too-wide-throws-method-closed-project.php | 52 +++ ...de-throws-property-hook-closed-project.php | 27 ++ .../TooWideMethodParameterOutTypeRuleTest.php | 46 +- .../TooWideMethodReturnTypehintRuleTest.php | 38 +- ...de-method-parameter-out-closed-project.php | 37 ++ ...wide-method-return-type-closed-project.php | 58 +++ 19 files changed, 1421 insertions(+), 209 deletions(-) create mode 100644 src/Rules/TooWideTypehints/OverridableMemberHelper.php create mode 100644 src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php create mode 100644 src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php create mode 100644 src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php create mode 100644 tests/PHPStan/Rules/Exceptions/data/too-wide-throws-method-closed-project.php create mode 100644 tests/PHPStan/Rules/Exceptions/data/too-wide-throws-property-hook-closed-project.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/too-wide-method-parameter-out-closed-project.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/too-wide-method-return-type-closed-project.php diff --git a/src/Rules/Exceptions/TooWideMethodThrowTypeRule.php b/src/Rules/Exceptions/TooWideMethodThrowTypeRule.php index 798d98f8c48..0568d79230f 100644 --- a/src/Rules/Exceptions/TooWideMethodThrowTypeRule.php +++ b/src/Rules/Exceptions/TooWideMethodThrowTypeRule.php @@ -4,6 +4,7 @@ use PhpParser\Comment\Doc; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\Conditional; @@ -12,10 +13,12 @@ use PHPStan\Reflection\ClassReflection; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Type\FileTypeMapper; use PHPStan\Type\TypeUtils; use PHPStan\Type\VerbosityLevel; use function array_diff; +use function array_keys; use function array_map; use function count; use function implode; @@ -38,6 +41,7 @@ public function __construct( private bool $checkProtectedAndPublicMethods, #[AutowiredParameter(ref: '%exceptions.check.tooWideImplicitThrowType%')] private bool $tooWideImplicitThrows, + private OverridableMemberHelper $overridableMemberHelper, ) { } @@ -47,30 +51,43 @@ public function getNodeType(): string return MethodReturnStatementsNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { $statementResult = $node->getStatementResult(); $method = $node->getMethodReflection(); - $isFirstDeclaration = $method->getPrototype()->getDeclaringClass() === $method->getDeclaringClass(); - if (!$method->isPrivate()) { - if (!$method->getDeclaringClass()->isFinal() && !$method->isFinal()->yes()) { - if (!$this->checkProtectedAndPublicMethods) { - return []; + $isClosedProject = $this->overridableMemberHelper->isClosedProject(); + if ($isClosedProject) { + foreach ($this->overridableMemberHelper->findOverriddenMethods($node->getClassReflection(), $method->getName()) as $overriddenMethod) { + $overriddenThrowType = $overriddenMethod->getThrowType(); + if ($overriddenThrowType === null || $overriddenThrowType->isVoid()->yes()) { + continue; } - if ($isFirstDeclaration) { - return []; - } + $this->overridableMemberHelper->emitUsage( + $scope, + OverridableMemberHelper::KIND_THROWS, + $overriddenMethod->getDeclaringClass()->getName(), + OverridableMemberHelper::getMethodKey($overriddenMethod->getName()), + 0, + array_keys($this->check->getUsedMembers($overriddenThrowType, $statementResult->getThrowPoints())), + ); } } - $throwType = $method->getThrowType(); - if ($throwType === null) { - return []; + $isFirstDeclaration = $method->getPrototype()->getDeclaringClass() === $method->getDeclaringClass(); + $isOverridable = !$method->isPrivate() && !$method->getDeclaringClass()->isFinal() && !$method->isFinal()->yes(); + if ($isOverridable && !$isClosedProject) { + if (!$this->checkProtectedAndPublicMethods) { + return []; + } + + if ($isFirstDeclaration) { + return []; + } } - $unusedThrowClasses = $this->check->check($throwType, $statementResult->getThrowPoints()); - if (count($unusedThrowClasses) === 0) { + $throwType = $method->getThrowType(); + if ($throwType === null || $throwType->isVoid()->yes()) { return []; } @@ -85,21 +102,54 @@ public function processNode(Node $node, Scope $scope): array return []; } + $messagePattern = sprintf( + 'Method %s::%s() has %%s in PHPDoc @throws tag but it\'s not thrown.', + $method->getDeclaringClass()->getDisplayName(), + $method->getName(), + ); + $tipPattern = $isThrowTypeExplicit ? null : 'You can narrow the thrown type with PHPDoc tag @throws %s.'; + + if ($isOverridable) { + $members = $this->check->getMembers($throwType); + $memberDescriptions = []; + $memberErrors = []; + foreach ($members as $member) { + $memberDescription = $member->describe(VerbosityLevel::typeOnly()); + $memberDescriptions[] = $memberDescription; + $memberErrors[] = [sprintf($messagePattern, $memberDescription), 'throws.unusedType', null]; + } + + $this->overridableMemberHelper->emitDeclaration( + $scope, + OverridableMemberHelper::KIND_THROWS, + $node->getClassReflection()->getName(), + OverridableMemberHelper::getMethodKey($method->getName()), + 0, + $node->getStartLine(), + array_keys($this->check->getUsedMembers($throwType, $statementResult->getThrowPoints())), + $memberErrors, + $tipPattern, + $memberDescriptions, + ); + + return []; + } + + $unusedThrowClasses = $this->check->check($throwType, $statementResult->getThrowPoints()); + if (count($unusedThrowClasses) === 0) { + return []; + } + $throwClasses = array_map(static fn ($type) => $type->describe(VerbosityLevel::typeOnly()), TypeUtils::flattenTypes($throwType)); $usedClasses = array_diff($throwClasses, $unusedThrowClasses); $errors = []; foreach ($unusedThrowClasses as $throwClass) { - $builder = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() has %s in PHPDoc @throws tag but it\'s not thrown.', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - $throwClass, - ))->identifier('throws.unusedType'); - - if (!$isThrowTypeExplicit) { + $builder = RuleErrorBuilder::message(sprintf($messagePattern, $throwClass))->identifier('throws.unusedType'); + + if ($tipPattern !== null) { $builder->tip(sprintf( - 'You can narrow the thrown type with PHPDoc tag @throws %s.', + $tipPattern, count($usedClasses) === 0 ? 'void' : implode('|', $usedClasses), )); } diff --git a/src/Rules/Exceptions/TooWidePropertyHookThrowTypeRule.php b/src/Rules/Exceptions/TooWidePropertyHookThrowTypeRule.php index 053d3156fef..6e2bfa149d7 100644 --- a/src/Rules/Exceptions/TooWidePropertyHookThrowTypeRule.php +++ b/src/Rules/Exceptions/TooWidePropertyHookThrowTypeRule.php @@ -3,6 +3,7 @@ namespace PHPStan\Rules\Exceptions; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\Conditional; @@ -10,7 +11,10 @@ use PHPStan\Node\PropertyHookReturnStatementsNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\ShouldNotHappenException; +use PHPStan\Type\VerbosityLevel; +use function array_keys; use function sprintf; use function ucfirst; @@ -28,6 +32,7 @@ public function __construct( private TooWideThrowTypeCheck $check, #[AutowiredParameter(ref: '%checkTooWideThrowTypesInProtectedAndPublicMethods%')] private bool $checkProtectedAndPublicMethods, + private OverridableMemberHelper $overridableMemberHelper, ) { } @@ -37,40 +42,78 @@ public function getNodeType(): string return PropertyHookReturnStatementsNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { $statementResult = $node->getStatementResult(); $hookReflection = $node->getHookReflection(); - if ($hookReflection->getPropertyHookName() === null) { + $hookName = $hookReflection->getPropertyHookName(); + if ($hookName === null) { throw new ShouldNotHappenException(); } $propertyReflection = $node->getPropertyReflection(); + $isClosedProject = $this->overridableMemberHelper->isClosedProject(); + if ($isClosedProject) { + foreach ($this->overridableMemberHelper->findOverriddenPropertyHooks($node->getClassReflection(), $propertyReflection->getName(), $hookName) as $overriddenProperty) { + $overriddenThrowType = $overriddenProperty->getHook($hookName)->getThrowType(); + if ($overriddenThrowType === null || $overriddenThrowType->isVoid()->yes()) { + continue; + } + + $this->overridableMemberHelper->emitUsage( + $scope, + OverridableMemberHelper::KIND_THROWS, + $overriddenProperty->getDeclaringClass()->getName(), + OverridableMemberHelper::getPropertyHookKey($overriddenProperty->getName(), $hookName), + 0, + array_keys($this->check->getUsedMembers($overriddenThrowType, $statementResult->getThrowPoints())), + ); + } + } $throwType = $hookReflection->getThrowType(); - if ($throwType === null) { + if ($throwType === null || $throwType->isVoid()->yes()) { return []; } - if ( - !$propertyReflection->isPrivate() + $isOverridable = !$propertyReflection->isPrivate() && !$propertyReflection->getDeclaringClass()->isFinal() && !$propertyReflection->isFinal()->yes() - && !$hookReflection->isFinal()->yes() - && !$this->checkProtectedAndPublicMethods - ) { + && !$hookReflection->isFinal()->yes(); + if ($isOverridable && !$isClosedProject && !$this->checkProtectedAndPublicMethods) { + return []; + } + + $messagePattern = sprintf( + '%s hook for property %s::$%s has %%s in PHPDoc @throws tag but it\'s not thrown.', + ucfirst($hookName), + $hookReflection->getDeclaringClass()->getDisplayName(), + $hookReflection->getHookedPropertyName(), + ); + + if ($isOverridable && $isClosedProject) { + $memberErrors = []; + foreach ($this->check->getMembers($throwType) as $member) { + $memberErrors[] = [sprintf($messagePattern, $member->describe(VerbosityLevel::typeOnly())), 'throws.unusedType', null]; + } + + $this->overridableMemberHelper->emitDeclaration( + $scope, + OverridableMemberHelper::KIND_THROWS, + $node->getClassReflection()->getName(), + OverridableMemberHelper::getPropertyHookKey($propertyReflection->getName(), $hookName), + 0, + $node->getStartLine(), + array_keys($this->check->getUsedMembers($throwType, $statementResult->getThrowPoints())), + $memberErrors, + ); + return []; } $errors = []; foreach ($this->check->check($throwType, $statementResult->getThrowPoints()) as $throwClass) { - $errors[] = RuleErrorBuilder::message(sprintf( - '%s hook for property %s::$%s has %s in PHPDoc @throws tag but it\'s not thrown.', - ucfirst($hookReflection->getPropertyHookName()), - $hookReflection->getDeclaringClass()->getDisplayName(), - $hookReflection->getHookedPropertyName(), - $throwClass, - )) + $errors[] = RuleErrorBuilder::message(sprintf($messagePattern, $throwClass)) ->identifier('throws.unusedType') ->build(); } diff --git a/src/Rules/Exceptions/TooWideThrowTypeCheck.php b/src/Rules/Exceptions/TooWideThrowTypeCheck.php index 1eb978a73ff..1b237a2e3eb 100644 --- a/src/Rules/Exceptions/TooWideThrowTypeCheck.php +++ b/src/Rules/Exceptions/TooWideThrowTypeCheck.php @@ -11,6 +11,7 @@ use PHPStan\Type\TypeUtils; use PHPStan\Type\VerbosityLevel; use function array_map; +use function array_values; #[AutowiredService] final class TooWideThrowTypeCheck @@ -33,6 +34,39 @@ public function check(Type $throwType, array $throwPoints): array return []; } + $members = $this->getMembers($throwType); + $usedMembers = $this->getUsedMembers($throwType, $throwPoints); + + $throwClasses = []; + foreach ($members as $i => $type) { + if (isset($usedMembers[$i])) { + continue; + } + + $throwClasses[] = $type->describe(VerbosityLevel::typeOnly()); + } + + return $throwClasses; + } + + /** + * The thrown types of the @throws type, check() reports the ones that are not thrown. + * + * @return list + */ + public function getMembers(Type $throwType): array + { + return array_values(TypeUtils::flattenTypes($throwType)); + } + + /** + * The members of the @throws type, as getMembers() lists them, that are thrown. + * + * @param ThrowPoint[] $throwPoints + * @return array + */ + public function getUsedMembers(Type $throwType, array $throwPoints): array + { $throwPointType = TypeCombinator::union(...array_map(function (ThrowPoint $throwPoint): Type { if (!$this->implicitThrows && !$throwPoint->isExplicit()) { return new NeverType(); @@ -41,16 +75,20 @@ public function check(Type $throwType, array $throwPoints): array return $throwPoint->getType(); }, $throwPoints)); - $throwClasses = []; - foreach (TypeUtils::flattenTypes($throwType) as $type) { - if (!$throwPointType instanceof NeverType && !$type->isSuperTypeOf($throwPointType)->no()) { + $usedMembers = []; + if ($throwPointType instanceof NeverType) { + return $usedMembers; + } + + foreach ($this->getMembers($throwType) as $i => $type) { + if ($type->isSuperTypeOf($throwPointType)->no()) { continue; } - $throwClasses[] = $type->describe(VerbosityLevel::typeOnly()); + $usedMembers[$i] = true; } - return $throwClasses; + return $usedMembers; } } diff --git a/src/Rules/TooWideTypehints/OverridableMemberHelper.php b/src/Rules/TooWideTypehints/OverridableMemberHelper.php new file mode 100644 index 00000000000..f0e1d54403c --- /dev/null +++ b/src/Rules/TooWideTypehints/OverridableMemberHelper.php @@ -0,0 +1,187 @@ +projectType === 'closed'; + } + + public static function getMethodKey(string $methodName): string + { + return strtolower($methodName); + } + + public static function getPropertyHookKey(string $propertyName, string $hookName): string + { + return sprintf('$%s::%s', $propertyName, $hookName); + } + + /** + * The methods of the parent classes with a body the method overrides. + * Constructors are not overridden, a class calls the constructor of its parent class explicitly. + * + * @return list + */ + public function findOverriddenMethods(ClassReflection $classReflection, string $methodName): array + { + if (strtolower($methodName) === '__construct') { + return []; + } + + $methods = []; + foreach ($classReflection->getParents() as $parentClass) { + if (!$parentClass->hasNativeMethod($methodName)) { + continue; + } + + $method = $parentClass->getNativeMethod($methodName); + $isAbstract = $method->isAbstract(); + if ( + $method->getDeclaringClass()->getName() !== $parentClass->getName() + || $method->isPrivate() + || $isAbstract === true + || ($isAbstract instanceof TrinaryLogic && $isAbstract->yes()) + ) { + continue; + } + + $methods[] = $method; + } + + return $methods; + } + + /** + * The properties of the parent classes with the hook the property hook overrides. + * + * @param 'get'|'set' $hookName + * @return list + */ + public function findOverriddenPropertyHooks(ClassReflection $classReflection, string $propertyName, string $hookName): array + { + $properties = []; + foreach ($classReflection->getParents() as $parentClass) { + if (!$parentClass->hasNativeProperty($propertyName)) { + continue; + } + + $property = $parentClass->getNativeProperty($propertyName); + if ( + $property->getDeclaringClass()->getName() !== $parentClass->getName() + || $property->isPrivate() + || !$property->hasHook($hookName) + ) { + continue; + } + + $properties[] = $property; + } + + return $properties; + } + + /** + * @param self::KIND_* $kind + * @param list $usedMembers the members of the type the member uses itself + * @param list $memberErrors message, identifier and tip for each member of the type + * @param string|null $usedMembersTip tip for the errors with %s for the used members, or void + * @param list $memberDescriptions the members of the type in $usedMembersTip + */ + public function emitDeclaration( + Scope&CollectedDataEmitter $scope, + string $kind, + string $className, + string $memberKey, + int $slot, + int $line, + array $usedMembers, + array $memberErrors, + ?string $usedMembersTip = null, + array $memberDescriptions = [], + ): void + { + $file = null; + $fileDescription = null; + if ($scope->isInTrait()) { + $file = $scope->getTraitReflection()->getFileName(); + $fileDescription = $scope->getFileDescription(); + } + + // whether the member is reported depends on the classes extending it, which can be anywhere + $scope->emitCollectedData(AnalysedFileDependencyCollector::class, null); + $scope->emitCollectedData(TooWideTypeInOverridableMemberCollector::class, [ + 'kind' => $kind, + 'class' => $className, + 'member' => $memberKey, + 'slot' => $slot, + 'file' => $file, + 'fileDescription' => $fileDescription, + 'line' => $line, + 'used' => $usedMembers, + 'errors' => $memberErrors, + 'usedMembersTip' => $usedMembersTip, + 'memberDescriptions' => $memberDescriptions, + ]); + } + + /** + * @param self::KIND_* $kind + * @param list $usedMembers the members of the type of the overridden member the overriding member uses + */ + public function emitUsage( + CollectedDataEmitter $scope, + string $kind, + string $overriddenClassName, + string $overriddenMemberKey, + int $slot, + array $usedMembers, + ): void + { + $scope->emitCollectedData(TypeUsedInOverridingMemberCollector::class, [ + 'kind' => $kind, + 'class' => $overriddenClassName, + 'member' => $overriddenMemberKey, + 'slot' => $slot, + 'used' => $usedMembers, + ]); + } + +} diff --git a/src/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRule.php b/src/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRule.php index f96c13f5803..3d829e768e0 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRule.php @@ -3,6 +3,7 @@ namespace PHPStan\Rules\TooWideTypehints; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; @@ -21,6 +22,7 @@ public function __construct( private TooWideParameterOutTypeCheck $check, #[AutowiredParameter(ref: '%checkTooWideParameterOutInProtectedAndPublicMethods%')] private bool $checkProtectedAndPublicMethods, + private OverridableMemberHelper $overridableMemberHelper, ) { } @@ -30,12 +32,58 @@ public function getNodeType(): string return MethodReturnStatementsNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { $inMethod = $node->getMethodReflection(); + $parameters = $inMethod->getParameters(); + $isClosedProject = $this->overridableMemberHelper->isClosedProject(); + if ($isClosedProject) { + foreach ($this->overridableMemberHelper->findOverriddenMethods($node->getClassReflection(), $inMethod->getName()) as $overriddenMethod) { + $usedMembersByParameter = $this->check->getUsedOverriddenMembers( + $node->getExecutionEnds(), + $node->getReturnStatements(), + $parameters, + $overriddenMethod->getOnlyVariant()->getParameters(), + $scope, + ); + foreach ($usedMembersByParameter as $slot => $usedMembers) { + $this->overridableMemberHelper->emitUsage( + $scope, + OverridableMemberHelper::KIND_PARAMETER_OUT, + $overriddenMethod->getDeclaringClass()->getName(), + OverridableMemberHelper::getMethodKey($overriddenMethod->getName()), + $slot, + $usedMembers, + ); + } + } + } + $functionDescription = sprintf('Method %s::%s()', $inMethod->getDeclaringClass()->getDisplayName(), $inMethod->getName()); if (!$inMethod->isPrivate()) { if (!$inMethod->getDeclaringClass()->isFinal() && !$inMethod->isFinal()->yes()) { + if ($isClosedProject) { + foreach ($this->check->createOverridableErrors( + $node->getExecutionEnds(), + $node->getReturnStatements(), + $parameters, + $functionDescription, + ) as $slot => [$usedMembers, $memberErrors]) { + $this->overridableMemberHelper->emitDeclaration( + $scope, + OverridableMemberHelper::KIND_PARAMETER_OUT, + $node->getClassReflection()->getName(), + OverridableMemberHelper::getMethodKey($inMethod->getName()), + $slot, + $node->getStartLine(), + $usedMembers, + $memberErrors, + ); + } + + return []; + } + if (!$this->checkProtectedAndPublicMethods) { return []; } @@ -47,7 +95,7 @@ public function processNode(Node $node, Scope $scope): array $node->getExecutionEnds(), $node->getReturnStatements(), $inMethod->getParameters(), - sprintf('Method %s::%s()', $inMethod->getDeclaringClass()->getDisplayName(), $inMethod->getName()), + $functionDescription, ); } diff --git a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php index 77c5ca7b1ff..98fea3003d8 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php @@ -3,6 +3,7 @@ namespace PHPStan\Rules\TooWideTypehints; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; @@ -21,6 +22,7 @@ public function __construct( #[AutowiredParameter(ref: '%checkTooWideReturnTypesInProtectedAndPublicMethods%')] private bool $checkProtectedAndPublicMethods, private TooWideTypeCheck $check, + private OverridableMemberHelper $overridableMemberHelper, ) { } @@ -30,15 +32,65 @@ public function getNodeType(): string return MethodReturnStatementsNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { + $method = $node->getMethodReflection(); + $classReflection = $node->getClassReflection(); + $isClosedProject = $this->overridableMemberHelper->isClosedProject(); + if ($isClosedProject) { + foreach ($this->overridableMemberHelper->findOverriddenMethods($classReflection, $method->getName()) as $overriddenMethod) { + $usedMembers = $this->check->getUsedOverriddenReturnTypeMembers($node, $overriddenMethod->getOnlyVariant(), $scope); + if ($usedMembers === null) { + continue; + } + + $this->overridableMemberHelper->emitUsage( + $scope, + OverridableMemberHelper::KIND_RETURN, + $overriddenMethod->getDeclaringClass()->getName(), + OverridableMemberHelper::getMethodKey($overriddenMethod->getName()), + 0, + $usedMembers, + ); + } + } + if ($scope->isInTrait()) { return []; } - $method = $node->getMethodReflection(); $isFirstDeclaration = $method->getPrototype()->getDeclaringClass() === $method->getDeclaringClass(); + $checkDescendantClass = !$isFirstDeclaration && !$method->isPrivate(); + $functionDescription = sprintf( + 'Method %s::%s()', + $method->getDeclaringClass()->getDisplayName(), + $method->getName(), + ); if (!$method->isPrivate()) { if (!$method->getDeclaringClass()->isFinal() && !$method->isFinal()->yes()) { + if ($isClosedProject) { + $result = $this->check->createOverridableReturnTypeErrors( + $node, + $method, + $functionDescription, + $checkDescendantClass, + $scope, + ); + if ($result !== null) { + $this->overridableMemberHelper->emitDeclaration( + $scope, + OverridableMemberHelper::KIND_RETURN, + $classReflection->getName(), + OverridableMemberHelper::getMethodKey($method->getName()), + 0, + $node->getStartLine(), + $result[0], + $result[1], + ); + } + + return []; + } + if (!$this->checkProtectedAndPublicMethods) { return []; } @@ -53,12 +105,8 @@ public function processNode(Node $node, Scope $scope): array $node, $method->getNativeReturnType(), $method->getPhpDocReturnType(), - sprintf( - 'Method %s::%s()', - $method->getDeclaringClass()->getDisplayName(), - $method->getName(), - ), - !$isFirstDeclaration && !$method->isPrivate(), + $functionDescription, + $checkDescendantClass, $scope, ); } diff --git a/src/Rules/TooWideTypehints/TooWideParameterOutTypeCheck.php b/src/Rules/TooWideTypehints/TooWideParameterOutTypeCheck.php index d952a33f819..6a3a5aaf614 100644 --- a/src/Rules/TooWideTypehints/TooWideParameterOutTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideParameterOutTypeCheck.php @@ -9,6 +9,7 @@ use PHPStan\Node\ReturnStatement; use PHPStan\Reflection\ExtendedParameterReflection; use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Type\Type; use function lcfirst; use function sprintf; @@ -36,75 +37,209 @@ public function check( string $functionDescription, ): array { - $finalScope = null; - foreach ($executionEnds as $executionEnd) { - $endScope = $executionEnd->getStatementResult()->getScope()->toWalkScope(); - if ($finalScope === null) { - $finalScope = $endScope; + $finalScope = $this->getFinalScope($executionEnds, $returnStatements); + if ($finalScope === null) { + return []; + } + + $errors = []; + foreach ($parameters as $parameter) { + if (!$parameter->passedByReference()->createsNewVariable()) { continue; } - $finalScope = $finalScope->mergeWith($endScope); - } - - foreach ($returnStatements as $statement) { - if ($finalScope === null) { - $finalScope = $statement->getScope()->toWalkScope(); + $assignedType = $this->getAssignedType($finalScope, $parameter); + if ($assignedType === null) { continue; } - $finalScope = $finalScope->mergeWith($statement->getScope()->toWalkScope()); + [$outType, $isParamOutType] = $this->getOutType($parameter); + [$unionMessagePattern, $boolMessagePattern] = $this->getMessagePatterns($functionDescription, $parameter, $isParamOutType); + foreach ($this->tooWideTypeCheck->checkParameterOutType( + $outType, + $assignedType, + $unionMessagePattern, + $boolMessagePattern, + sprintf( + '%s %%s of %s can be narrowed to %%s.', + $isParamOutType ? 'PHPDoc tag @param-out type' : 'By-ref type', + lcfirst($functionDescription), + ), + $finalScope, + $startLine, + $isParamOutType ? 'paramOut' : 'parameterByRef', + $this->getTip($isParamOutType), + ) as $error) { + $errors[] = $error; + } } + return $errors; + } + + /** + * Like TooWideTypeCheck::createOverridableReturnTypeErrors(), for each parameter passed by reference, + * by its position. + * + * @param list $executionEnds + * @param list $returnStatements + * @param list $parameters + * @return array, list}> + */ + public function createOverridableErrors( + array $executionEnds, + array $returnStatements, + array $parameters, + string $functionDescription, + ): array + { + $finalScope = $this->getFinalScope($executionEnds, $returnStatements); if ($finalScope === null) { return []; } - $errors = []; - foreach ($parameters as $parameter) { + $result = []; + foreach ($parameters as $i => $parameter) { if (!$parameter->passedByReference()->createsNewVariable()) { continue; } - foreach ($this->processSingleParameter($startLine, $finalScope, $functionDescription, $parameter) as $error) { - $errors[] = $error; + $assignedType = $this->getAssignedType($finalScope, $parameter); + if ($assignedType === null) { + continue; } + + [$outType, $isParamOutType] = $this->getOutType($parameter); + [$unionMessagePattern, $boolMessagePattern] = $this->getMessagePatterns($functionDescription, $parameter, $isParamOutType); + $parameterResult = $this->tooWideTypeCheck->createOverridableParameterOutTypeErrors( + $outType, + $assignedType, + $unionMessagePattern, + $boolMessagePattern, + $finalScope, + $isParamOutType ? 'paramOut' : 'parameterByRef', + $this->getTip($isParamOutType), + ); + if ($parameterResult === null) { + continue; + } + + $result[$i] = $parameterResult; } - return $errors; + return $result; } /** - * @return list + * Like TooWideTypeCheck::getUsedOverriddenReturnTypeMembers(), for each parameter + * of the overridden method passed by reference, by its position. + * + * @param list $executionEnds + * @param list $returnStatements + * @param list $parameters + * @param list $overriddenParameters + * @return array> */ - private function processSingleParameter( - int $startLine, + public function getUsedOverriddenMembers( + array $executionEnds, + array $returnStatements, + array $parameters, + array $overriddenParameters, Scope $scope, - string $functionDescription, - ExtendedParameterReflection $parameter, ): array { - $isParamOutType = true; - $outType = $parameter->getOutType(); - if ($outType === null) { - $isParamOutType = false; - $outType = $parameter->getType(); + $finalScope = $this->getFinalScope($executionEnds, $returnStatements); + + $result = []; + foreach ($overriddenParameters as $i => $overriddenParameter) { + if (!$overriddenParameter->passedByReference()->createsNewVariable()) { + continue; + } + + $assignedType = null; + if ($finalScope !== null && isset($parameters[$i])) { + $assignedType = $this->getAssignedType($finalScope, $parameters[$i]); + } + + [$outType] = $this->getOutType($overriddenParameter); + $usedMembers = $this->tooWideTypeCheck->getUsedOverriddenParameterOutTypeMembers($outType, $assignedType, $scope); + if ($usedMembers === null) { + continue; + } + + $result[$i] = $usedMembers; } - $variableExpr = new Variable($parameter->getName()); - $variableType = $scope->getType($variableExpr); + return $result; + } + + /** + * @param list $executionEnds + * @param list $returnStatements + */ + private function getFinalScope(array $executionEnds, array $returnStatements): ?Scope + { + $finalScope = null; + foreach ($executionEnds as $executionEnd) { + $endScope = $executionEnd->getStatementResult()->getScope()->toWalkScope(); + if ($finalScope === null) { + $finalScope = $endScope; + continue; + } + + $finalScope = $finalScope->mergeWith($endScope); + } + + foreach ($returnStatements as $statement) { + if ($finalScope === null) { + $finalScope = $statement->getScope()->toWalkScope(); + continue; + } + + $finalScope = $finalScope->mergeWith($statement->getScope()->toWalkScope()); + } + + return $finalScope; + } + + /** + * Null when it is not known. + */ + private function getAssignedType(Scope $finalScope, ExtendedParameterReflection $parameter): ?Type + { + $variableType = $finalScope->getType(new Variable($parameter->getName())); // a variadic out type describes one argument - see ParameterOutTypeCheck if ($parameter->isVariadic()) { if (!$variableType->isArray()->yes()) { - return []; + return null; } - $variableType = $variableType->getIterableValueType(); + + return $variableType->getIterableValueType(); + } + + return $variableType; + } + + /** + * @return array{Type, bool} the type and whether it is a @param-out type + */ + private function getOutType(ExtendedParameterReflection $parameter): array + { + $outType = $parameter->getOutType(); + if ($outType === null) { + return [$parameter->getType(), false]; } - return $this->tooWideTypeCheck->checkParameterOutType( - $outType, - $variableType, + return [$outType, true]; + } + + /** + * @return array{string, string} + */ + private function getMessagePatterns(string $functionDescription, ExtendedParameterReflection $parameter, bool $isParamOutType): array + { + return [ sprintf( '%s never assigns %%s to &$%s so it can be removed from the %s.', $functionDescription, @@ -117,16 +252,12 @@ private function processSingleParameter( $parameter->getName(), $isParamOutType ? '@param-out type' : 'by-ref type', ), - sprintf( - '%s %%s of %s can be narrowed to %%s.', - $isParamOutType ? 'PHPDoc tag @param-out type' : 'By-ref type', - lcfirst($functionDescription), - ), - $scope, - $startLine, - $isParamOutType ? 'paramOut' : 'parameterByRef', - $isParamOutType ? null : 'You can narrow the parameter out type with @param-out PHPDoc tag.', - ); + ]; + } + + private function getTip(bool $isParamOutType): ?string + { + return $isParamOutType ? null : 'You can narrow the parameter out type with @param-out PHPDoc tag.'; } } diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 307a3ec5280..7c8597d3123 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -11,6 +11,7 @@ use PHPStan\Node\MethodReturnStatementsNode; use PHPStan\Node\Property\PropertyAssign; use PHPStan\Reflection\ClassReflection; +use PHPStan\Reflection\ExtendedParametersAcceptor; use PHPStan\Rules\IdentifierRuleError; use PHPStan\Rules\Properties\PropertyReflectionFinder; use PHPStan\Rules\RuleErrorBuilder; @@ -25,6 +26,7 @@ use PHPStan\Type\UnionType; use PHPStan\Type\VerbosityLevel; use PHPStan\Type\VoidType; +use function array_keys; use function count; use function in_array; use function lcfirst; @@ -170,66 +172,15 @@ public function checkFunctionReturnType( Scope $scope, ): array { - $statementResult = $node->getStatementResult(); - if ($statementResult->hasYield()) { - return []; - } - - $returnStatements = $node->getReturnStatements(); - if (count($returnStatements) === 0) { - return []; - } - - $returnTypes = []; - foreach ($returnStatements as $returnStatement) { - $returnNode = $returnStatement->getReturnNode(); - if ($returnNode->expr === null) { - $returnTypes[] = new VoidType(); - continue; - } - - $returnTypes[] = $returnStatement->getScope()->getType($returnNode->expr); - } - - if (!$statementResult->isAlwaysTerminating()) { - $returnTypes[] = new VoidType(); - } - - if (!$node->hasNativeReturnTypehint()) { - foreach ($node->getExecutionEnds() as $executionEnd) { - if ($executionEnd->getStatementResult()->isAlwaysTerminating()) { - continue; - } - - $returnTypes[] = new NullType(); - break; - } - } - - $returnType = TypeCombinator::union(...$returnTypes); - + $returnType = $this->getReturnedType($node); if ( - count($returnStatements) === 1 - && $returnStatements[0]->getReturnNode()->expr instanceof ConstFetch - && in_array(strtolower($returnStatements[0]->getReturnNode()->expr->name->toString()), ['true', 'false'], true) - && ( - $nativeFunctionReturnType->isBoolean()->yes() - || $phpDocFunctionReturnType->isBoolean()->yes() - ) + $returnType === null + || $this->keepsWholeReturnType($node, $nativeFunctionReturnType, $phpDocFunctionReturnType, $returnType, $checkDescendantClass) ) { return []; } - $unionMessagePattern = sprintf('%s never returns %%s so it can be removed from the return type.', $functionDescription); - $boolMessagePattern = sprintf('%s never returns %%s so the return type can be changed to %%s.', $functionDescription); - - // Do not require to have @return null/true/false in descendant classes - if ( - $checkDescendantClass - && ($returnType->isNull()->yes() || $returnType->isTrue()->yes() || $returnType->isFalse()->yes()) - ) { - return []; - } + [$unionMessagePattern, $boolMessagePattern] = $this->getReturnTypeMessagePatterns($functionDescription); if (!$phpDocFunctionReturnType instanceof MixedType || $phpDocFunctionReturnType->isExplicitMixed()) { $phpDocFunctionReturnType = TypeUtils::resolveLateResolvableTypes(TypehintHelper::decideType($nativeFunctionReturnType, $phpDocFunctionReturnType)); @@ -291,6 +242,166 @@ public function checkFunctionReturnType( return []; } + /** + * The members of the return type of a method that can be overridden, which TooWideTypeInOverridableMemberRule + * reports when neither the method nor the methods overriding it return them: the members the method returns + * itself and the error for each member. Null when the method has nothing to report. + * + * @return array{list, list}|null + */ + public function createOverridableReturnTypeErrors( + MethodReturnStatementsNode $node, + ExtendedParametersAcceptor $methodVariant, + string $functionDescription, + bool $checkDescendantClass, + Scope $scope, + ): ?array + { + $returnType = $this->getReturnedType($node); + if ( + $returnType === null + || $this->keepsWholeReturnType($node, $methodVariant->getNativeReturnType(), $methodVariant->getPhpDocReturnType(), $returnType, $checkDescendantClass) + ) { + return null; + } + + [$declaredType, $native] = $this->getCheckedReturnType($methodVariant); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + [$unionMessagePattern, $boolMessagePattern] = $this->getReturnTypeMessagePatterns($functionDescription); + + return [ + $this->getUsedMembers($declaredType, $members, $returnType, $checkDescendantClass), + $this->createMemberErrors($declaredType, $members, $unionMessagePattern, $boolMessagePattern, 'return', null), + ]; + } + + /** + * The members of the return type of an overridden method, as createOverridableReturnTypeErrors() lists them, + * that the overriding method returns. All of them when it is not known what it returns, + * null when no member of the return type can be reported. + * + * @return list|null + */ + public function getUsedOverriddenReturnTypeMembers( + MethodReturnStatementsNode $node, + ExtendedParametersAcceptor $overriddenMethodVariant, + Scope $scope, + ): ?array + { + [$declaredType, $native] = $this->getCheckedReturnType($overriddenMethodVariant); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + $returnType = $this->getReturnedType($node); + if ($returnType === null) { + return array_keys($members); + } + + return $this->getUsedMembers($declaredType, $members, $returnType, false); + } + + /** + * Null when the function is a generator or it does not return anything. + */ + private function getReturnedType(MethodReturnStatementsNode|FunctionReturnStatementsNode $node): ?Type + { + $statementResult = $node->getStatementResult(); + if ($statementResult->hasYield()) { + return null; + } + + $returnStatements = $node->getReturnStatements(); + if (count($returnStatements) === 0) { + return null; + } + + $returnTypes = []; + foreach ($returnStatements as $returnStatement) { + $returnNode = $returnStatement->getReturnNode(); + if ($returnNode->expr === null) { + $returnTypes[] = new VoidType(); + continue; + } + + $returnTypes[] = $returnStatement->getScope()->getType($returnNode->expr); + } + + if (!$statementResult->isAlwaysTerminating()) { + $returnTypes[] = new VoidType(); + } + + if (!$node->hasNativeReturnTypehint()) { + foreach ($node->getExecutionEnds() as $executionEnd) { + if ($executionEnd->getStatementResult()->isAlwaysTerminating()) { + continue; + } + + $returnTypes[] = new NullType(); + break; + } + } + + return TypeCombinator::union(...$returnTypes); + } + + private function keepsWholeReturnType( + MethodReturnStatementsNode|FunctionReturnStatementsNode $node, + Type $nativeFunctionReturnType, + Type $phpDocFunctionReturnType, + Type $returnType, + bool $checkDescendantClass, + ): bool + { + $returnStatements = $node->getReturnStatements(); + if ( + count($returnStatements) === 1 + && $returnStatements[0]->getReturnNode()->expr instanceof ConstFetch + && in_array(strtolower($returnStatements[0]->getReturnNode()->expr->name->toString()), ['true', 'false'], true) + && ( + $nativeFunctionReturnType->isBoolean()->yes() + || $phpDocFunctionReturnType->isBoolean()->yes() + ) + ) { + return true; + } + + // Do not require to have @return null/true/false in descendant classes + return $checkDescendantClass + && ($returnType->isNull()->yes() || $returnType->isTrue()->yes() || $returnType->isFalse()->yes()); + } + + /** + * The declared return type checkFunctionReturnType() narrows, and whether it is the native one. + * + * @return array{Type, bool} + */ + private function getCheckedReturnType(ExtendedParametersAcceptor $variant): array + { + $phpDocReturnType = $variant->getPhpDocReturnType(); + if (!$phpDocReturnType instanceof MixedType || $phpDocReturnType->isExplicitMixed()) { + return [TypeUtils::resolveLateResolvableTypes(TypehintHelper::decideType($variant->getNativeReturnType(), $phpDocReturnType)), false]; + } + + return [$variant->getNativeReturnType(), true]; + } + + /** + * @return array{string, string} + */ + private function getReturnTypeMessagePatterns(string $functionDescription): array + { + return [ + sprintf('%s never returns %%s so it can be removed from the return type.', $functionDescription), + sprintf('%s never returns %%s so the return type can be changed to %%s.', $functionDescription), + ]; + } + /** * @param 'paramOut'|'parameterByRef' $identifierPart * @return list @@ -348,6 +459,55 @@ public function checkParameterOutType( ); } + /** + * Like createOverridableReturnTypeErrors(), for the type of a parameter passed by reference after the call. + * + * @param 'paramOut'|'parameterByRef' $identifierPart + * @return array{list, list}|null + */ + public function createOverridableParameterOutTypeErrors( + Type $parameterOutType, + Type $actualVariableType, + string $unionMessagePattern, + string $boolMessagePattern, + Scope $scope, + string $identifierPart, + ?string $tip, + ): ?array + { + $parameterOutType = TypeUtils::resolveLateResolvableTypes($parameterOutType); + $members = $this->getRemovableMembers($parameterOutType, $scope, false); + if ($members === null) { + return null; + } + + return [ + $this->getUsedMembers($parameterOutType, $members, $actualVariableType, false), + $this->createMemberErrors($parameterOutType, $members, $unionMessagePattern, $boolMessagePattern, $identifierPart, $tip), + ]; + } + + /** + * Like getUsedOverriddenReturnTypeMembers(), for the type of a parameter passed by reference after the call. + * All members when the type the overriding method assigns is not known. + * + * @return list|null + */ + public function getUsedOverriddenParameterOutTypeMembers(Type $parameterOutType, ?Type $actualVariableType, Scope $scope): ?array + { + $parameterOutType = TypeUtils::resolveLateResolvableTypes($parameterOutType); + $members = $this->getRemovableMembers($parameterOutType, $scope, false); + if ($members === null) { + return null; + } + + if ($actualVariableType === null) { + return array_keys($members); + } + + return $this->getUsedMembers($parameterOutType, $members, $actualVariableType, false); + } + /** * @param 'return'|'property'|'paramOut'|'parameterByRef' $identifierPart * @return list @@ -435,76 +595,134 @@ private function narrowType( bool $native, ): Type { - if ($declaredType instanceof UnionType) { - if ( - $declaredType->isConstantScalarValue()->yes() - && $actualReturnType->isConstantScalarValue()->yes() - ) { - return $declaredType; - } - $usedTypes = []; - foreach ($declaredType->getTypes() as $innerType) { - if ($innerType->isSuperTypeOf($actualReturnType)->no()) { - if (!$checkDescendantClass) { - continue; - } - if ($innerType->isNull()->yes()) { - $usedTypes[] = $innerType; - continue; - } - if ( - !$actualReturnType->isTrue()->yes() - && !$actualReturnType->isFalse()->yes() - && !$actualReturnType->isNull()->yes() - ) { - continue; - } - } + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return $declaredType; + } - $usedTypes[] = $innerType; - } + $usedMembers = $this->getUsedMembers($declaredType, $members, $actualReturnType, $checkDescendantClass); + if (count($usedMembers) === count($members)) { + return $declaredType; + } + + $usedTypes = []; + foreach ($usedMembers as $i) { + $usedTypes[] = $members[$i]; + } + + return TypeCombinator::union(...$usedTypes); + } - return TypeCombinator::union(...$usedTypes); + /** + * The members of the declared type that can be removed from it when they are not used, + * null when the type cannot be narrowed this way. + * + * @return list|null + */ + private function getRemovableMembers(Type $declaredType, Scope $scope, bool $native): ?array + { + if ($declaredType instanceof UnionType) { + return $declaredType->getTypes(); } if (!$this->reportTooWideBool) { - return $declaredType; + return null; } if ($native && !$scope->getPhpVersion()->supportsTrueAndFalseStandaloneType()->yes()) { - return $declaredType; + return null; } if (!$declaredType->isBoolean()->yes()) { - return $declaredType; + return null; } if ( $declaredType->isTrue()->yes() || $declaredType->isFalse()->yes() ) { - return $declaredType; + return null; } - $usedTypes = []; - foreach ($declaredType->getFiniteTypes() as $innerType) { - if ($innerType->isSuperTypeOf($actualReturnType)->no()) { + return $declaredType->getFiniteTypes(); + } + + /** + * @param list $members + * @return list + */ + private function getUsedMembers(Type $declaredType, array $members, Type $actualType, bool $checkDescendantClass): array + { + if ( + $declaredType instanceof UnionType + && $declaredType->isConstantScalarValue()->yes() + && $actualType->isConstantScalarValue()->yes() + ) { + return array_keys($members); + } + + $usedMembers = []; + foreach ($members as $i => $member) { + if ($member->isSuperTypeOf($actualType)->no()) { if (!$checkDescendantClass) { continue; } if ( - !$actualReturnType->isTrue()->yes() - && !$actualReturnType->isFalse()->yes() - && !$actualReturnType->isNull()->yes() + !$member->isNull()->yes() + && !$actualType->isTrue()->yes() + && !$actualType->isFalse()->yes() + && !$actualType->isNull()->yes() ) { continue; } } - $usedTypes[] = $innerType; + $usedMembers[] = $i; } - return TypeCombinator::union(...$usedTypes); + return $usedMembers; + } + + /** + * The error createErrors() reports for each member when only that member is not used. + * + * @param list $members + * @param 'return'|'paramOut'|'parameterByRef' $identifierPart + * @return list message, identifier, tip + */ + private function createMemberErrors( + Type $declaredType, + array $members, + string $unionMessagePattern, + string $boolMessagePattern, + string $identifierPart, + ?string $tip, + ): array + { + $errors = []; + foreach ($members as $i => $member) { + if ($declaredType->isBoolean()->yes()) { + $usedMember = $members[1 - $i]; + $errors[] = [ + sprintf( + $boolMessagePattern, + $member->describe(VerbosityLevel::getRecommendedLevelByType($member)), + $usedMember->describe(VerbosityLevel::getRecommendedLevelByType($usedMember)), + ), + sprintf('%s.tooWideBool', $identifierPart), + $tip, + ]; + continue; + } + + $errors[] = [ + sprintf($unionMessagePattern, $member->describe(VerbosityLevel::getRecommendedLevelByType($member))), + sprintf('%s.unusedType', $identifierPart), + $tip, + ]; + } + + return $errors; } } diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php new file mode 100644 index 00000000000..4b4f4d8f949 --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php @@ -0,0 +1,28 @@ +, errors: list, usedMembersTip: string|null, memberDescriptions: list}> + */ +final class TooWideTypeInOverridableMemberCollector implements Collector +{ + + public function getNodeType(): string + { + throw new ShouldNotHappenException(); + } + + public function processNode(Node $node, Scope $scope) + { + throw new ShouldNotHappenException(); + } + +} diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php new file mode 100644 index 00000000000..33499ca271d --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php @@ -0,0 +1,99 @@ + + */ +#[RegisteredRule(level: 4)] +final class TooWideTypeInOverridableMemberRule implements Rule +{ + + public function getNodeType(): string + { + return CollectedDataNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $declarations = $node->get(TooWideTypeInOverridableMemberCollector::class); + // the members overriding the declarations might not be analysed + if ($declarations === [] || $node->isOnlyFilesAnalysis()) { + return []; + } + + $usedByOverridingMembers = []; + foreach ($node->get(TypeUsedInOverridingMemberCollector::class) as $usages) { + foreach ($usages as $usage) { + foreach ($usage['used'] as $i) { + $usedByOverridingMembers[$usage['kind']][$usage['class']][$usage['member']][$usage['slot']][$i] = true; + } + } + } + + $errors = []; + foreach ($declarations as $file => $fileDeclarations) { + foreach ($fileDeclarations as $declaration) { + $usedMembers = $usedByOverridingMembers[$declaration['kind']][$declaration['class']][$declaration['member']][$declaration['slot']] ?? []; + foreach ($declaration['used'] as $i) { + $usedMembers[$i] = true; + } + + if (count($usedMembers) >= count($declaration['errors'])) { + continue; + } + + $usedMembersTip = null; + if ($declaration['usedMembersTip'] !== null) { + $usedMemberDescriptions = []; + foreach ($declaration['memberDescriptions'] as $i => $memberDescription) { + if (!isset($usedMembers[$i])) { + continue; + } + + $usedMemberDescriptions[] = $memberDescription; + } + + $usedMembersTip = sprintf( + $declaration['usedMembersTip'], + count($usedMemberDescriptions) === 0 ? 'void' : implode('|', $usedMemberDescriptions), + ); + } + + foreach ($declaration['errors'] as $i => [$message, $identifier, $tip]) { + if (isset($usedMembers[$i])) { + continue; + } + + $builder = RuleErrorBuilder::message($message) + ->identifier($identifier) + ->file($declaration['file'] ?? $file, $declaration['fileDescription']) + ->line($declaration['line']); + $tip ??= $usedMembersTip; + if ($tip !== null) { + $builder->tip($tip); + } + + $errors[] = $builder->build(); + } + } + } + + return $errors; + } + +} diff --git a/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php new file mode 100644 index 00000000000..e0a5d00b981 --- /dev/null +++ b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php @@ -0,0 +1,28 @@ +}> + */ +final class TypeUsedInOverridingMemberCollector implements Collector +{ + + public function getNodeType(): string + { + throw new ShouldNotHappenException(); + } + + public function processNode(Node $node, Scope $scope) + { + throw new ShouldNotHappenException(); + } + +} diff --git a/tests/PHPStan/Rules/Exceptions/TooWideMethodThrowTypeRuleTest.php b/tests/PHPStan/Rules/Exceptions/TooWideMethodThrowTypeRuleTest.php index 7697d0e2c18..61e23fce035 100644 --- a/tests/PHPStan/Rules/Exceptions/TooWideMethodThrowTypeRuleTest.php +++ b/tests/PHPStan/Rules/Exceptions/TooWideMethodThrowTypeRuleTest.php @@ -3,17 +3,23 @@ namespace PHPStan\Rules\Exceptions; use PHPStan\Rules\Rule; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; +use PHPStan\Rules\TooWideTypehints\TooWideTypeInOverridableMemberRule; +use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; use PHPStan\Type\FileTypeMapper; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhp; /** - * @extends RuleTestCase + * @extends RuleTestCase */ class TooWideMethodThrowTypeRuleTest extends RuleTestCase { + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + private bool $implicitThrows = true; private bool $checkProtectedAndPublicMethods = true; @@ -22,12 +28,17 @@ class TooWideMethodThrowTypeRuleTest extends RuleTestCase protected function getRule(): Rule { - return new TooWideMethodThrowTypeRule( - self::getContainer()->getByType(FileTypeMapper::class), - new TooWideThrowTypeCheck($this->implicitThrows), - $this->checkProtectedAndPublicMethods, - $this->tooWideImplicitThrows, - ); + // @phpstan-ignore argument.type + return new CompositeRule([ + new TooWideMethodThrowTypeRule( + self::getContainer()->getByType(FileTypeMapper::class), + new TooWideThrowTypeCheck($this->implicitThrows), + $this->checkProtectedAndPublicMethods, + $this->tooWideImplicitThrows, + new OverridableMemberHelper($this->projectType), + ), + new TooWideTypeInOverridableMemberRule(), + ]); } public function testRule(): void @@ -189,4 +200,21 @@ public function testTooWideImplicitThrows(bool $tooWideImplicitThrows, array $ex $this->analyse([__DIR__ . '/data/too-wide-implicit-throws.php'], $expectedErrors); } + public function testClosedProject(): void + { + $this->projectType = 'closed'; + // has no effect in a closed project + $this->checkProtectedAndPublicMethods = false; + $this->analyse([__DIR__ . '/data/too-wide-throws-method-closed-project.php'], [ + [ + 'Method TooWideThrowsMethodClosedProject\\ParentClass::doFoo() has TooWideThrowsMethodClosedProject\\BazException in PHPDoc @throws tag but it\'s not thrown.', + 26, + ], + [ + 'Method TooWideThrowsMethodClosedProject\\ParentClass::notOverridden() has TooWideThrowsMethodClosedProject\\BarException in PHPDoc @throws tag but it\'s not thrown.', + 34, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Exceptions/TooWidePropertyHookThrowTypeRuleTest.php b/tests/PHPStan/Rules/Exceptions/TooWidePropertyHookThrowTypeRuleTest.php index cbda0882992..e372afb40d8 100644 --- a/tests/PHPStan/Rules/Exceptions/TooWidePropertyHookThrowTypeRuleTest.php +++ b/tests/PHPStan/Rules/Exceptions/TooWidePropertyHookThrowTypeRuleTest.php @@ -3,21 +3,31 @@ namespace PHPStan\Rules\Exceptions; use PHPStan\Rules\Rule; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; +use PHPStan\Rules\TooWideTypehints\TooWideTypeInOverridableMemberRule; +use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhp; /** - * @extends RuleTestCase + * @extends RuleTestCase */ class TooWidePropertyHookThrowTypeRuleTest extends RuleTestCase { + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + private bool $checkProtectedAndPublicMethods = true; protected function getRule(): Rule { - return new TooWidePropertyHookThrowTypeRule(new TooWideThrowTypeCheck(true), $this->checkProtectedAndPublicMethods); + // @phpstan-ignore argument.type + return new CompositeRule([ + new TooWidePropertyHookThrowTypeRule(new TooWideThrowTypeCheck(true), $this->checkProtectedAndPublicMethods, new OverridableMemberHelper($this->projectType)), + new TooWideTypeInOverridableMemberRule(), + ]); } #[RequiresPhp('>= 8.4.0')] @@ -117,4 +127,18 @@ public function testAlwaysCheckFinal(bool $checkProtectedAndPublicMethods, array $this->analyse([__DIR__ . '/data/too-wide-throw-type-always-check-final-property-hooks.php'], $expectedErrors); } + #[RequiresPhp('>= 8.4.0')] + public function testClosedProject(): void + { + $this->projectType = 'closed'; + // has no effect in a closed project + $this->checkProtectedAndPublicMethods = false; + $this->analyse([__DIR__ . '/data/too-wide-throws-property-hook-closed-project.php'], [ + [ + 'Get hook for property TooWideThrowsPropertyHookClosedProject\\ParentClass::$a has RuntimeException in PHPDoc @throws tag but it\'s not thrown.', + 10, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Exceptions/data/too-wide-throws-method-closed-project.php b/tests/PHPStan/Rules/Exceptions/data/too-wide-throws-method-closed-project.php new file mode 100644 index 00000000000..2f15ea3fb67 --- /dev/null +++ b/tests/PHPStan/Rules/Exceptions/data/too-wide-throws-method-closed-project.php @@ -0,0 +1,52 @@ += 8.4 + +namespace TooWideThrowsPropertyHookClosedProject; + +class ParentClass +{ + + public int $a { + /** @throws \InvalidArgumentException|\DomainException|\RuntimeException */ + get { + throw new \InvalidArgumentException(); + } + } + +} + +class ChildClass extends ParentClass +{ + + public int $a { + /** @throws \DomainException */ + get { + throw new \DomainException(); + } + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRuleTest.php b/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRuleTest.php index 56824b30bc1..ec746d1369d 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRuleTest.php +++ b/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodParameterOutTypeRuleTest.php @@ -4,25 +4,34 @@ use PHPStan\Rules\Properties\PropertyReflectionFinder; use PHPStan\Rules\Rule as TRule; +use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; /** - * @extends RuleTestCase + * @extends RuleTestCase */ class TooWideMethodParameterOutTypeRuleTest extends RuleTestCase { + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + private bool $checkProtectedAndPublicMethods = true; protected function getRule(): TRule { - return new TooWideMethodParameterOutTypeRule( - new TooWideParameterOutTypeCheck( - new TooWideTypeCheck(new PropertyReflectionFinder(), true, true), + // @phpstan-ignore argument.type + return new CompositeRule([ + new TooWideMethodParameterOutTypeRule( + new TooWideParameterOutTypeCheck( + new TooWideTypeCheck(new PropertyReflectionFinder(), true, true), + ), + $this->checkProtectedAndPublicMethods, + new OverridableMemberHelper($this->projectType), ), - $this->checkProtectedAndPublicMethods, - ); + new TooWideTypeInOverridableMemberRule(), + ]); } public function testRule(): void @@ -157,4 +166,29 @@ public function testBug15066(): void ]); } + public function testClosedProject(): void + { + $this->projectType = 'closed'; + // has no effect in a closed project + $this->checkProtectedAndPublicMethods = false; + $this->analyse([__DIR__ . '/data/too-wide-method-parameter-out-closed-project.php'], [ + [ + 'Method TooWideMethodParameterOutClosedProject\\ParentClass::doFoo() never assigns null to &$p so it can be removed from the @param-out type.', + 11, + ], + [ + 'Method TooWideMethodParameterOutClosedProject\\ParentClass::notOverridden() never assigns string to &$p so it can be removed from the @param-out type.', + 19, + ], + [ + 'Method TooWideMethodParameterOutClosedProject\\ChildClass::doFoo() never assigns int to &$q so it can be removed from the @param-out type.', + 32, + ], + [ + 'Method TooWideMethodParameterOutClosedProject\\ChildClass::doFoo() never assigns null to &$q so it can be removed from the @param-out type.', + 32, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodReturnTypehintRuleTest.php b/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodReturnTypehintRuleTest.php index 30646844dd6..80b4a6e438c 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodReturnTypehintRuleTest.php +++ b/tests/PHPStan/Rules/TooWideTypehints/TooWideMethodReturnTypehintRuleTest.php @@ -4,16 +4,20 @@ use PHPStan\Rules\Properties\PropertyReflectionFinder; use PHPStan\Rules\Rule; +use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhp; /** - * @extends RuleTestCase + * @extends RuleTestCase */ class TooWideMethodReturnTypehintRuleTest extends RuleTestCase { + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + private bool $checkProtectedAndPublicMethods = true; private bool $reportTooWideBool = false; @@ -22,7 +26,11 @@ class TooWideMethodReturnTypehintRuleTest extends RuleTestCase protected function getRule(): Rule { - return new TooWideMethodReturnTypehintRule($this->checkProtectedAndPublicMethods, new TooWideTypeCheck(new PropertyReflectionFinder(), $this->reportTooWideBool, $this->reportNestedTooWideType)); + // @phpstan-ignore argument.type + return new CompositeRule([ + new TooWideMethodReturnTypehintRule($this->checkProtectedAndPublicMethods, new TooWideTypeCheck(new PropertyReflectionFinder(), $this->reportTooWideBool, $this->reportNestedTooWideType), new OverridableMemberHelper($this->projectType)), + new TooWideTypeInOverridableMemberRule(), + ]); } public function testPrivate(): void @@ -315,4 +323,30 @@ public function testBug11430(): void $this->analyse([__DIR__ . '/data/bug-11430.php'], []); } + #[RequiresPhp('>= 8.0.0')] + public function testClosedProject(): void + { + $this->projectType = 'closed'; + // has no effect in a closed project + $this->checkProtectedAndPublicMethods = false; + $this->analyse([__DIR__ . '/data/too-wide-method-return-type-closed-project.php'], [ + [ + 'Method TooWideMethodReturnTypeClosedProject\\ParentClass::notOverridden() never returns string so it can be removed from the return type.', + 13, + ], + [ + 'Method TooWideMethodReturnTypeClosedProject\\ParentClass::overriddenWithoutUsingIt() never returns string so it can be removed from the return type.', + 18, + ], + [ + 'Method TooWideMethodReturnTypeClosedProject\\ChildClass::returnsIntOrString() never returns int so it can be removed from the return type.', + 28, + ], + [ + 'Method TooWideMethodReturnTypeClosedProject\\FinalClass::doFoo() never returns string so it can be removed from the return type.', + 43, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/too-wide-method-parameter-out-closed-project.php b/tests/PHPStan/Rules/TooWideTypehints/data/too-wide-method-parameter-out-closed-project.php new file mode 100644 index 00000000000..16e1feb6c73 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/too-wide-method-parameter-out-closed-project.php @@ -0,0 +1,37 @@ += 8.0 + +namespace TooWideMethodReturnTypeClosedProject; + +class ParentClass +{ + + public function returnsIntOrString(): int|string|null + { + return 1; + } + + public function notOverridden(): int|string + { + return 1; + } + + protected function overriddenWithoutUsingIt(): int|string + { + return 1; + } + +} + +class ChildClass extends ParentClass +{ + + public function returnsIntOrString(): int|string|null + { + return 'foo'; + } + + protected function overriddenWithoutUsingIt(): int + { + return 2; + } + +} + +final class FinalClass +{ + + public function doFoo(): int|string + { + return 1; + } + +} + +class GrandChildClass extends ChildClass +{ + + public function returnsIntOrString(): int|string|null + { + return null; + } + +} From 167cc121301838546f0c1719783bc5815e0792f8 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 15:52:45 +0000 Subject: [PATCH 04/24] Record the scope of yields in function and method return statements nodes MethodReturnStatementsNode and FunctionReturnStatementsNode now keep the scope each yield was evaluated in, next to the yield node itself, so rules can read the key and value types of yields the same way they read the types of returned expressions. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../StmtHandler/ClassMethodHandler.php | 3 +- src/Analyser/StmtHandler/FunctionHandler.php | 3 +- src/Node/FunctionReturnStatementsNode.php | 13 +++++++- src/Node/MethodReturnStatementsNode.php | 13 +++++++- src/Node/YieldStatement.php | 33 +++++++++++++++++++ turbo-ext/src/ClassMethodHandler.cpp | 5 ++- turbo-ext/src/FunctionHandler.cpp | 5 ++- turbo-ext/src/support.cpp | 1 + turbo-ext/src/support.h | 1 + 9 files changed, 71 insertions(+), 6 deletions(-) create mode 100644 src/Node/YieldStatement.php diff --git a/src/Analyser/StmtHandler/ClassMethodHandler.php b/src/Analyser/StmtHandler/ClassMethodHandler.php index eb08face0f8..4faddde4480 100644 --- a/src/Analyser/StmtHandler/ClassMethodHandler.php +++ b/src/Analyser/StmtHandler/ClassMethodHandler.php @@ -34,6 +34,7 @@ use PHPStan\Node\PropertyAssignNode; use PHPStan\Node\ReturnAfterFinallyNode; use PHPStan\Node\ReturnStatement; +use PHPStan\Node\YieldStatement; use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection; use PHPStan\ShouldNotHappenException; use PHPStan\Turbo\ShadowedByTurboExtension; @@ -228,7 +229,7 @@ public function processStmt( return; } if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) { - $gatheredYieldStatements[] = $node; + $gatheredYieldStatements[] = new YieldStatement($scope, $node); } if (!$node instanceof Return_) { return; diff --git a/src/Analyser/StmtHandler/FunctionHandler.php b/src/Analyser/StmtHandler/FunctionHandler.php index 1c1611ee03f..53adabfd441 100644 --- a/src/Analyser/StmtHandler/FunctionHandler.php +++ b/src/Analyser/StmtHandler/FunctionHandler.php @@ -29,6 +29,7 @@ use PHPStan\Node\PropertyAssignNode; use PHPStan\Node\ReturnAfterFinallyNode; use PHPStan\Node\ReturnStatement; +use PHPStan\Node\YieldStatement; use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection; use PHPStan\ShouldNotHappenException; use PHPStan\Turbo\ShadowedByTurboExtension; @@ -143,7 +144,7 @@ public function processStmt( return; } if ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom) { - $gatheredYieldStatements[] = $node; + $gatheredYieldStatements[] = new YieldStatement($scope, $node); } if (!$node instanceof Return_) { return; diff --git a/src/Node/FunctionReturnStatementsNode.php b/src/Node/FunctionReturnStatementsNode.php index 476ada5788c..ed5f002bd87 100644 --- a/src/Node/FunctionReturnStatementsNode.php +++ b/src/Node/FunctionReturnStatementsNode.php @@ -12,6 +12,7 @@ use PHPStan\Analyser\StatementResult; use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection; use PHPStan\Turbo\ReferencedByTurboExtension; +use function array_map; use function count; /** @@ -24,7 +25,7 @@ final class FunctionReturnStatementsNode extends NodeAbstract implements ReturnS /** * @param list $returnStatements * @param list $returnStatementsAfterFinally - * @param list $yieldStatements + * @param list $yieldStatements * @param list $executionEnds * @param ImpurePoint[] $impurePoints */ @@ -83,6 +84,16 @@ public function hasNativeReturnTypehint(): bool } public function getYieldStatements(): array + { + return array_map(static fn (YieldStatement $statement): Yield_|YieldFrom => $statement->getYieldNode(), $this->yieldStatements); + } + + /** + * The yields with the scopes they are in. + * + * @return list + */ + public function getYieldStatementsWithScope(): array { return $this->yieldStatements; } diff --git a/src/Node/MethodReturnStatementsNode.php b/src/Node/MethodReturnStatementsNode.php index adc2f9a68ad..ee0a5067122 100644 --- a/src/Node/MethodReturnStatementsNode.php +++ b/src/Node/MethodReturnStatementsNode.php @@ -13,6 +13,7 @@ use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection; use PHPStan\Turbo\ReferencedByTurboExtension; +use function array_map; use function count; /** @@ -27,7 +28,7 @@ final class MethodReturnStatementsNode extends NodeAbstract implements ReturnSta /** * @param list $returnStatements * @param list $returnStatementsAfterFinally - * @param list $yieldStatements + * @param list $yieldStatements * @param list $executionEnds * @param ImpurePoint[] $impurePoints */ @@ -93,6 +94,16 @@ public function getMethodName(): string } public function getYieldStatements(): array + { + return array_map(static fn (YieldStatement $statement): Yield_|YieldFrom => $statement->getYieldNode(), $this->yieldStatements); + } + + /** + * The yields with the scopes they are in. + * + * @return list + */ + public function getYieldStatementsWithScope(): array { return $this->yieldStatements; } diff --git a/src/Node/YieldStatement.php b/src/Node/YieldStatement.php new file mode 100644 index 00000000000..70dcc6e27c9 --- /dev/null +++ b/src/Node/YieldStatement.php @@ -0,0 +1,33 @@ +scope; + } + + public function getYieldNode(): Yield_|YieldFrom + { + return $this->yieldNode; + } + +} diff --git a/turbo-ext/src/ClassMethodHandler.cpp b/turbo-ext/src/ClassMethodHandler.cpp index 91bda2883b1..0d78c0d4dff 100644 --- a/turbo-ext/src/ClassMethodHandler.cpp +++ b/turbo-ext/src/ClassMethodHandler.cpp @@ -692,7 +692,10 @@ class ClassMethodHandler bool isYield = ptsh::isInstanceOf(node, PT_CLASS_YIELD, error) || ptsh::isInstanceOf(node, PT_CLASS_YIELD_FROM, error); if (UNEXPECTED(error)) return; if (isYield) { - ptsh::appendToReference(&captures[4], node); + zv::Args yieldStatementArgv{scope, node}; + zv::Val yieldStatement = pt_type_new(PT_CLASS_YIELD_STATEMENT, 2, yieldStatementArgv); + if (UNEXPECTED(yieldStatement.isUndef())) return; + ptsh::appendToReference(&captures[4], yieldStatement.raw()); } bool isReturn = ptsh::isInstanceOf(node, PT_CLASS_RETURN_STMT, error); if (!isReturn) return; diff --git a/turbo-ext/src/FunctionHandler.cpp b/turbo-ext/src/FunctionHandler.cpp index a45072e6cf7..0581d20b6ae 100644 --- a/turbo-ext/src/FunctionHandler.cpp +++ b/turbo-ext/src/FunctionHandler.cpp @@ -353,7 +353,10 @@ class FunctionHandler bool isYield = ptsh::isInstanceOf(node, PT_CLASS_YIELD, error) || ptsh::isInstanceOf(node, PT_CLASS_YIELD_FROM, error); if (UNEXPECTED(error)) return; if (isYield) { - ptsh::appendToReference(&captures[3], node); + zv::Args yieldStatementArgv{scope, node}; + zv::Val yieldStatement = pt_type_new(PT_CLASS_YIELD_STATEMENT, 2, yieldStatementArgv); + if (UNEXPECTED(yieldStatement.isUndef())) return; + ptsh::appendToReference(&captures[3], yieldStatement.raw()); } bool isReturn = ptsh::isInstanceOf(node, PT_CLASS_RETURN_STMT, error); if (!isReturn) return; diff --git a/turbo-ext/src/support.cpp b/turbo-ext/src/support.cpp index 0ccef7b2f03..a908d83efe4 100644 --- a/turbo-ext/src/support.cpp +++ b/turbo-ext/src/support.cpp @@ -300,6 +300,7 @@ static const pt_class_template pt_class_templates[PT_CLASS_COUNT] = { /* PT_CLASS_FUNCTION_RETURN_STATEMENTS_NODE */ {"functionReturnStatementsNode", "PHPStan\\Node\\FunctionReturnStatementsNode"}, /* PT_CLASS_RETURN_AFTER_FINALLY_NODE */ {"returnAfterFinallyNode", "PHPStan\\Node\\ReturnAfterFinallyNode"}, /* PT_CLASS_RETURN_STATEMENT */ {"returnStatement", "PHPStan\\Node\\ReturnStatement"}, + /* PT_CLASS_YIELD_STATEMENT */ {"yieldStatement", "PHPStan\\Node\\YieldStatement"}, /* PT_CLASS_IN_CLASS_NODE */ {"inClassNode", "PHPStan\\Node\\InClassNode"}, /* PT_CLASS_CLASS_PROPERTIES_NODE */ {"classPropertiesNode", "PHPStan\\Node\\ClassPropertiesNode"}, /* PT_CLASS_CLASS_METHODS_NODE */ {"classMethodsNode", "PHPStan\\Node\\ClassMethodsNode"}, diff --git a/turbo-ext/src/support.h b/turbo-ext/src/support.h index 3fa62464769..a732c810987 100644 --- a/turbo-ext/src/support.h +++ b/turbo-ext/src/support.h @@ -390,6 +390,7 @@ enum { PT_CLASS_FUNCTION_RETURN_STATEMENTS_NODE, PT_CLASS_RETURN_AFTER_FINALLY_NODE, PT_CLASS_RETURN_STATEMENT, + PT_CLASS_YIELD_STATEMENT, PT_CLASS_IN_CLASS_NODE, PT_CLASS_CLASS_PROPERTIES_NODE, PT_CLASS_CLASS_METHODS_NODE, From 0ee64769011d6404f599a9caafefadefde7812bb Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 13:50:41 +0000 Subject: [PATCH 05/24] Fix missing return types with the returned type under the fixMissingReturnTypes feature toggle Bleeding edge enables the toggle. The missingType.return and missingType.iterableValue errors are fixed with a native return type of the type the function returns: void when it returns nothing, never when it always throws, and the Generator its yields describe for a generator, read from the scopes the return statements node records for its yields. Its TSend is what the generators it delegates to with yield from accept, the intersection of their TSend types, and mixed when it delegates to none. A function returning a value and also nothing is not fixed, PHP and PHPStan would report it. Without native union types, objects are declared natively as their closest common parent class. A type with mixed in it, even explicit mixed or an array of mixed values, is not written (the mixed key type of array excepted): callers would lose precision, while a later round may infer a more specific type once the callees are typed. Only the TSend of a Generator is mixed when nothing restricts what can be sent to it. A @return PHPDoc tag is added only when the native type does not say everything: for iterables, callables and generic classes it carries the full returned type, and when the PHP version cannot declare the type natively, like static on PHP 7.4 or never on PHP 8.0, it carries the type the newest PHP version would declare. The methods overriding a method that can be overridden in a closed project are known only after the analysis, so MissingReturnTypeFixRule reports and fixes these errors. The return type of such a method covers what the overriding methods return, and its native type is declared only when every overriding method has one or gets one with its own fix. Methods that can be overridden in an open project are not fixed. A method of a trait, private ones too, is fixed in MissingReturnTypeFixRule as well: the rules emit what it returns in each class using the trait, with the types resolved in the trait so that $this is static, and its return type covers all of them, one fix shared by all the classes. The errors are still reported in the context of each class. When the trait method can be overridden, it is fixed only in a closed project, covering the overriding methods. The fixes are tested for PHP 7.4, 8.0, 8.1 and 8.2 with a phpVersion configuration file each. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- Makefile | 1 + conf/bleedingEdge.neon | 1 + conf/config.neon | 1 + conf/parametersSchema.neon | 1 + .../MissingFunctionReturnTypehintRule.php | 66 ++- ...ingImplementedMethodReturnTypehintRule.php | 151 +++++- .../MissingMethodReturnTypehintRule.php | 54 ++- src/Rules/MissingReturnTypeCollector.php | 44 ++ src/Rules/MissingReturnTypeFixRule.php | 317 ++++++++++++ src/Rules/MissingReturnTypeFixer.php | 452 ++++++++++++++++++ tests/PHPStan/Generics/data/functions-6.json | 3 +- tests/PHPStan/Generics/data/pick-6.json | 3 +- .../Generics/data/varyingAcceptor-6.json | 3 +- tests/PHPStan/Levels/data/acceptTypes-6.json | 6 +- .../Levels/data/callableVariance-6.json | 6 +- .../MissingFunctionReturnTypehintRuleTest.php | 6 +- ...mplementedMethodReturnTypehintRuleTest.php | 8 +- .../MissingMethodReturnTypehintRuleTest.php | 8 +- .../Rules/MissingReturnTypeFixPhp74Test.php | 13 + .../Rules/MissingReturnTypeFixPhp80Test.php | 13 + .../Rules/MissingReturnTypeFixPhp81Test.php | 13 + .../Rules/MissingReturnTypeFixPhp82Test.php | 13 + .../Rules/MissingReturnTypeFixTestCase.php | 138 ++++++ .../data/fix-missing-return-type-php74.neon | 4 + .../data/fix-missing-return-type-php80.neon | 4 + .../data/fix-missing-return-type-php81.neon | 4 + .../data/fix-missing-return-type-php82.neon | 4 + .../functions-php74.php.fixed | 147 ++++++ .../functions-php80.php.fixed | 147 ++++++ .../functions-php81.php.fixed | 144 ++++++ .../functions-php82.php.fixed | 141 ++++++ .../functions-with-ignores-php74.php.fixed | 43 ++ .../functions-with-ignores-php80.php.fixed | 43 ++ .../functions-with-ignores-php81.php.fixed | 43 ++ .../functions-with-ignores-php82.php.fixed | 43 ++ .../functions-with-ignores.php | 40 ++ .../fix-missing-return-type/functions.php | 125 +++++ .../methods-closed-project-php74.php.fixed | 134 ++++++ .../methods-closed-project-php80.php.fixed | 125 +++++ .../methods-closed-project-php81.php.fixed | 122 +++++ .../methods-closed-project-php82.php.fixed | 122 +++++ .../methods-open-project-php74.php.fixed | 122 +++++ .../methods-open-project-php80.php.fixed | 119 +++++ .../methods-open-project-php81.php.fixed | 116 +++++ .../methods-open-project-php82.php.fixed | 116 +++++ .../data/fix-missing-return-type/methods.php | 116 +++++ .../traits-closed-project-php74.php.fixed | 238 +++++++++ .../traits-closed-project-php80.php.fixed | 232 +++++++++ .../traits-closed-project-php81.php.fixed | 232 +++++++++ .../traits-closed-project-php82.php.fixed | 232 +++++++++ .../traits-open-project-php74.php.fixed | 238 +++++++++ .../traits-open-project-php80.php.fixed | 232 +++++++++ .../traits-open-project-php81.php.fixed | 232 +++++++++ .../traits-open-project-php82.php.fixed | 232 +++++++++ .../data/fix-missing-return-type/traits.php | 229 +++++++++ 55 files changed, 5402 insertions(+), 40 deletions(-) create mode 100644 src/Rules/MissingReturnTypeCollector.php create mode 100644 src/Rules/MissingReturnTypeFixRule.php create mode 100644 src/Rules/MissingReturnTypeFixer.php create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixPhp74Test.php create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixPhp80Test.php create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixPhp81Test.php create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixPhp82Test.php create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores.php create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions.php create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods.php create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits.php diff --git a/Makefile b/Makefile index 32ae3cd51f9..989758c626e 100644 --- a/Makefile +++ b/Makefile @@ -20,6 +20,7 @@ lint: --exclude tests/PHPStan/Analyser/nsrt \ --exclude tests/PHPStan/Rules/Methods/data \ --exclude tests/PHPStan/Rules/Functions/data \ + --exclude tests/PHPStan/Rules/data/fix-missing-return-type \ --exclude tests/PHPStan/Rules/Names/data \ --exclude tests/PHPStan/Rules/Operators/data/invalid-inc-dec.php \ --exclude tests/PHPStan/Rules/Arrays/data/offset-access-without-dim-for-reading.php \ diff --git a/conf/bleedingEdge.neon b/conf/bleedingEdge.neon index d82b36a0599..7500d488850 100644 --- a/conf/bleedingEdge.neon +++ b/conf/bleedingEdge.neon @@ -12,6 +12,7 @@ parameters: checkExtensionsForComparisonOperators: true checkGenericIterableClasses: true reportTooWideBool: true + fixMissingReturnTypes: true rawMessageInBaseline: true reportNestedTooWideType: false # tmp assignToByRefForeachExpr: true diff --git a/conf/config.neon b/conf/config.neon index aaae7ff73cf..cbd68829cd3 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -74,6 +74,7 @@ parameters: checkConditionalParameterTypes: false checkMixedWitnessTypes: false recursiveLoopTypes: false + fixMissingReturnTypes: false fileExtensions: - php checkAdvancedIsset: false diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index 769b6be85d9..2e6005aae9e 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -71,6 +71,7 @@ parametersSchema: checkConditionalParameterTypes: bool() checkMixedWitnessTypes: bool() recursiveLoopTypes: bool() + fixMissingReturnTypes: bool() ]) fileExtensions: listOf(string()) checkAdvancedIsset: bool() diff --git a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php index cfa44a4b618..0b4c2dd3497 100644 --- a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php +++ b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php @@ -7,6 +7,8 @@ use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; use PHPStan\Node\FunctionReturnStatementsNode; +use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; @@ -24,6 +26,7 @@ final class MissingFunctionReturnTypehintRule implements Rule public function __construct( private MissingTypehintCheck $missingTypehintCheck, + private MissingReturnTypeFixer $fixer, ) { } @@ -38,21 +41,26 @@ public function processNode(Node $node, Scope $scope): array $functionReflection = $node->getFunctionReflection(); $returnType = $functionReflection->getReturnType(); + $errors = []; if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { - return [ - RuleErrorBuilder::message(sprintf( - 'Function %s() has no return type specified.', - $functionReflection->getName(), - ))->identifier('missingType.return')->build(), + $errors[] = [ + sprintf('Function %s() has no return type specified.', $functionReflection->getName()), + 'missingType.return', + null, ]; + } else { + foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { + $errors[] = [ + sprintf('Function %s() return type has no value type specified in %s.', $functionReflection->getName(), $iterableTypeDescription), + 'missingType.iterableValue', + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ]; + } } - $messages = []; - foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { - $messages[] = RuleErrorBuilder::message(sprintf('Function %s() return type has no value type specified in %s.', $functionReflection->getName(), $iterableTypeDescription)) - ->tip(MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP) - ->identifier('missingType.iterableValue') - ->build(); + $messages = $this->createReturnTypeErrors($node, $errors); + if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + return $messages; } foreach ($this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($returnType) as [$name, $genericTypeNames]) { @@ -77,4 +85,40 @@ public function processNode(Node $node, Scope $scope): array return $messages; } + /** + * With the fixMissingReturnTypes feature toggle, the errors are fixed with the returned type. + * + * @param list $errors + * @return list + */ + private function createReturnTypeErrors(FunctionReturnStatementsNode $node, array $errors): array + { + if ($errors === []) { + return []; + } + + $function = $node->getFunction(); + $fix = null; + if ($this->fixer->isEnabled()) { + $type = $this->fixer->combine([$this->fixer->getReturnInfo($node)]); + if ($type !== null) { + $fix = $this->fixer->createFix($function, $type, $type, null); + } + } + + $ruleErrors = []; + foreach ($errors as [$message, $identifier, $tip]) { + $builder = RuleErrorBuilder::message($message)->identifier($identifier); + if ($tip !== null) { + $builder->tip($tip); + } + if ($fix !== null) { + $builder->fixNode($function, $fix); + } + $ruleErrors[] = $builder->build(); + } + + return $ruleErrors; + } + } diff --git a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php index 547f45a8986..f006b921b06 100644 --- a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php @@ -3,20 +3,31 @@ namespace PHPStan\Rules\Methods; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; use PHPStan\Node\MethodReturnStatementsNode; +use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Rules\MissingReturnTypeCollector; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Type\MixedType; +use function array_map; use function sprintf; +use function strtolower; /** * Reports the missing return type and the missing iterable value type of methods with a body, * where the returned types are known. MissingMethodReturnTypehintRule reports them for methods without a body. * + * With the fixMissingReturnTypes feature toggle, the errors are fixed with the returned type. The return type + * of a method that can be overridden in a closed project depends on the overriding methods, + * MissingReturnTypeFixRule reports and fixes it. + * * @implements Rule */ #[RegisteredRule(level: 6)] @@ -24,7 +35,11 @@ final class MissingImplementedMethodReturnTypehintRule implements Rule { - public function __construct(private MissingTypehintCheck $missingTypehintCheck) + public function __construct( + private MissingTypehintCheck $missingTypehintCheck, + private MissingReturnTypeFixer $fixer, + private OverridableMemberHelper $overridableMemberHelper, + ) { } @@ -33,7 +48,7 @@ public function getNodeType(): string return MethodReturnStatementsNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { if ( $scope->isInTrait() @@ -45,30 +60,132 @@ public function processNode(Node $node, Scope $scope): array $methodReflection = $node->getMethodReflection(); $returnType = $methodReflection->getReturnType(); + $errors = []; if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { - return [ - RuleErrorBuilder::message(sprintf( + $errors[] = [ + sprintf( 'Method %s::%s() has no return type specified.', $methodReflection->getDeclaringClass()->getDisplayName(), $methodReflection->getName(), - ))->identifier('missingType.return')->build(), + ), + 'missingType.return', + null, ]; + } else { + foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { + $errors[] = [ + sprintf( + 'Method %s::%s() return type has no value type specified in %s.', + $methodReflection->getDeclaringClass()->getDisplayName(), + $methodReflection->getName(), + $iterableTypeDescription, + ), + 'missingType.iterableValue', + MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP, + ]; + } + } + + if (!$this->fixer->isEnabled()) { + return array_map(static fn (array $error) => self::buildError($error)->build(), $errors); + } + + return $this->processFixableErrors($node, $scope, $errors); + } + + /** + * @param list $errors + * @return list + */ + private function processFixableErrors(MethodReturnStatementsNode $node, Scope&CollectedDataEmitter $scope, array $errors): array + { + $classReflection = $node->getClassReflection(); + $methodReflection = $node->getMethodReflection(); + $classMethod = $node->getClassMethod(); + $isClosedProject = $this->overridableMemberHelper->isClosedProject(); + $isOverridable = !$methodReflection->isPrivate() + && !$classReflection->isFinal() + && !$methodReflection->isFinal()->yes() + && strtolower($methodReflection->getName()) !== '__construct'; + $isInTrait = $scope->isInTrait(); + + $overrides = []; + if ($isClosedProject) { + foreach ($this->overridableMemberHelper->findOverriddenMethods($classReflection, $methodReflection->getName()) as $overriddenMethod) { + $overrides[] = MissingReturnTypeFixer::getKey($overriddenMethod->getDeclaringClass()->getName(), $overriddenMethod->getName()); + } } - $messages = []; - foreach ($this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($returnType) as $iterableTypeDescription) { - $messages[] = RuleErrorBuilder::message(sprintf( - 'Method %s::%s() return type has no value type specified in %s.', - $methodReflection->getDeclaringClass()->getDisplayName(), - $methodReflection->getName(), - $iterableTypeDescription, - )) - ->tip(MissingTypehintCheck::MISSING_ITERABLE_VALUE_TYPE_TIP) - ->identifier('missingType.iterableValue') - ->build(); + $returnInfo = $this->fixer->getReturnInfo($node); + // the methods overriding a method in an open project are not known, it is not fixed, + // and a method of a trait is fixed with what it returns in all the classes using the trait + $isDeferred = $errors !== [] && ($isInTrait || ($isOverridable && $isClosedProject)); + + $ruleErrors = []; + $fixedNatively = false; + if (!$isDeferred) { + $fix = null; + if (!$isInTrait && !$isOverridable) { + $type = $this->fixer->combine([$returnInfo]); + if ($type !== null) { + $fix = $this->fixer->createFix($classMethod, $type, $type, $classReflection); + } + } + + $fixedNatively = $fix !== null && $classMethod->returnType === null; + foreach ($errors as $error) { + $builder = self::buildError($error); + if ($fix !== null) { + $builder->fixNode($classMethod, $fix); + } + $ruleErrors[] = $builder->build(); + } + } + + if ($isDeferred || $overrides !== []) { + $traitMethod = null; + $className = $classReflection->getName(); + $file = $scope->getFile(); + if ($isInTrait) { + // the types are resolved in the trait, $this of each class using it is static there + $traitReflection = $scope->getTraitReflection(); + $className = $traitReflection->getName(); + $traitMethod = MissingReturnTypeFixer::getKey($className, $classMethod->getAttribute('originalTraitMethodName') ?? $classMethod->name->toString()); + $file = $traitReflection->getFileName() ?? $file; + } + + $scope->emitCollectedData(MissingReturnTypeCollector::class, [ + 'key' => MissingReturnTypeFixer::getKey($classReflection->getName(), $methodReflection->getName()), + 'traitMethod' => $traitMethod, + 'class' => $className, + 'overrides' => $overrides, + 'overridable' => $isOverridable, + 'returnInfo' => $this->fixer->serializeReturnInfo($returnInfo), + 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, + 'fixedNatively' => $fixedNatively, + 'errors' => $isDeferred ? $errors : [], + 'file' => $file, + 'fileDescription' => $scope->getFileDescription(), + 'line' => $node->getStartLine(), + 'startPos' => $classMethod->getStartFilePos(), + ]); + } + + return $ruleErrors; + } + + /** + * @param array{string, string, string|null} $error + * @return RuleErrorBuilder + */ + private static function buildError(array $error): RuleErrorBuilder + { + $builder = RuleErrorBuilder::message($error[0])->identifier($error[1]); + if ($error[2] !== null) { + $builder->tip($error[2]); } - return $messages; + return $builder; } } diff --git a/src/Rules/Methods/MissingMethodReturnTypehintRule.php b/src/Rules/Methods/MissingMethodReturnTypehintRule.php index a0974a7c158..7613fdb0834 100644 --- a/src/Rules/Methods/MissingMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingMethodReturnTypehintRule.php @@ -3,13 +3,17 @@ namespace PHPStan\Rules\Methods; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; use PHPStan\Node\InClassMethodNode; +use PHPStan\Rules\MissingReturnTypeCollector; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Type\MixedType; use PHPStan\Type\VerbosityLevel; use function sprintf; @@ -22,7 +26,11 @@ final class MissingMethodReturnTypehintRule implements Rule { - public function __construct(private MissingTypehintCheck $missingTypehintCheck) + public function __construct( + private MissingTypehintCheck $missingTypehintCheck, + private MissingReturnTypeFixer $fixer, + private OverridableMemberHelper $overridableMemberHelper, + ) { } @@ -31,7 +39,7 @@ public function getNodeType(): string return InClassMethodNode::class; } - public function processNode(Node $node, Scope $scope): array + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array { $methodReflection = $node->getMethodReflection(); if ($scope->isInTrait()) { @@ -45,6 +53,9 @@ public function processNode(Node $node, Scope $scope): array // MissingImplementedMethodReturnTypehintRule reports these for methods with a body $hasBody = $node->getOriginalNode()->stmts !== null; + if (!$hasBody) { + $this->emitOverridingMethodWithoutBody($node, $scope); + } if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { if ($hasBody) { return []; @@ -98,4 +109,43 @@ public function processNode(Node $node, Scope $scope): array return $messages; } + /** + * An abstract method overriding a method with a body has to declare a native return type + * before MissingReturnTypeFixRule can declare one in the overridden method. + */ + private function emitOverridingMethodWithoutBody(InClassMethodNode $node, Scope&CollectedDataEmitter $scope): void + { + if (!$this->fixer->isEnabled() || !$this->overridableMemberHelper->isClosedProject()) { + return; + } + + $classReflection = $node->getClassReflection(); + $methodReflection = $node->getMethodReflection(); + $overrides = []; + foreach ($this->overridableMemberHelper->findOverriddenMethods($classReflection, $methodReflection->getName()) as $overriddenMethod) { + $overrides[] = MissingReturnTypeFixer::getKey($overriddenMethod->getDeclaringClass()->getName(), $overriddenMethod->getName()); + } + + if ($overrides === []) { + return; + } + + $classMethod = $node->getOriginalNode(); + $scope->emitCollectedData(MissingReturnTypeCollector::class, [ + 'key' => MissingReturnTypeFixer::getKey($classReflection->getName(), $methodReflection->getName()), + 'traitMethod' => null, + 'class' => $classReflection->getName(), + 'overrides' => $overrides, + 'overridable' => true, + 'returnInfo' => null, + 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, + 'fixedNatively' => false, + 'errors' => [], + 'file' => $scope->getFile(), + 'fileDescription' => $scope->getFileDescription(), + 'line' => $node->getStartLine(), + 'startPos' => $classMethod->getStartFilePos(), + ]); + } + } diff --git a/src/Rules/MissingReturnTypeCollector.php b/src/Rules/MissingReturnTypeCollector.php new file mode 100644 index 00000000000..02a77436afa --- /dev/null +++ b/src/Rules/MissingReturnTypeCollector.php @@ -0,0 +1,44 @@ +, overridable: bool, returnInfo: array{values: string, void: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> + */ +final class MissingReturnTypeCollector implements Collector +{ + + public function getNodeType(): string + { + throw new ShouldNotHappenException(); + } + + public function processNode(Node $node, Scope $scope) + { + throw new ShouldNotHappenException(); + } + +} diff --git a/src/Rules/MissingReturnTypeFixRule.php b/src/Rules/MissingReturnTypeFixRule.php new file mode 100644 index 00000000000..a625c4204b9 --- /dev/null +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -0,0 +1,317 @@ +, overridable: bool, returnInfo: array{values: string, void: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} + * @implements Rule + */ +#[RegisteredRule(level: 6)] +final class MissingReturnTypeFixRule implements Rule +{ + + /** @var array */ + private array $records = []; + + /** @var array> keys of the methods overriding the method, by its key */ + private array $overriddenBy = []; + + /** @var array> keys of the records of a method of a trait in the classes using it, by the key of the trait method */ + private array $traitMethodRecords = []; + + /** @var array */ + private array $returnInfos = []; + + /** @var array */ + private array $fixes = []; + + private bool $isOnlyFilesAnalysis = false; + + public function __construct( + private MissingReturnTypeFixer $fixer, + private OverridableMemberHelper $overridableMemberHelper, + private TypeStringResolver $typeStringResolver, + private ReflectionProvider $reflectionProvider, + #[AutowiredParameter(ref: '@defaultAnalysisParser')] + private Parser $parser, + ) + { + } + + public function getNodeType(): string + { + return CollectedDataNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $collectedRecords = $node->get(MissingReturnTypeCollector::class); + if ($collectedRecords === []) { + return []; + } + + $this->records = []; + $this->overriddenBy = []; + $this->traitMethodRecords = []; + $this->returnInfos = []; + $this->fixes = []; + foreach ($collectedRecords as $fileRecords) { + foreach ($fileRecords as $record) { + $this->records[$record['key']] = $record; + foreach ($record['overrides'] as $overriddenKey) { + $this->overriddenBy[$overriddenKey][] = $record['key']; + } + if ($record['traitMethod'] === null) { + continue; + } + + $this->traitMethodRecords[$record['traitMethod']][] = $record['key']; + } + } + + $this->isOnlyFilesAnalysis = $node->isOnlyFilesAnalysis(); + + $errors = []; + foreach ($this->records as $key => $record) { + if ($record['errors'] === []) { + continue; + } + + $fix = $this->getFix($key); + foreach ($record['errors'] as [$message, $identifier, $tip]) { + $builder = RuleErrorBuilder::message($message) + ->identifier($identifier) + ->file($record['file'], $record['fileDescription']) + ->line($record['line']); + if ($tip !== null) { + $builder->tip($tip); + } + if ($fix !== null) { + $functionNode = $this->findFunctionNode($record); + if ($functionNode !== null) { + $builder->fixNode($functionNode, $fix, $record['file']); + } + } + + $errors[] = $builder->build(); + } + } + + return $errors; + } + + /** + * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null + */ + private function getFix(string $key): ?callable + { + // the classes using a trait share the fix of its method + $fixKey = $this->records[$key]['traitMethod'] ?? $key; + if (!array_key_exists($fixKey, $this->fixes)) { + // a method whose fix depends on itself is not fixed + $this->fixes[$fixKey] = false; + $this->fixes[$fixKey] = $this->createFix($key) ?? false; + } + + $fix = $this->fixes[$fixKey]; + + return $fix === false ? null : $fix; + } + + /** + * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null + */ + private function createFix(string $key): ?callable + { + $record = $this->records[$key]; + $traitMethod = $record['traitMethod']; + // the classes using a trait might not be analysed + if ($traitMethod !== null && $this->isOnlyFilesAnalysis) { + return null; + } + + $returnInfos = []; + $nativeReturnInfos = []; + foreach ($traitMethod !== null ? $this->traitMethodRecords[$traitMethod] : [$key] as $contextKey) { + $contextRecord = $this->records[$contextKey]; + if ($contextRecord['errors'] === []) { + return null; + } + + $returnInfo = $this->getReturnInfo($contextKey); + if ($returnInfo === null) { + return null; + } + + $returnInfos[] = $returnInfo; + $nativeReturnInfos[] = $returnInfo; + if (!$contextRecord['overridable']) { + continue; + } + + // the methods overriding it are not known in an open project, and might not be analysed + if (!$this->overridableMemberHelper->isClosedProject() || $this->isOnlyFilesAnalysis) { + return null; + } + + foreach ($this->overriddenBy[$contextKey] ?? [] as $overridingKey) { + $overridingRecord = $this->records[$overridingKey]; + if ($overridingRecord['traitMethod'] !== null) { + // the same method of the trait gets the same fix + if ($overridingRecord['traitMethod'] === $traitMethod) { + continue; + } + + // the types of the method of another trait are resolved in that trait + return null; + } + + $overridingReturnInfo = $this->getReturnInfo($overridingKey); + $overridingNativeType = $this->resolve($overridingRecord['nativeReturnType'], $overridingRecord['class']); + $overridingNativeReturnInfo = $overridingNativeType !== null ? $this->createNativeReturnInfo($overridingNativeType) : null; + $overridingReturnInfo ??= $overridingNativeReturnInfo; + if ($overridingReturnInfo === null) { + return null; + } + + $returnInfos[] = $overridingReturnInfo; + if ($overridingNativeReturnInfo !== null) { + $nativeReturnInfos[] = $overridingNativeReturnInfo; + continue; + } + + // PHP requires a native return type of the overriding method when the overridden method declares one + if ($contextRecord['nativeReturnType'] === null && !$this->willDeclareNativeReturnType($overridingKey)) { + return null; + } + + $nativeReturnInfos[] = $overridingReturnInfo; + } + } + + if ($nativeReturnInfos === []) { + return null; + } + + $phpDocType = $this->fixer->combine($returnInfos); + $nativeSourceType = $this->fixer->combine($nativeReturnInfos); + if ($phpDocType === null || $nativeSourceType === null) { + return null; + } + + $functionNode = $this->findFunctionNode($record); + if ($functionNode === null) { + return null; + } + + $classReflection = $record['class'] !== null && $this->reflectionProvider->hasClass($record['class']) + ? $this->reflectionProvider->getClass($record['class']) + : null; + + return $this->fixer->createFix($functionNode, $phpDocType, $nativeSourceType, $classReflection); + } + + private function willDeclareNativeReturnType(string $key): bool + { + $record = $this->records[$key]; + if ($record['fixedNatively']) { + return true; + } + + return $record['nativeReturnType'] === null && $this->getFix($key) !== null; + } + + /** + * @return ReturnInfo|null + */ + private function getReturnInfo(string $key): ?array + { + if (array_key_exists($key, $this->returnInfos)) { + return $this->returnInfos[$key]; + } + + $record = $this->records[$key]; + $returnInfo = null; + if ($record['returnInfo'] !== null) { + $values = $this->resolve($record['returnInfo']['values'], $record['class']); + if ($values !== null) { + $returnInfo = [ + 'values' => $values, + 'void' => $record['returnInfo']['void'], + ]; + } + } + + return $this->returnInfos[$key] = $returnInfo; + } + + /** + * @return ReturnInfo + */ + private function createNativeReturnInfo(Type $nativeType): array + { + // an overriding method declaring void forbids returning a value + if ($nativeType->isVoid()->yes()) { + return ['values' => new NeverType(true), 'void' => true]; + } + + return ['values' => $nativeType, 'void' => false]; + } + + private function resolve(?string $type, ?string $className): ?Type + { + if ($type === null) { + return null; + } + + return $this->typeStringResolver->resolve($type, new NameScope(null, [], $className)); + } + + /** + * @param Record $record + */ + private function findFunctionNode(array $record): ClassMethod|Function_|null + { + try { + $stmts = $this->parser->parseFile($record['file']); + } catch (ParserErrorsException) { + return null; + } + + $startPos = $record['startPos']; + $functionNode = (new NodeFinder())->findFirst($stmts, static fn (Node $node): bool => ($node instanceof ClassMethod || $node instanceof Function_) && $node->getStartFilePos() === $startPos); + if (!$functionNode instanceof ClassMethod && !$functionNode instanceof Function_) { + return null; + } + + return $functionNode; + } + +} diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php new file mode 100644 index 00000000000..607febd9d70 --- /dev/null +++ b/src/Rules/MissingReturnTypeFixer.php @@ -0,0 +1,452 @@ +hasTemplateOrLateResolvableType()) { + return null; + } + + return $this->printer->print($type->toPhpDocNode()); + } + + /** + * @param ReturnInfo $returnInfo + * @return array{values: string, void: bool}|null + */ + public function serializeReturnInfo(array $returnInfo): ?array + { + $values = $this->serialize($returnInfo['values']); + if ($values === null) { + return null; + } + + return ['values' => $values, 'void' => $returnInfo['void']]; + } + + public function isEnabled(): bool + { + return $this->enabled; + } + + /** + * @return ReturnInfo + */ + public function getReturnInfo(MethodReturnStatementsNode|FunctionReturnStatementsNode $node): array + { + $values = []; + $void = false; + foreach ($node->getReturnStatements() as $returnStatement) { + $expr = $returnStatement->getReturnNode()->expr; + if ($expr === null) { + $void = true; + continue; + } + + $values[] = $returnStatement->getScope()->getType($expr); + } + + $returnInfo = [ + 'values' => count($values) === 0 ? new NeverType(true) : TypeCombinator::union(...$values), + 'void' => $void || !$node->getStatementResult()->isAlwaysTerminating(), + ]; + if (!$node->isGenerator()) { + return $returnInfo; + } + + $keyTypes = []; + $valueTypes = []; + $sendTypes = []; + foreach ($node->getYieldStatementsWithScope() as $yieldStatement) { + $yieldNode = $yieldStatement->getYieldNode(); + $yieldScope = $yieldStatement->getScope(); + if ($yieldNode instanceof Yield_) { + $keyTypes[] = $yieldNode->key === null ? new IntegerType() : $yieldScope->getType($yieldNode->key); + $valueTypes[] = $yieldNode->value === null ? new NullType() : $yieldScope->getType($yieldNode->value); + continue; + } + + $iterableType = $yieldScope->getType($yieldNode->expr); + $keyTypes[] = $iterableType->getIterableKeyType(); + $valueTypes[] = $iterableType->getIterableValueType(); + + // the values sent to the generator are sent on to the generators it delegates to + $generatorType = new ObjectType(Generator::class); + if ($generatorType->isSuperTypeOf($iterableType)->no()) { + continue; + } + + $sendType = TypeCombinator::intersect($iterableType, $generatorType)->getTemplateType(Generator::class, 'TSend'); + if ($sendType->isSuperTypeOf(new MixedType())->yes()) { + continue; + } + + $sendTypes[] = $sendType; + } + + return $this->createGeneratorReturnInfo( + TypeCombinator::union(...$keyTypes), + TypeCombinator::union(...$valueTypes), + count($sendTypes) === 0 ? new MixedType(true) : TypeCombinator::intersect(...$sendTypes), + $returnInfo, + ); + } + + /** + * @param ReturnInfo $returnInfo what the generator returns + * @return ReturnInfo + */ + private function createGeneratorReturnInfo(Type $keyType, Type $valueType, Type $sendType, array $returnInfo): array + { + // a generator returning nothing returns null to Generator::getReturn() + $generatorReturnType = $this->combine([$returnInfo]) ?? TypeCombinator::addNull($returnInfo['values']); + + return [ + 'values' => new GenericObjectType(Generator::class, [ + $keyType, + $valueType, + $sendType, + $generatorReturnType, + ]), + 'void' => false, + ]; + } + + /** + * The type the functions with these return infos return together, null when no return type + * can be declared for them: some return nothing, others a value. With a declared return type, + * PHPStan reports falling off the end of the function, and PHP a bare return statement. + * + * @param non-empty-list $returnInfos + */ + public function combine(array $returnInfos): ?Type + { + $values = []; + $void = false; + foreach ($returnInfos as $returnInfo) { + $values[] = $returnInfo['values']; + $void = $void || $returnInfo['void']; + } + + $type = TypeCombinator::union(...$values); + if (!$void) { + return $type; + } + + if ($type instanceof NeverType) { + return new VoidType(); + } + + return null; + } + + /** + * The fix that declares the return type of the function. The native type is declared when the function + * does not have one, it is $nativeSourceType widened to what PHP allows, or to the closest common + * parent class of the returned objects. Null when $phpDocType cannot be written, or a native type cannot be declared. + * + * The @return tag is added or changed only when the native type does not say enough: with $phpDocType + * when the native type has an iterable, a generic class or a callable, whose value types, type arguments + * or signature only PHPDoc describes, and with the native type of the newest PHP version when the PHP version + * does not allow it, like static or a union type. + * + * @template TNode of ClassMethod|Function_ + * @param TNode $node + * @return (callable(TNode): TNode)|null + */ + public function createFix( + ClassMethod|Function_ $node, + Type $phpDocType, + Type $nativeSourceType, + ?ClassReflection $classReflection, + ): ?callable + { + if (!$this->canWrite($phpDocType)) { + return null; + } + + $nativeTypeNode = null; + if ($node->returnType === null) { + $nativeTypeNode = $this->createNativeTypeNode($nativeSourceType); + if ($nativeTypeNode === null) { + return null; + } + $nativeType = ParserNodeTypeToPHPStanType::resolve($nativeTypeNode, $classReflection); + } else { + $nativeType = ParserNodeTypeToPHPStanType::resolve($node->returnType, $classReflection); + } + + if ($nativeType->isSuperTypeOf($phpDocType)->no()) { + return null; + } + + $phpDocTypeNode = null; + $returnedPhpDocType = $this->getPhpDocType($phpDocType, $classReflection); + if (!$nativeType->equals($returnedPhpDocType)) { + $phpDocTypeNode = $returnedPhpDocType->toPhpDocNode(); + } + + $phpDocEditor = $this->phpDocEditor; + + return static function (ClassMethod|Function_ $node) use ($nativeTypeNode, $phpDocTypeNode, $phpDocEditor): ClassMethod|Function_ { + if ($nativeTypeNode !== null) { + $node->returnType = $nativeTypeNode; + } + + if ($phpDocTypeNode === null) { + return $node; + } + + $phpDocEditor->edit($node, static function (PhpDocAstNode $phpDocNode) use ($phpDocTypeNode): PhpDocAstNode { + if ($phpDocNode instanceof ReturnTagValueNode) { + $phpDocNode->type = $phpDocTypeNode; + return $phpDocNode; + } + + if (!$phpDocNode instanceof PhpDocNode || count($phpDocNode->getReturnTagValues()) > 0) { + return $phpDocNode; + } + + // the ignore tags at the end of the PHPDoc stay last + $position = count($phpDocNode->children); + while ($position > 0 && $phpDocNode->children[$position - 1] instanceof PhpDocTagNode && str_starts_with($phpDocNode->children[$position - 1]->name, '@phpstan-ignore')) { + $position--; + } + array_splice($phpDocNode->children, $position, 0, [new PhpDocTagNode('@return', new ReturnTagValueNode($phpDocTypeNode, ''))]); + + return $phpDocNode; + }); + + return $node; + }; + } + + /** + * Whether the type can be written as the return type without causing other errors: + * it has to be known and every iterable, generic class and callable in it has to be described. + * + * A type with mixed in it, even explicit, is not written, except as the key type of array. + * The analysis of the callers would stop at it, while the next round of fixes may infer a more + * precise type once the callees are typed. Only the TSend of a Generator is mixed when nothing + * restricts what can be sent to it. + */ + private function canWrite(Type $type): bool + { + $canWrite = true; + TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$canWrite): Type { + if ($type instanceof TemplateType) { + return $type; + } + + if ($type instanceof ErrorType || $type instanceof MixedType) { + $canWrite = false; + return $type; + } + + // array has a mixed key type, PHPDoc cannot say more about the keys than array-key + if (($type instanceof ArrayType || $type instanceof IterableType) && $type->getKeyType() instanceof MixedType) { + $traverse($type->getItemType()); + return $type; + } + + if ($type instanceof GenericObjectType && $type->getClassName() === Generator::class) { + $typeArguments = $type->getTypes(); + if (($typeArguments[2] ?? null) instanceof MixedType) { + $typeArguments[2] = new NeverType(true); + } + $traverse(new GenericObjectType(Generator::class, $typeArguments)); + + return $type; + } + + return $traverse($type); + }); + + return $canWrite + && $this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($type) === [] + && $this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($type) === [] + && $this->missingTypehintCheck->getCallablesWithMissingSignature($type) === []; + } + + /** + * The type the @return tag describes: the native type of the newest PHP version, + * or the returned type when that native type does not describe everything a return type has to. + */ + private function getPhpDocType(Type $type, ?ClassReflection $classReflection): Type + { + $typeNode = $this->createNativeTypeNode($type, new PhpVersion(PhpVersionFactory::MAX_PHP_VERSION)); + if ($typeNode === null) { + return $type; + } + + $nativeType = ParserNodeTypeToPHPStanType::resolve($typeNode, $classReflection); + $describesEverything = true; + TypeTraverser::map($nativeType, static function (Type $type, callable $traverse) use (&$describesEverything): Type { + if ($type instanceof UnionType || $type instanceof IntersectionType) { + return $traverse($type); + } + + if ($type->isIterable()->yes() || $type->isCallable()->yes()) { + $describesEverything = false; + } + + foreach ($type->getObjectClassReflections() as $typeClassReflection) { + if (!$typeClassReflection->isGeneric()) { + continue; + } + + $describesEverything = false; + } + + return $type; + }); + + return $describesEverything ? $nativeType : $type; + } + + /** + * @return Identifier|Name|ComplexType|null + */ + private function createNativeTypeNode(Type $type, ?PhpVersion $phpVersion = null) + { + $position = NativeTypePosition::returnType($phpVersion ?? $this->phpVersion); + $typeNode = $type->toNativePhpTypeNode($position); + if ($typeNode !== null) { + return $typeNode; + } + + // never before PHP 8.1 + if ($type instanceof NeverType) { + return (new VoidType())->toNativePhpTypeNode($position); + } + + $commonParentType = $this->findCommonParentType(TypeCombinator::removeNull($type)); + if ($commonParentType === null) { + return null; + } + + if (!$type->isNull()->no()) { + $commonParentType = TypeCombinator::addNull($commonParentType); + } + + return $commonParentType->toNativePhpTypeNode($position); + } + + /** + * The closest class or interface all the objects of the type are instances of, without union types before PHP 8.0. + */ + private function findCommonParentType(Type $type): ?Type + { + if (!$type->isObject()->yes()) { + return null; + } + + $classNames = $type->getObjectClassNames(); + if (count($classNames) < 2) { + return null; + } + + $firstClass = $this->reflectionProvider->getClass($classNames[0]); + $candidates = [$firstClass, ...$firstClass->getParents(), ...array_values($firstClass->getInterfaces())]; + foreach ($candidates as $candidate) { + $candidateType = new ObjectType($candidate->getName()); + if (!$candidateType->isSuperTypeOf($type)->yes()) { + continue; + } + + return $candidateType; + } + + return null; + } + +} diff --git a/tests/PHPStan/Generics/data/functions-6.json b/tests/PHPStan/Generics/data/functions-6.json index 72e5278a642..812dd32ef83 100644 --- a/tests/PHPStan/Generics/data/functions-6.json +++ b/tests/PHPStan/Generics/data/functions-6.json @@ -2,7 +2,8 @@ { "message": "Function PHPStan\\Generics\\Functions\\testF() has no return type specified.", "line": 27, - "ignorable": true + "ignorable": true, + "fixable": true }, { "message": "Unable to resolve the template type B in call to function PHPStan\\Generics\\Functions\\f", diff --git a/tests/PHPStan/Generics/data/pick-6.json b/tests/PHPStan/Generics/data/pick-6.json index 1598be53206..8f9348859c3 100644 --- a/tests/PHPStan/Generics/data/pick-6.json +++ b/tests/PHPStan/Generics/data/pick-6.json @@ -2,6 +2,7 @@ { "message": "Function PHPStan\\Generics\\Pick\\test() has no return type specified.", "line": 22, - "ignorable": true + "ignorable": true, + "fixable": true } ] \ No newline at end of file diff --git a/tests/PHPStan/Generics/data/varyingAcceptor-6.json b/tests/PHPStan/Generics/data/varyingAcceptor-6.json index 72f7b7dc7ae..342ebd8e575 100644 --- a/tests/PHPStan/Generics/data/varyingAcceptor-6.json +++ b/tests/PHPStan/Generics/data/varyingAcceptor-6.json @@ -2,6 +2,7 @@ { "message": "Function PHPStan\\Generics\\VaryingAcceptor\\testApply() has no return type specified.", "line": 30, - "ignorable": true + "ignorable": true, + "fixable": true } ] \ No newline at end of file diff --git a/tests/PHPStan/Levels/data/acceptTypes-6.json b/tests/PHPStan/Levels/data/acceptTypes-6.json index 27cbc796d03..fa448abae49 100644 --- a/tests/PHPStan/Levels/data/acceptTypes-6.json +++ b/tests/PHPStan/Levels/data/acceptTypes-6.json @@ -132,12 +132,14 @@ { "message": "Method Levels\\AcceptTypes\\Baz::requireArray() has no return type specified.", "line": 550, - "ignorable": true + "ignorable": true, + "fixable": true }, { "message": "Method Levels\\AcceptTypes\\Baz::requireFoo() has no return type specified.", "line": 555, - "ignorable": true + "ignorable": true, + "fixable": true }, { "message": "Method Levels\\AcceptTypes\\ArrayShapes::doFoo() has no return type specified.", diff --git a/tests/PHPStan/Levels/data/callableVariance-6.json b/tests/PHPStan/Levels/data/callableVariance-6.json index 28eec65b646..14dee01987f 100644 --- a/tests/PHPStan/Levels/data/callableVariance-6.json +++ b/tests/PHPStan/Levels/data/callableVariance-6.json @@ -2,11 +2,13 @@ { "message": "Function Levels\\CallableVariance\\d() has no return type specified.", "line": 68, - "ignorable": true + "ignorable": true, + "fixable": true }, { "message": "Function Levels\\CallableVariance\\testD() has no return type specified.", "line": 79, - "ignorable": true + "ignorable": true, + "fixable": true } ] \ No newline at end of file diff --git a/tests/PHPStan/Rules/Functions/MissingFunctionReturnTypehintRuleTest.php b/tests/PHPStan/Rules/Functions/MissingFunctionReturnTypehintRuleTest.php index d649656b88f..6ce046a63a0 100644 --- a/tests/PHPStan/Rules/Functions/MissingFunctionReturnTypehintRuleTest.php +++ b/tests/PHPStan/Rules/Functions/MissingFunctionReturnTypehintRuleTest.php @@ -2,6 +2,7 @@ namespace PHPStan\Rules\Functions; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; @@ -14,7 +15,10 @@ class MissingFunctionReturnTypehintRuleTest extends RuleTestCase protected function getRule(): Rule { - return new MissingFunctionReturnTypehintRule(new MissingTypehintCheck(true, [], true)); + $missingTypehintCheck = new MissingTypehintCheck(true, [], true); + $fixer = self::getContainer()->getByType(MissingReturnTypeFixer::class); + + return new MissingFunctionReturnTypehintRule($missingTypehintCheck, $fixer); } public function testRule(): void diff --git a/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php b/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php index 73a978b5a12..50d97933b3b 100644 --- a/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php @@ -2,8 +2,10 @@ namespace PHPStan\Rules\Methods; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; @@ -15,7 +17,11 @@ class MissingImplementedMethodReturnTypehintRuleTest extends RuleTestCase protected function getRule(): Rule { - return new MissingImplementedMethodReturnTypehintRule(new MissingTypehintCheck(true, [], true)); + return new MissingImplementedMethodReturnTypehintRule( + new MissingTypehintCheck(true, [], true), + self::getContainer()->getByType(MissingReturnTypeFixer::class), + new OverridableMemberHelper('open'), + ); } public function testRule(): void diff --git a/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php b/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php index 84a8a82a3b5..7b1fd6c07e7 100644 --- a/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MissingMethodReturnTypehintRuleTest.php @@ -2,8 +2,10 @@ namespace PHPStan\Rules\Methods; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; +use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; @@ -15,7 +17,11 @@ class MissingMethodReturnTypehintRuleTest extends RuleTestCase protected function getRule(): Rule { - return new MissingMethodReturnTypehintRule(new MissingTypehintCheck(true, [], true)); + return new MissingMethodReturnTypehintRule( + new MissingTypehintCheck(true, [], true), + self::getContainer()->getByType(MissingReturnTypeFixer::class), + new OverridableMemberHelper('open'), + ); } public function testRule(): void diff --git a/tests/PHPStan/Rules/MissingReturnTypeFixPhp74Test.php b/tests/PHPStan/Rules/MissingReturnTypeFixPhp74Test.php new file mode 100644 index 00000000000..6dbe533cc86 --- /dev/null +++ b/tests/PHPStan/Rules/MissingReturnTypeFixPhp74Test.php @@ -0,0 +1,13 @@ + + */ +abstract class MissingReturnTypeFixTestCase extends RuleTestCase +{ + + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + + private bool $reportMissingParameterTypes = false; + + abstract protected static function getPhpVersionSuffix(): string; + + protected function getRule(): Rule + { + $missingTypehintCheck = self::getContainer()->getByType(MissingTypehintCheck::class); + $fixer = self::getContainer()->getByType(MissingReturnTypeFixer::class); + $overridableMemberHelper = new OverridableMemberHelper($this->projectType); + + $rules = [ + new MissingFunctionReturnTypehintRule($missingTypehintCheck, $fixer), + new MissingMethodReturnTypehintRule($missingTypehintCheck, $fixer, $overridableMemberHelper), + new MissingImplementedMethodReturnTypehintRule($missingTypehintCheck, $fixer, $overridableMemberHelper), + new MissingReturnTypeFixRule( + $fixer, + $overridableMemberHelper, + self::getContainer()->getByType(TypeStringResolver::class), + self::createReflectionProvider(), + self::getContainer()->getService('defaultAnalysisParser'), + ), + ]; + if ($this->reportMissingParameterTypes) { + // errors on the function line for the ignore tags in the PHPDoc to match + $rules[] = new MissingFunctionParameterTypehintRule($missingTypehintCheck); + } + + // @phpstan-ignore argument.type + return new CompositeRule($rules); + } + + public function testFunctions(): void + { + $this->fix(__DIR__ . '/data/fix-missing-return-type/functions.php', $this->getFixedFile('functions')); + } + + public function testFunctionsWithIgnores(): void + { + $this->reportMissingParameterTypes = true; + $this->fix(__DIR__ . '/data/fix-missing-return-type/functions-with-ignores.php', $this->getFixedFile('functions-with-ignores')); + } + + public function testMethodsInOpenProject(): void + { + $this->fix(__DIR__ . '/data/fix-missing-return-type/methods.php', $this->getFixedFile('methods-open-project')); + } + + public function testMethodsInClosedProject(): void + { + $this->projectType = 'closed'; + $this->fix(__DIR__ . '/data/fix-missing-return-type/methods.php', $this->getFixedFile('methods-closed-project')); + } + + public function testTraitsInOpenProject(): void + { + $this->fix(__DIR__ . '/data/fix-missing-return-type/traits.php', $this->getFixedFile('traits-open-project')); + } + + public function testTraitsInClosedProject(): void + { + $this->projectType = 'closed'; + $this->fix(__DIR__ . '/data/fix-missing-return-type/traits.php', $this->getFixedFile('traits-closed-project')); + } + + public function testTraitErrorsInEachClassUsingTheTrait(): void + { + $this->projectType = 'closed'; + $file = __DIR__ . '/data/fix-missing-return-type/traits.php'; + $errors = []; + foreach ($this->gatherAnalyserErrors([$file]) as $error) { + $errors[] = sprintf('%s:%s: %s', str_replace($this->getFileHelper()->normalizePath($file), 'traits.php', $error->getFile()), $error->getLine() ?? '', $error->getMessage()); + } + sort($errors); + + $this->assertSame([ + 'traits.php (in context of class FixMissingReturnTypeTrait\FluentOne):90: Method FixMissingReturnTypeTrait\FluentOne::fluent() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\FluentOne):95: Method FixMissingReturnTypeTrait\FluentOne::newSelf() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\FluentTwo):90: Method FixMissingReturnTypeTrait\FluentTwo::fluent() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\FluentTwo):95: Method FixMissingReturnTypeTrait\FluentTwo::newSelf() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\HasCat):62: Method FixMissingReturnTypeTrait\HasCat::createAnimal() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\HasDog):62: Method FixMissingReturnTypeTrait\HasDog::createAnimal() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\IntValue):29: Method FixMissingReturnTypeTrait\IntValue::getValue() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\IntValue):34: Method FixMissingReturnTypeTrait\IntValue::getValuePublic() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\StringValue):29: Method FixMissingReturnTypeTrait\StringValue::getValue() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\StringValue):34: Method FixMissingReturnTypeTrait\StringValue::getValuePublic() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\TypedProperty):119: Method FixMissingReturnTypeTrait\TypedProperty::get() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UntypedProperty):119: Method FixMissingReturnTypeTrait\UntypedProperty::get() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesAliased):205: Method FixMissingReturnTypeTrait\UsesAliased::aliased() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesNothing):147: Method FixMissingReturnTypeTrait\UsesNothing::doNothing() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesNothing):151: Method FixMissingReturnTypeTrait\UsesNothing::list() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesOverridable):168: Method FixMissingReturnTypeTrait\UsesOverridable::overridden() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesOverridable):173: Method FixMissingReturnTypeTrait\UsesOverridable::notOverridden() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesOverridable):178: Method FixMissingReturnTypeTrait\UsesOverridable::privateInOverridableClass() has no return type specified.', + 'traits.php (in context of class FixMissingReturnTypeTrait\UsesPrivateMethodInOneClass):12: Method FixMissingReturnTypeTrait\UsesPrivateMethodInOneClass::privateMethod() has no return type specified.', + 'traits.php:195: Method FixMissingReturnTypeTrait\OverridesTraitMethod::overridden() has no return type specified.', + ], $errors); + } + + private function getFixedFile(string $name): string + { + return __DIR__ . '/data/fix-missing-return-type/' . $name . '-' . static::getPhpVersionSuffix() . '.php.fixed'; + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/data/fix-missing-return-type-' . static::getPhpVersionSuffix() . '.neon', + ]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon new file mode 100644 index 00000000000..8f92412bf73 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: 70400 + featureToggles: + fixMissingReturnTypes: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon new file mode 100644 index 00000000000..bd000042fa9 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: 80000 + featureToggles: + fixMissingReturnTypes: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon new file mode 100644 index 00000000000..37e0a8a815e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: 80100 + featureToggles: + fixMissingReturnTypes: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon new file mode 100644 index 00000000000..0111e7acb63 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon @@ -0,0 +1,4 @@ +parameters: + phpVersion: 80200 + featureToggles: + fixMissingReturnTypes: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed new file mode 100644 index 00000000000..d832d0a0a1d --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -0,0 +1,147 @@ + 1]; +} + +/** + * @return \Generator<'a', 1, mixed, true> + */ +function generator(): \Generator +{ + yield 'a' => 1; + return true; +} + +/** + * @return never + */ +function alwaysThrows(): void +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +/** + * @return \ArrayIterator|\ArrayObject + */ +function returnsObjects(bool $b): \ArrayAccess +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +/** + * @return false + */ +function returnsFalse(): bool +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +/** + * @return \Generator + */ +function delegates(bool $b): \Generator +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +/** + * @return \Generator + */ +function delegatesToIterator(): \Generator +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + * @return array|iterable + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable +{ + return $b ? $a : $i; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed new file mode 100644 index 00000000000..6d8d341de60 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -0,0 +1,147 @@ + 1]; +} + +/** + * @return \Generator<'a', 1, mixed, true> + */ +function generator(): \Generator +{ + yield 'a' => 1; + return true; +} + +/** + * @return never + */ +function alwaysThrows(): void +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +/** + * @return \ArrayIterator|\ArrayObject + */ +function returnsObjects(bool $b): \ArrayObject|\ArrayIterator +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +/** + * @return false + */ +function returnsFalse(): bool +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +/** + * @return \Generator + */ +function delegates(bool $b): \Generator +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +/** + * @return \Generator + */ +function delegatesToIterator(): \Generator +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + * @return array|iterable + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable +{ + return $b ? $a : $i; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed new file mode 100644 index 00000000000..e2eff36ca07 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -0,0 +1,144 @@ + 1]; +} + +/** + * @return \Generator<'a', 1, mixed, true> + */ +function generator(): \Generator +{ + yield 'a' => 1; + return true; +} + +function alwaysThrows(): never +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +/** + * @return \ArrayIterator|\ArrayObject + */ +function returnsObjects(bool $b): \ArrayObject|\ArrayIterator +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +/** + * @return false + */ +function returnsFalse(): bool +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +/** + * @return \Generator + */ +function delegates(bool $b): \Generator +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +/** + * @return \Generator + */ +function delegatesToIterator(): \Generator +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + * @return array|iterable + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable +{ + return $b ? $a : $i; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed new file mode 100644 index 00000000000..ff848849c24 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -0,0 +1,141 @@ + 1]; +} + +/** + * @return \Generator<'a', 1, mixed, true> + */ +function generator(): \Generator +{ + yield 'a' => 1; + return true; +} + +function alwaysThrows(): never +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +/** + * @return \ArrayIterator|\ArrayObject + */ +function returnsObjects(bool $b): \ArrayObject|\ArrayIterator +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +function returnsFalse(): false +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +/** + * @return \Generator + */ +function delegates(bool $b): \Generator +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +/** + * @return \Generator + */ +function delegatesToIterator(): \Generator +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + * @return array|iterable + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable +{ + return $b ? $a : $i; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php74.php.fixed new file mode 100644 index 00000000000..4b20dec7a4e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php74.php.fixed @@ -0,0 +1,43 @@ + $a + * @return list + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b): array +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + * @return list + */ +function ignoreAboveParam(array $a, $b): array +{ + return $a; +} + +/** + * @return array{a: int} + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b): array +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php80.php.fixed new file mode 100644 index 00000000000..4b20dec7a4e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php80.php.fixed @@ -0,0 +1,43 @@ + $a + * @return list + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b): array +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + * @return list + */ +function ignoreAboveParam(array $a, $b): array +{ + return $a; +} + +/** + * @return array{a: int} + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b): array +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php81.php.fixed new file mode 100644 index 00000000000..4b20dec7a4e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php81.php.fixed @@ -0,0 +1,43 @@ + $a + * @return list + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b): array +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + * @return list + */ +function ignoreAboveParam(array $a, $b): array +{ + return $a; +} + +/** + * @return array{a: int} + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b): array +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php82.php.fixed new file mode 100644 index 00000000000..4b20dec7a4e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php82.php.fixed @@ -0,0 +1,43 @@ + $a + * @return list + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b): array +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + * @return list + */ +function ignoreAboveParam(array $a, $b): array +{ + return $a; +} + +/** + * @return array{a: int} + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b): array +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores.php new file mode 100644 index 00000000000..a08bfba3d4f --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores.php @@ -0,0 +1,40 @@ + $a + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b) +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + */ +function ignoreAboveParam(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b) +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php new file mode 100644 index 00000000000..395155bf083 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -0,0 +1,125 @@ + 1]; +} + +function generator() +{ + yield 'a' => 1; + return true; +} + +function alwaysThrows() +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +function returnsObjects(bool $b) +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +function returnsFalse() +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +function delegates(bool $b) +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +function delegatesToIterator() +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b) +{ + return $b ? $a : $i; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed new file mode 100644 index 00000000000..2caf05ad450 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -0,0 +1,134 @@ + + */ + public function generator(): \Generator + { + yield 1; + } + + /** + * @return static + */ + public function returnsThis(): self + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString(): string + { + return 'foo'; + } + + public function createAnimal(): Cat + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class IterableParent +{ + + /** + * @return array{int}|array{string} + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed new file mode 100644 index 00000000000..cc043cc6aac --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -0,0 +1,125 @@ + + */ + public function generator(): \Generator + { + yield 1; + } + + public function returnsThis(): static + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString(): string + { + return 'foo'; + } + + public function createAnimal(): Cat + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class IterableParent +{ + + /** + * @return array{int}|array{string} + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed new file mode 100644 index 00000000000..4b190efff95 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -0,0 +1,122 @@ + + */ + public function generator(): \Generator + { + yield 1; + } + + public function returnsThis(): static + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString(): string + { + return 'foo'; + } + + public function createAnimal(): Cat + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class IterableParent +{ + + /** + * @return array{int}|array{string} + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed new file mode 100644 index 00000000000..4b190efff95 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -0,0 +1,122 @@ + + */ + public function generator(): \Generator + { + yield 1; + } + + public function returnsThis(): static + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString(): string + { + return 'foo'; + } + + public function createAnimal(): Cat + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class IterableParent +{ + + /** + * @return array{int}|array{string} + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed new file mode 100644 index 00000000000..7543b91423d --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -0,0 +1,122 @@ +value; + } + + public function getValuePublic() + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + /** + * @return Cat|Dog + */ + public function createAnimal(): Animal + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + /** + * @return static + */ + public function fluent(): self + { + return $this; + } + + public function newSelf() + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden(): int + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden(): string + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed new file mode 100644 index 00000000000..111c0102b0e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden(): int|string + { + return 1; + } + + protected function notOverridden(): int + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden(): string + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed new file mode 100644 index 00000000000..111c0102b0e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden(): int|string + { + return 1; + } + + protected function notOverridden(): int + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden(): string + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed new file mode 100644 index 00000000000..111c0102b0e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden(): int|string + { + return 1; + } + + protected function notOverridden(): int + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden(): string + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed new file mode 100644 index 00000000000..2f880179550 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed @@ -0,0 +1,238 @@ +value; + } + + public function getValuePublic() + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + /** + * @return Cat|Dog + */ + public function createAnimal(): Animal + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + /** + * @return static + */ + public function fluent(): self + { + return $this; + } + + public function newSelf() + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed new file mode 100644 index 00000000000..1ebcb9939f9 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed new file mode 100644 index 00000000000..1ebcb9939f9 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed new file mode 100644 index 00000000000..1ebcb9939f9 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed @@ -0,0 +1,232 @@ +value; + } + + public function getValuePublic(): int|string + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal(): Dog|Cat + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent(): static + { + return $this; + } + + public function newSelf(): FluentOne|FluentTwo + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{1, 2} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits.php b/tests/PHPStan/Rules/data/fix-missing-return-type/traits.php new file mode 100644 index 00000000000..6fb5bd8114a --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits.php @@ -0,0 +1,229 @@ +value; + } + + public function getValuePublic() + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + public function createAnimal() + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + public function fluent() + { + return $this; + } + + public function newSelf() + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing() + { + } + + public function list() + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass() + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original() + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} From e991e2d0654744a6e59b9ba4ade7913b6b96e243 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:05:06 +0000 Subject: [PATCH 06/24] Do not fix the return type of a function returning a value as never or void A function whose return statements return only the result of a call to a function that never returns, or to one returning void, returns never or void, but PHP forbids a return statement with a value in a function declaring never or void. Its missing return type is not fixed. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeCollector.php | 2 +- src/Rules/MissingReturnTypeFixRule.php | 7 +++--- src/Rules/MissingReturnTypeFixer.php | 18 ++++++++++--- .../functions-php74.php.fixed | 25 +++++++++++++++++++ .../functions-php80.php.fixed | 25 +++++++++++++++++++ .../functions-php81.php.fixed | 25 +++++++++++++++++++ .../functions-php82.php.fixed | 25 +++++++++++++++++++ .../fix-missing-return-type/functions.php | 25 +++++++++++++++++++ 8 files changed, 144 insertions(+), 8 deletions(-) diff --git a/src/Rules/MissingReturnTypeCollector.php b/src/Rules/MissingReturnTypeCollector.php index 02a77436afa..849a37b6446 100644 --- a/src/Rules/MissingReturnTypeCollector.php +++ b/src/Rules/MissingReturnTypeCollector.php @@ -26,7 +26,7 @@ * * Not registered as a collector, the data is emitted by the rules for missing return types. * - * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> + * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> */ final class MissingReturnTypeCollector implements Collector { diff --git a/src/Rules/MissingReturnTypeFixRule.php b/src/Rules/MissingReturnTypeFixRule.php index a625c4204b9..98a14635868 100644 --- a/src/Rules/MissingReturnTypeFixRule.php +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -30,7 +30,7 @@ * so that \$this is static. Its return type covers what it returns in all of them, they share one fix. * * @phpstan-import-type ReturnInfo from MissingReturnTypeFixer - * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} + * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} * @implements Rule */ #[RegisteredRule(level: 6)] @@ -265,6 +265,7 @@ private function getReturnInfo(string $key): ?array $returnInfo = [ 'values' => $values, 'void' => $record['returnInfo']['void'], + 'returnsValue' => $record['returnInfo']['returnsValue'], ]; } } @@ -279,10 +280,10 @@ private function createNativeReturnInfo(Type $nativeType): array { // an overriding method declaring void forbids returning a value if ($nativeType->isVoid()->yes()) { - return ['values' => new NeverType(true), 'void' => true]; + return ['values' => new NeverType(true), 'void' => true, 'returnsValue' => false]; } - return ['values' => $nativeType, 'void' => false]; + return ['values' => $nativeType, 'void' => false, 'returnsValue' => false]; } private function resolve(?string $type, ?string $className): ?Type diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index 607febd9d70..eae3247f587 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -53,10 +53,11 @@ * with a native type and a @return PHPDoc tag. Experimental, enabled by the fixMissingReturnTypes feature toggle. * * What a function returns is described by its return info: the union of the returned values (never when - * there are none), and whether it returns without a value, falling off its end or with a bare return statement. + * there are none), whether it returns without a value, falling off its end or with a bare return statement, + * and whether it has a return statement with a value, even one that never returns, like a call to a function returning never. * A generator returns the Generator described by its yields. * - * @phpstan-type ReturnInfo array{values: Type, void: bool} + * @phpstan-type ReturnInfo array{values: Type, void: bool, returnsValue: bool} */ #[AutowiredService] final class MissingReturnTypeFixer @@ -101,7 +102,7 @@ public function serialize(Type $type): ?string /** * @param ReturnInfo $returnInfo - * @return array{values: string, void: bool}|null + * @return array{values: string, void: bool, returnsValue: bool}|null */ public function serializeReturnInfo(array $returnInfo): ?array { @@ -110,7 +111,7 @@ public function serializeReturnInfo(array $returnInfo): ?array return null; } - return ['values' => $values, 'void' => $returnInfo['void']]; + return ['values' => $values, 'void' => $returnInfo['void'], 'returnsValue' => $returnInfo['returnsValue']]; } public function isEnabled(): bool @@ -138,6 +139,7 @@ public function getReturnInfo(MethodReturnStatementsNode|FunctionReturnStatement $returnInfo = [ 'values' => count($values) === 0 ? new NeverType(true) : TypeCombinator::union(...$values), 'void' => $void || !$node->getStatementResult()->isAlwaysTerminating(), + 'returnsValue' => count($values) > 0, ]; if (!$node->isGenerator()) { return $returnInfo; @@ -198,6 +200,7 @@ private function createGeneratorReturnInfo(Type $keyType, Type $valueType, Type $generatorReturnType, ]), 'void' => false, + 'returnsValue' => false, ]; } @@ -205,6 +208,8 @@ private function createGeneratorReturnInfo(Type $keyType, Type $valueType, Type * The type the functions with these return infos return together, null when no return type * can be declared for them: some return nothing, others a value. With a declared return type, * PHPStan reports falling off the end of the function, and PHP a bare return statement. + * Also null when they return only never or void with a return statement with a value, + * PHP forbids it in a function declaring never or void. * * @param non-empty-list $returnInfos */ @@ -212,12 +217,17 @@ public function combine(array $returnInfos): ?Type { $values = []; $void = false; + $returnsValue = false; foreach ($returnInfos as $returnInfo) { $values[] = $returnInfo['values']; $void = $void || $returnInfo['void']; + $returnsValue = $returnsValue || $returnInfo['returnsValue']; } $type = TypeCombinator::union(...$values); + if ($returnsValue && ($type instanceof NeverType || $type->isVoid()->yes())) { + return null; + } if (!$void) { return $type; } diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed index d832d0a0a1d..274b42db4f0 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -145,3 +145,28 @@ function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable { return $b ? $a : $i; } + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid() +{ + return declaredVoid(); +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed index 6d8d341de60..c81d1664ae9 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -145,3 +145,28 @@ function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable { return $b ? $a : $i; } + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid() +{ + return declaredVoid(); +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed index e2eff36ca07..9c50a30813b 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -142,3 +142,28 @@ function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable { return $b ? $a : $i; } + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid() +{ + return declaredVoid(); +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed index ff848849c24..eec176cdb2e 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -139,3 +139,28 @@ function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable { return $b ? $a : $i; } + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid(): null +{ + return declaredVoid(); +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php index 395155bf083..804cc64bba9 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -123,3 +123,28 @@ function returnsArrayOfStrings(array $a, iterable $i, bool $b) { return $b ? $a : $i; } + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid() +{ + return declaredVoid(); +} From 532ef1289c3c22646c5e2e6f43bc036d429757a4 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:06:25 +0000 Subject: [PATCH 07/24] Fix the return type of a function returning an anonymous class with its parent class or interfaces An anonymous class cannot be named in a return type. It is replaced by its parent class, the intersection of the interfaces it implements, or object, in the native type and in the @return PHPDoc tag. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixer.php | 14 ++++- src/Type/ObjectType.php | 34 ++++++++++++ .../functions-php74.php.fixed | 54 +++++++++++++++++++ .../functions-php80.php.fixed | 54 +++++++++++++++++++ .../functions-php81.php.fixed | 51 ++++++++++++++++++ .../functions-php82.php.fixed | 51 ++++++++++++++++++ .../fix-missing-return-type/functions.php | 48 +++++++++++++++++ turbo-ext/src/ObjectType.cpp | 47 +++++++++++++--- turbo-ext/src/generated/ObjectType.h | 19 ++++--- 9 files changed, 356 insertions(+), 16 deletions(-) diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index eae3247f587..50c3064a696 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -432,7 +432,8 @@ private function createNativeTypeNode(Type $type, ?PhpVersion $phpVersion = null } /** - * The closest class or interface all the objects of the type are instances of, without union types before PHP 8.0. + * The closest class or interface all the objects of the type are instances of, without union types before PHP 8.0 + * and intersection types before PHP 8.1. */ private function findCommonParentType(Type $type): ?Type { @@ -441,13 +442,22 @@ private function findCommonParentType(Type $type): ?Type } $classNames = $type->getObjectClassNames(); - if (count($classNames) < 2) { + if (count($classNames) === 0) { return null; } + // a single named class has no better candidate, an anonymous class is written as one of its ancestors $firstClass = $this->reflectionProvider->getClass($classNames[0]); + if (count($classNames) === 1 && !$firstClass->isAnonymous()) { + return null; + } + $candidates = [$firstClass, ...$firstClass->getParents(), ...array_values($firstClass->getInterfaces())]; foreach ($candidates as $candidate) { + if ($candidate->isAnonymous()) { + continue; + } + $candidateType = new ObjectType($candidate->getName()); if (!$candidateType->isSuperTypeOf($type)->yes()) { continue; diff --git a/src/Type/ObjectType.php b/src/Type/ObjectType.php index 0d68e03dbd0..3126b99ef24 100644 --- a/src/Type/ObjectType.php +++ b/src/Type/ObjectType.php @@ -2178,11 +2178,21 @@ public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type public function toPhpDocNode(): TypeNode { + $writtenType = $this->getAnonymousClassWrittenType(); + if ($writtenType !== null) { + return $writtenType->toPhpDocNode(); + } + return new FullyQualifiedNameNode($this->getClassName()); } public function toNativePhpTypeNode(NativeTypePosition $position) { + $writtenType = $this->getAnonymousClassWrittenType(); + if ($writtenType !== null) { + return $writtenType->toNativePhpTypeNode($position); + } + $className = $this->getClassName(); if ($className === '' || !$position->isClassNameAllowed()) { return null; @@ -2191,6 +2201,30 @@ public function toNativePhpTypeNode(NativeTypePosition $position) return new FullyQualified($className); } + /** + * An anonymous class cannot be named in a type, it is written as its parent class, + * the intersection of the interfaces it implements, or object. Null for a named class. + */ + private function getAnonymousClassWrittenType(): ?Type + { + $classReflection = $this->getClassReflection(); + if ($classReflection === null || !$classReflection->isAnonymous()) { + return null; + } + + $parent = $this->getParent(); + if ($parent !== null) { + return $parent; + } + + $interfaces = $this->getInterfaces(); + if (count($interfaces) === 0) { + return new ObjectWithoutClassType(); + } + + return TypeCombinator::intersect(...array_values($interfaces)); + } + public function hasTemplateOrLateResolvableType(): bool { if ($this->subtractedType === null) { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed index 274b42db4f0..79b44166bd2 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -170,3 +170,57 @@ function returnsVoid() { return declaredVoid(); } + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass(): AbstractAnimal +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation(): Named +{ + return new class implements Named { + }; +} + +/** + * @return Aged&Named + */ +function returnsAnonymousWithInterfaces(): Named +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass(): object +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b): ?AbstractAnimal +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +/** + * @return array{AbstractAnimal} + */ +function returnsAnonymousInArray(): array +{ + return [new class extends AbstractAnimal { + }]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed index c81d1664ae9..8a037854826 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -170,3 +170,57 @@ function returnsVoid() { return declaredVoid(); } + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass(): AbstractAnimal +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation(): Named +{ + return new class implements Named { + }; +} + +/** + * @return Aged&Named + */ +function returnsAnonymousWithInterfaces(): Named +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass(): object +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b): ?AbstractAnimal +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +/** + * @return array{AbstractAnimal} + */ +function returnsAnonymousInArray(): array +{ + return [new class extends AbstractAnimal { + }]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed index 9c50a30813b..100f2a426d1 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -167,3 +167,54 @@ function returnsVoid() { return declaredVoid(); } + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass(): AbstractAnimal +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation(): Named +{ + return new class implements Named { + }; +} + +function returnsAnonymousWithInterfaces(): Named&Aged +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass(): object +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b): ?AbstractAnimal +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +/** + * @return array{AbstractAnimal} + */ +function returnsAnonymousInArray(): array +{ + return [new class extends AbstractAnimal { + }]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed index eec176cdb2e..53499059ac8 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -164,3 +164,54 @@ function returnsVoid(): null { return declaredVoid(); } + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass(): AbstractAnimal +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation(): Named +{ + return new class implements Named { + }; +} + +function returnsAnonymousWithInterfaces(): Named&Aged +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass(): object +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b): ?AbstractAnimal +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +/** + * @return array{AbstractAnimal} + */ +function returnsAnonymousInArray(): array +{ + return [new class extends AbstractAnimal { + }]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php index 804cc64bba9..252c1bf55e6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -148,3 +148,51 @@ function returnsVoid() { return declaredVoid(); } + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass() +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation() +{ + return new class implements Named { + }; +} + +function returnsAnonymousWithInterfaces() +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass() +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b) +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +function returnsAnonymousInArray() +{ + return [new class extends AbstractAnimal { + }]; +} diff --git a/turbo-ext/src/ObjectType.cpp b/turbo-ext/src/ObjectType.cpp index 81c838d06ae..f931a2220a9 100644 --- a/turbo-ext/src/ObjectType.cpp +++ b/turbo-ext/src/ObjectType.cpp @@ -2588,12 +2588,11 @@ class ObjectType } /* $this->classReflection ?? $this->lazyClassReflection (borrowed; - * IS_NULL when neither is known; NULL with an Error pending when - * uninitialized) */ + * IS_NULL when neither is known); like ??, an uninitialized + * $classReflection reads as null, the class name read next reports it */ [[nodiscard]] zval *resolvedClassReflection() const { - zval *reflection = classReflection(); - if (UNEXPECTED(reflection == NULL)) return NULL; + zval *reflection = OBJ_PROP_NUM(self, slots::classReflection); if (Z_TYPE_P(reflection) == IS_OBJECT) return reflection; return lazyClassReflection(); } @@ -2885,18 +2884,54 @@ class ObjectType return pt_type_new_error_type(); } - /* new FullyQualifiedNameNode($this->getClassName()); UNDEF = pending exception */ + /* getAnonymousClassWrittenType(): an anonymous class's parent class, the + * intersection of its interfaces, or new ObjectWithoutClassType(); null + * for a named class; UNDEF = pending exception */ + zv::Val getAnonymousClassWrittenType() const + { + zv::Val classReflection = thisGetClassReflection(); + if (UNEXPECTED(classReflection.isUndef())) return zv::Val(); + if (classReflection.isNull()) return zv::Val::null(); + zv::Val isAnonymous = pt_type_call(Z_OBJ_P(classReflection.raw()), PT_LC("isanonymous"), 0, NULL); + if (UNEXPECTED(isAnonymous.isUndef())) return zv::Val(); + if (Z_TYPE_P(isAnonymous.raw()) != IS_TRUE) return zv::Val::null(); + + zv::Val parent = getParent(); + if (UNEXPECTED(parent.isUndef())) return zv::Val(); + if (!parent.isNull()) return parent; + + zv::Val interfaces = getInterfaces(); + if (UNEXPECTED(interfaces.isUndef())) return zv::Val(); + if (zend_hash_num_elements(Z_ARRVAL_P(interfaces.raw())) == 0) { + zval objectType; + if (UNEXPECTED(!pt_object_without_class_type_new(&objectType))) return zv::Val(); + return zv::Val::adopt(objectType); + } + return pt_type_combinator_call_spread(PT_LC("intersect"), Z_ARRVAL_P(interfaces.raw())); + } + + /* the anonymous class's written type's toPhpDocNode(), else + * new FullyQualifiedNameNode($this->getClassName()); UNDEF = pending exception */ zv::Val toPhpDocNode() const { + zv::Val writtenType = getAnonymousClassWrittenType(); + if (UNEXPECTED(writtenType.isUndef())) return zv::Val(); + if (!writtenType.isNull()) return pt_type_call(Z_OBJ_P(writtenType.raw()), PT_LC("tophpdocnode"), 0, NULL); + zv::Val name = thisGetClassName(); if (UNEXPECTED(name.isUndef())) return zv::Val(); return pt_type_new(PT_CLASS_FULLY_QUALIFIED_NAME_NODE, 1, name.raw()); } - /* null for an empty class name, else $position->isClassNameAllowed() + /* the anonymous class's written type's toNativePhpTypeNode($position), else + * null for an empty class name, else $position->isClassNameAllowed() * ? new FullyQualified($className) : null; UNDEF = pending exception */ zv::Val toNativePhpTypeNode(zval *position) const { + zv::Val writtenType = getAnonymousClassWrittenType(); + if (UNEXPECTED(writtenType.isUndef())) return zv::Val(); + if (!writtenType.isNull()) return pt_type_call(Z_OBJ_P(writtenType.raw()), PT_LC("tonativephptypenode"), 1, position); + zv::Val name = thisGetClassName(); if (UNEXPECTED(name.isUndef())) return zv::Val(); if (Z_STRLEN_P(name.raw()) == 0) return zv::Val::null(); diff --git a/turbo-ext/src/generated/ObjectType.h b/turbo-ext/src/generated/ObjectType.h index a62e858a1ac..b704d9e8721 100644 --- a/turbo-ext/src/generated/ObjectType.h +++ b/turbo-ext/src/generated/ObjectType.h @@ -238,10 +238,11 @@ inline constexpr char strings[] = "position\0" /* 3089 */ "PHPStan\\Type\\NativeTypePosition\0" /* 3098 */ "toNativePhpTypeNode\0" /* 3130 */ - "hasTemplateOrLateResolvableType\0" /* 3150 */ - "hasUnresolvedTemplateArgumentType\0" /* 3182 */ - "PHPStan\\Type\\ValueSet\0" /* 3216 */ - "toValueSet"; /* 3238 */ + "getAnonymousClassWrittenType\0" /* 3150 */ + "hasTemplateOrLateResolvableType\0" /* 3179 */ + "hasUnresolvedTemplateArgumentType\0" /* 3211 */ + "PHPStan\\Type\\ValueSet\0" /* 3245 */ + "toValueSet"; /* 3267 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, MAY_BE_STRING), /* __construct $className */ reg::packed(10, MAY_BE_NULL, 25, false, false, 43), /* __construct $subtractedType */ @@ -422,9 +423,10 @@ inline constexpr reg::PackedArg args[] = { reg::packed(111, 0, 25), /* arithmeticPower return */ reg::packed(111, 0, 3037), /* toPhpDocNode return */ reg::packed(3089, 0, 3098), /* toNativePhpTypeNode $position */ + reg::packed(111, MAY_BE_NULL, 25), /* getAnonymousClassWrittenType return */ reg::packed(111, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ reg::packed(111, MAY_BE_BOOL), /* hasUnresolvedTemplateArgumentType return */ - reg::packed(111, 0, 3216), /* toValueSet return */ + reg::packed(111, 0, 3245), /* toValueSet return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -550,9 +552,10 @@ inline constexpr sigtab::Sig getFiniteTypes = { { 2997 /* getFiniteTypes */, 0, inline constexpr sigtab::Sig arithmeticPower = { { 3021 /* arithmeticPower */, 2, 174, 2, 176, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig toPhpDocNode = { { 3076 /* toPhpDocNode */, 0, 177, 0, 177, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig toNativePhpTypeNode = { { 3130 /* toNativePhpTypeNode */, 1, 178, 1, reg::NoArg, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 3150 /* hasTemplateOrLateResolvableType */, 0, 179, 0, 179, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 3182 /* hasUnresolvedTemplateArgumentType */, 0, 180, 0, 180, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toValueSet = { { 3238 /* toValueSet */, 0, 181, 0, 181, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getAnonymousClassWrittenType = { { 3150 /* getAnonymousClassWrittenType */, 0, 179, 0, 179, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 3179 /* hasTemplateOrLateResolvableType */, 0, 180, 0, 180, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 3211 /* hasUnresolvedTemplateArgumentType */, 0, 181, 0, 181, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toValueSet = { { 3267 /* toValueSet */, 0, 182, 0, 182, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::ObjectType From 9dc42c7afe1af71c18d10078bde0eeeee02737ec Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:17:58 +0000 Subject: [PATCH 08/24] Generalize constant values and large array shapes in fixed return types The @return PHPDoc tag written by the fix of a missing return type describes what the function returns in general, not the literal values of one implementation: constant strings, integers and floats are generalized, true and false only inside arrays, and an array shape stays a shape only with at most ten keys that are integers or ASCII identifiers. Otherwise it is a general array of the generalized value types. Literals copied from a data provider made the tags huge, and a string containing */ ended the PHPDoc comment. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixer.php | 68 ++++++++++++++ .../functions-php74.php.fixed | 88 ++++++++++++++++++- .../functions-php80.php.fixed | 88 ++++++++++++++++++- .../functions-php81.php.fixed | 88 ++++++++++++++++++- .../functions-php82.php.fixed | 88 ++++++++++++++++++- .../fix-missing-return-type/functions.php | 63 +++++++++++++ .../methods-closed-project-php74.php.fixed | 4 +- .../methods-closed-project-php80.php.fixed | 4 +- .../methods-closed-project-php81.php.fixed | 4 +- .../methods-closed-project-php82.php.fixed | 4 +- .../traits-closed-project-php74.php.fixed | 2 +- .../traits-closed-project-php80.php.fixed | 2 +- .../traits-closed-project-php81.php.fixed | 2 +- .../traits-closed-project-php82.php.fixed | 2 +- .../traits-open-project-php74.php.fixed | 2 +- .../traits-open-project-php80.php.fixed | 2 +- .../traits-open-project-php81.php.fixed | 2 +- .../traits-open-project-php82.php.fixed | 2 +- 18 files changed, 491 insertions(+), 24 deletions(-) diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index 50c3064a696..12980014bac 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -23,8 +23,12 @@ use PHPStan\PhpDocParser\Printer\Printer; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\ReflectionProvider; +use PHPStan\Type\Accessory\AccessoryArrayListType; +use PHPStan\Type\Accessory\NonEmptyArrayType; use PHPStan\Type\ArrayType; +use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\ErrorType; +use PHPStan\Type\GeneralizePrecision; use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\TemplateType; use PHPStan\Type\IntegerType; @@ -44,6 +48,7 @@ use function array_splice; use function array_values; use function count; +use function preg_match; use function sprintf; use function str_starts_with; use function strtolower; @@ -63,6 +68,9 @@ final class MissingReturnTypeFixer { + /** An array shape with more keys is written as a general array, see generalize(). */ + private const ARRAY_SHAPE_KEYS_LIMIT = 10; + public function __construct( #[AutowiredParameter(ref: '%featureToggles.fixMissingReturnTypes%')] private bool $enabled, @@ -260,6 +268,7 @@ public function createFix( ?ClassReflection $classReflection, ): ?callable { + $phpDocType = $this->generalize($phpDocType); if (!$this->canWrite($phpDocType)) { return null; } @@ -320,6 +329,65 @@ public function createFix( }; } + /** + * Generalizes the returned type to one worth declaring: constant strings, integers and floats + * are generalized, so are all the constant values in an array, and an array shape stays a shape + * only with at most ARRAY_SHAPE_KEYS_LIMIT keys that are integers or ASCII identifiers, + * otherwise it is a general array. + */ + private function generalize(Type $type, bool $inArray = false): Type + { + $constantArrays = $type->getConstantArrays(); + if (count($constantArrays) === 1 && $type->isConstantArray()->yes()) { + $type = $constantArrays[0]; + if (self::canStayArrayShape($type)) { + return $type->traverse(fn (Type $innerType): Type => $this->generalize($innerType, true)); + } + + $arrayType = new ArrayType( + $type->getIterableKeyType()->generalize(GeneralizePrecision::lessSpecific()), + $this->generalize($type->getIterableValueType(), true), + ); + if ($type->isList()->yes()) { + $arrayType = TypeCombinator::intersect($arrayType, new AccessoryArrayListType()); + } + if ($type->isIterableAtLeastOnce()->yes()) { + $arrayType = TypeCombinator::intersect($arrayType, new NonEmptyArrayType()); + } + + return $arrayType; + } + + // true is worth declaring as the return type, an array of true and false values is not + if ( + $type->isConstantScalarValue()->yes() + && !$type->isNull()->yes() + && ($inArray || !$type->isBoolean()->yes()) + ) { + return $type->generalize(GeneralizePrecision::lessSpecific()); + } + + $isArray = $inArray || $type->isArray()->yes(); + + return $type->traverse(fn (Type $innerType): Type => $this->generalize($innerType, $isArray)); + } + + private static function canStayArrayShape(ConstantArrayType $type): bool + { + $keyTypes = $type->getKeyTypes(); + if (count($keyTypes) > self::ARRAY_SHAPE_KEYS_LIMIT) { + return false; + } + + foreach ($keyTypes as $keyType) { + if ($keyType->isString()->yes() && preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', (string) $keyType->getValue()) !== 1) { + return false; + } + } + + return true; + } + /** * Whether the type can be written as the return type without causing other errors: * it has to be known and every iterable, generic class and callable in it has to be described. diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed index 79b44166bd2..128e5b88b84 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -16,7 +16,7 @@ function returnsNothing(): void } /** - * @return array{a: 1} + * @return array{a: int} */ function returnsArray(): array { @@ -24,7 +24,7 @@ function returnsArray(): array } /** - * @return \Generator<'a', 1, mixed, true> + * @return \Generator */ function generator(): \Generator { @@ -224,3 +224,87 @@ function returnsAnonymousInArray(): array return [new class extends AbstractAnimal { }]; } + +/** + * @return array{id: int, name: string, tags: array{string, string}, active: bool, parent: null} + */ +function returnsSmallShape(): array +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +/** + * @return non-empty-array + */ +function returnsLargeShape(): array +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithNonAsciiKey(): array +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithEndOfCommentKey(): array +{ + return ['a*/' => 1]; +} + +/** + * @return array{array{string, string, bool, null}, array{string, string, bool, string}} + */ +function dataProvider(): array +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + * @return list + */ +function returnsListOfConstantString(array $ints): array +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +/** + * @return \Generator + */ +function yieldsConstantStrings(): \Generator +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + * @return array{a: string, ...} + */ +function returnsUnsealedShape(array $a): array +{ + return $a; +} + +/** + * @param array{...}>} $a + * @return array}> + */ +function returnsNestedUnsealedShape(array $a): array +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed index 8a037854826..bd71dc85145 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -16,7 +16,7 @@ function returnsNothing(): void } /** - * @return array{a: 1} + * @return array{a: int} */ function returnsArray(): array { @@ -24,7 +24,7 @@ function returnsArray(): array } /** - * @return \Generator<'a', 1, mixed, true> + * @return \Generator */ function generator(): \Generator { @@ -224,3 +224,87 @@ function returnsAnonymousInArray(): array return [new class extends AbstractAnimal { }]; } + +/** + * @return array{id: int, name: string, tags: array{string, string}, active: bool, parent: null} + */ +function returnsSmallShape(): array +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +/** + * @return non-empty-array + */ +function returnsLargeShape(): array +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithNonAsciiKey(): array +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithEndOfCommentKey(): array +{ + return ['a*/' => 1]; +} + +/** + * @return array{array{string, string, bool, null}, array{string, string, bool, string}} + */ +function dataProvider(): array +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + * @return list + */ +function returnsListOfConstantString(array $ints): array +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +/** + * @return \Generator + */ +function yieldsConstantStrings(): \Generator +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + * @return array{a: string, ...} + */ +function returnsUnsealedShape(array $a): array +{ + return $a; +} + +/** + * @param array{...}>} $a + * @return array}> + */ +function returnsNestedUnsealedShape(array $a): array +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed index 100f2a426d1..d21322e4aac 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -16,7 +16,7 @@ function returnsNothing(): void } /** - * @return array{a: 1} + * @return array{a: int} */ function returnsArray(): array { @@ -24,7 +24,7 @@ function returnsArray(): array } /** - * @return \Generator<'a', 1, mixed, true> + * @return \Generator */ function generator(): \Generator { @@ -218,3 +218,87 @@ function returnsAnonymousInArray(): array return [new class extends AbstractAnimal { }]; } + +/** + * @return array{id: int, name: string, tags: array{string, string}, active: bool, parent: null} + */ +function returnsSmallShape(): array +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +/** + * @return non-empty-array + */ +function returnsLargeShape(): array +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithNonAsciiKey(): array +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithEndOfCommentKey(): array +{ + return ['a*/' => 1]; +} + +/** + * @return array{array{string, string, bool, null}, array{string, string, bool, string}} + */ +function dataProvider(): array +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + * @return list + */ +function returnsListOfConstantString(array $ints): array +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +/** + * @return \Generator + */ +function yieldsConstantStrings(): \Generator +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + * @return array{a: string, ...} + */ +function returnsUnsealedShape(array $a): array +{ + return $a; +} + +/** + * @param array{...}>} $a + * @return array}> + */ +function returnsNestedUnsealedShape(array $a): array +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed index 53499059ac8..9136a9d71f3 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -16,7 +16,7 @@ function returnsNothing(): void } /** - * @return array{a: 1} + * @return array{a: int} */ function returnsArray(): array { @@ -24,7 +24,7 @@ function returnsArray(): array } /** - * @return \Generator<'a', 1, mixed, true> + * @return \Generator */ function generator(): \Generator { @@ -215,3 +215,87 @@ function returnsAnonymousInArray(): array return [new class extends AbstractAnimal { }]; } + +/** + * @return array{id: int, name: string, tags: array{string, string}, active: bool, parent: null} + */ +function returnsSmallShape(): array +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +/** + * @return non-empty-array + */ +function returnsLargeShape(): array +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithNonAsciiKey(): array +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithEndOfCommentKey(): array +{ + return ['a*/' => 1]; +} + +/** + * @return array{array{string, string, bool, null}, array{string, string, bool, string}} + */ +function dataProvider(): array +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + * @return list + */ +function returnsListOfConstantString(array $ints): array +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +/** + * @return \Generator + */ +function yieldsConstantStrings(): \Generator +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + * @return array{a: string, ...} + */ +function returnsUnsealedShape(array $a): array +{ + return $a; +} + +/** + * @param array{...}>} $a + * @return array}> + */ +function returnsNestedUnsealedShape(array $a): array +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php index 252c1bf55e6..43e2f790a6e 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -196,3 +196,66 @@ function returnsAnonymousInArray() return [new class extends AbstractAnimal { }]; } + +function returnsSmallShape() +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +function returnsLargeShape() +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +function returnsShapeWithNonAsciiKey() +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +function returnsShapeWithEndOfCommentKey() +{ + return ['a*/' => 1]; +} + +function dataProvider() +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + */ +function returnsListOfConstantString(array $ints) +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +function yieldsConstantStrings() +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + */ +function returnsUnsealedShape(array $a) +{ + return $a; +} + +/** + * @param array{...}>} $a + */ +function returnsNestedUnsealedShape(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed index 2caf05ad450..a18c946aafc 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -59,7 +59,7 @@ class ParentClass } /** - * @return array{1, 2} + * @return array{int, int} */ public function notOverridden(): array { @@ -67,7 +67,7 @@ class ParentClass } /** - * @return \Generator + * @return \Generator */ public function generator(): \Generator { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed index cc043cc6aac..46e8bd9afbc 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -53,7 +53,7 @@ class ParentClass } /** - * @return array{1, 2} + * @return array{int, int} */ public function notOverridden(): array { @@ -61,7 +61,7 @@ class ParentClass } /** - * @return \Generator + * @return \Generator */ public function generator(): \Generator { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed index 4b190efff95..010e75de37f 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -50,7 +50,7 @@ class ParentClass } /** - * @return array{1, 2} + * @return array{int, int} */ public function notOverridden(): array { @@ -58,7 +58,7 @@ class ParentClass } /** - * @return \Generator + * @return \Generator */ public function generator(): \Generator { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed index 4b190efff95..010e75de37f 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -50,7 +50,7 @@ class ParentClass } /** - * @return array{1, 2} + * @return array{int, int} */ public function notOverridden(): array { @@ -58,7 +58,7 @@ class ParentClass } /** - * @return \Generator + * @return \Generator */ public function generator(): \Generator { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed index 943f3276b84..b2f5745ad84 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed @@ -155,7 +155,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed index 111c0102b0e..3f579c8edd2 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php80.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed index 111c0102b0e..3f579c8edd2 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php81.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed index 111c0102b0e..3f579c8edd2 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php82.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed index 2f880179550..71cd06f18b0 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php74.php.fixed @@ -155,7 +155,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed index 1ebcb9939f9..f9b477cb4d6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php80.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed index 1ebcb9939f9..f9b477cb4d6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php81.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed index 1ebcb9939f9..f9b477cb4d6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php82.php.fixed @@ -149,7 +149,7 @@ trait Nothing } /** - * @return array{1, 2} + * @return array{int, int} */ public function list(): array { From 0e513fdb61b2ab7e1ea2e34a51a1106119df18ee Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:33:08 +0000 Subject: [PATCH 09/24] Pass the files changed by the previous rounds of --fix in a file Every next round of --fix got each file the previous rounds changed as a --fixed-ignored-in option, even without --fix-ignored, the only option that reads them. After thousands of changed files, the command of the round exceeded the length the system allows and could not be launched. The list is now written to a JSON file in tmpDir, passed with --fixed-files, and removed after the round. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- e2e/fix-many-files/.gitignore | 4 +++ e2e/fix-many-files/composer.json | 7 ++++ e2e/fix-many-files/fix-many-files_test.sh | 28 +++++++++++++++ e2e/fix-many-files/phpstan.neon | 8 +++++ e2e/fix-many-files/rules/StepRule.php | 43 +++++++++++++++++++++++ src/Command/AnalyseCommand.php | 35 ++++++++++++------ 6 files changed, 114 insertions(+), 11 deletions(-) create mode 100644 e2e/fix-many-files/.gitignore create mode 100644 e2e/fix-many-files/composer.json create mode 100755 e2e/fix-many-files/fix-many-files_test.sh create mode 100644 e2e/fix-many-files/phpstan.neon create mode 100644 e2e/fix-many-files/rules/StepRule.php diff --git a/e2e/fix-many-files/.gitignore b/e2e/fix-many-files/.gitignore new file mode 100644 index 00000000000..82cdbfd52b3 --- /dev/null +++ b/e2e/fix-many-files/.gitignore @@ -0,0 +1,4 @@ +/src +/tmp +/vendor +/composer.lock diff --git a/e2e/fix-many-files/composer.json b/e2e/fix-many-files/composer.json new file mode 100644 index 00000000000..12a1404d2e9 --- /dev/null +++ b/e2e/fix-many-files/composer.json @@ -0,0 +1,7 @@ +{ + "autoload-dev": { + "classmap": [ + "rules/" + ] + } +} diff --git a/e2e/fix-many-files/fix-many-files_test.sh b/e2e/fix-many-files/fix-many-files_test.sh new file mode 100755 index 00000000000..c9bb618f8cb --- /dev/null +++ b/e2e/fix-many-files/fix-many-files_test.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# @tags result-cache + +function set_up() { + e2e::set_up +} + +function tear_down() { + e2e::tear_down +} + +# the files changed by the previous rounds do not fit on the command line of the next round +function test_fix_many_files() { + composer install + rm -rf src tmp && mkdir -p src + printf ' src/functions.php + for i in $(seq 1 2000); do + printf ' "src/a-file-with-a-name-long-enough-to-fill-the-command-line-of-the-next-round-$i.php" + done + OUTPUT=$(../../bin/phpstan analyse --fix 2>&1) && CODE=0 || CODE=$? + echo "$OUTPUT" | tail -20 + assert_same "0" "$CODE" + assert_contains 'Round 2: fixed 2000 errors in 2000 files' "$OUTPUT" + assert_contains '[OK] 4000 errors fixed in 2000 files' "$OUTPUT" + assert_same "step3();" "$(tail -1 src/a-file-with-a-name-long-enough-to-fill-the-command-line-of-the-next-round-1.php)" + # the list of the changed files is removed after the rounds + assert_same "" "$(find tmp -name 'fixed-files-*')" +} diff --git a/e2e/fix-many-files/phpstan.neon b/e2e/fix-many-files/phpstan.neon new file mode 100644 index 00000000000..fe1926b5fb3 --- /dev/null +++ b/e2e/fix-many-files/phpstan.neon @@ -0,0 +1,8 @@ +parameters: + level: 0 + paths: + - src + tmpDir: tmp + +rules: + - FixManyFilesE2E\StepRule diff --git a/e2e/fix-many-files/rules/StepRule.php b/e2e/fix-many-files/rules/StepRule.php new file mode 100644 index 00000000000..2684949d94e --- /dev/null +++ b/e2e/fix-many-files/rules/StepRule.php @@ -0,0 +1,43 @@ + + */ +final class StepRule implements Rule +{ + + public function getNodeType(): string + { + return FuncCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->name instanceof Node\Name || preg_match('~^step([1-2])$~', $node->name->toString(), $matches) !== 1) { + return []; + } + + $next = 'step' . ((int) $matches[1] + 1); + + return [ + RuleErrorBuilder::message(sprintf('Call %s() instead.', $next)) + ->identifier('fixManyFilesE2E.step') + ->fixNode($node, static function (FuncCall $node) use ($next): FuncCall { + $node->name = new Node\Name($next); + return $node; + }) + ->build(), + ]; + } + +} diff --git a/src/Command/AnalyseCommand.php b/src/Command/AnalyseCommand.php index 114757add92..32d3db49349 100644 --- a/src/Command/AnalyseCommand.php +++ b/src/Command/AnalyseCommand.php @@ -75,6 +75,8 @@ use function strlen; use function substr; use function trim; +use function uniqid; +use function unlink; use const PATHINFO_BASENAME; use const PATHINFO_EXTENSION; @@ -102,7 +104,7 @@ final class AnalyseCommand extends Command private const OPTION_FIX_ROUND = 'fix-round'; - private const OPTION_FIXED_IGNORED_IN = 'fixed-ignored-in'; + private const OPTION_FIXED_FILES = 'fixed-files'; /** * @param string[] $composerAutoloaderProjectPaths @@ -137,7 +139,7 @@ protected function configure(): void new InputOption('fix', mode: InputOption::VALUE_NONE, description: 'Fix auto-fixable errors (experimental)'), new InputOption('fix-ignored', mode: InputOption::VALUE_NONE, description: 'Fix auto-fixable ignored errors, can be combined with --fix (experimental)'), new InputOption(self::OPTION_FIX_ROUND, mode: InputOption::VALUE_NONE, description: '(Internal) Run one round of --fix and print its counts as JSON'), - new InputOption(self::OPTION_FIXED_IGNORED_IN, mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, description: '(Internal) Files changed by the previous rounds of --fix-ignored'), + new InputOption(self::OPTION_FIXED_FILES, mode: InputOption::VALUE_REQUIRED, description: '(Internal) JSON file with the list of the files changed by the previous rounds of --fix'), new InputOption('watch', mode: InputOption::VALUE_NONE, description: 'Launch PHPStan Pro'), new InputOption('pro', mode: InputOption::VALUE_NONE, description: 'Launch PHPStan Pro'), new InputOption('fail-without-result-cache', mode: InputOption::VALUE_NONE, description: 'Return non-zero exit code when result cache is not used'), @@ -588,7 +590,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (!$fixReported) { // a fixed ignored error leaves behind the ignore that matched it, like an unmatched baseline entry // or a count that is too high, those are reported in the files the previous rounds changed - $fixedIgnoredIn = array_fill_keys($input->getOption(self::OPTION_FIXED_IGNORED_IN), true); + $fixedFilesFile = $input->getOption(self::OPTION_FIXED_FILES); + /** @var list $fixedFiles */ + $fixedFiles = is_string($fixedFilesFile) ? Json::decode(FileReader::read($fixedFilesFile), Json::FORCE_ARRAY) : []; + $fixedIgnoredIn = array_fill_keys($fixedFiles, true); foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) { if ( !$fileSpecificError->isFixable() @@ -688,6 +693,7 @@ private function fixInRounds( { $errorOutput = $inceptionResult->getErrorOutput(); $stdOutput = $inceptionResult->getStdOutput(); + $tmpDir = $inceptionResult->getContainer()->getParameter('tmpDir'); $appliedCount = count($fixResult->getFixedErrors()); $roundChangedFiles = $fixResult->getChangedFiles(); $fixedCount = 0; @@ -716,6 +722,9 @@ private function fixInRounds( $round++; $errorOutput->writeLineFormatted(''); $errorOutput->writeLineFormatted(sprintf('Analysing fixed code (round %d)...', $round)); + // thousands of changed files do not fit on the command line + $fixedFilesFile = sprintf('%s/%s.json', $tmpDir, uniqid('fixed-files-', true)); + FileWriter::write($fixedFilesFile, Json::encode(array_keys($changedFiles))); $command = ProcessHelper::getWorkerCommand( $_SERVER['argv'][0], self::NAME, @@ -725,19 +734,23 @@ private function fixInRounds( (bool) $input->getOption(ErrorsConsoleStyle::OPTION_NO_PROGRESS) ? ['--' . ErrorsConsoleStyle::OPTION_NO_PROGRESS] : [], (bool) $input->getOption('fix') ? ['--fix'] : [], (bool) $input->getOption('fix-ignored') ? ['--fix-ignored'] : [], - array_map(static fn (string $file): string => '--' . self::OPTION_FIXED_IGNORED_IN . '=' . escapeshellarg($file), array_keys($changedFiles)), + ['--' . self::OPTION_FIXED_FILES . '=' . escapeshellarg($fixedFilesFile)], ), $input, ); $process = Process::fromShellCommandline($command, timeout: null); - // the progress bar of the analysis is on stderr, the result of the round on stdout - $process->run(static function (string $type, string $buffer) use ($errorOutput): void { - if ($type !== Process::ERR) { - return; - } + try { + // the progress bar of the analysis is on stderr, the result of the round on stdout + $process->run(static function (string $type, string $buffer) use ($errorOutput): void { + if ($type !== Process::ERR) { + return; + } - $errorOutput->writeRaw($buffer); - }); + $errorOutput->writeRaw($buffer); + }); + } finally { + @unlink($fixedFilesFile); + } try { /** @var array{fixable: int, applied: int, changedFiles: list} $roundResult */ $roundResult = Json::decode($process->getOutput(), Json::FORCE_ARRAY); From b921d483432502ebfd0a16ce11101d7b3e07b35f Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:37:05 +0000 Subject: [PATCH 10/24] Normalize the union of returned objects in fixed return types The type of new Foo() says the object is exactly an instance of Foo, so the union of the types of new RedirectResponse() and new Response() kept both. A written type cannot say that, the fix of a missing return type declared RedirectResponse|Response, a union with a member that is a subtype of another. The returned types lose it before they are combined, the fix declares Response. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixer.php | 7 +++--- .../functions-php74.php.fixed | 25 +++++++++++++++++++ .../functions-php80.php.fixed | 25 +++++++++++++++++++ .../functions-php81.php.fixed | 25 +++++++++++++++++++ .../functions-php82.php.fixed | 25 +++++++++++++++++++ .../fix-missing-return-type/functions.php | 22 ++++++++++++++++ 6 files changed, 126 insertions(+), 3 deletions(-) diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index 12980014bac..b2e22628464 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -31,6 +31,7 @@ use PHPStan\Type\GeneralizePrecision; use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\TemplateType; +use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\IntegerType; use PHPStan\Type\IntersectionType; use PHPStan\Type\IterableType; @@ -145,7 +146,7 @@ public function getReturnInfo(MethodReturnStatementsNode|FunctionReturnStatement } $returnInfo = [ - 'values' => count($values) === 0 ? new NeverType(true) : TypeCombinator::union(...$values), + 'values' => count($values) === 0 ? new NeverType(true) : TemplateTypeHelper::removeFinalByKeywordOverrides(TypeCombinator::union(...$values)), 'void' => $void || !$node->getStatementResult()->isAlwaysTerminating(), 'returnsValue' => count($values) > 0, ]; @@ -184,8 +185,8 @@ public function getReturnInfo(MethodReturnStatementsNode|FunctionReturnStatement } return $this->createGeneratorReturnInfo( - TypeCombinator::union(...$keyTypes), - TypeCombinator::union(...$valueTypes), + TemplateTypeHelper::removeFinalByKeywordOverrides(TypeCombinator::union(...$keyTypes)), + TemplateTypeHelper::removeFinalByKeywordOverrides(TypeCombinator::union(...$valueTypes)), count($sendTypes) === 0 ? new MixedType(true) : TypeCombinator::intersect(...$sendTypes), $returnInfo, ); diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed index 128e5b88b84..805b691c887 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -308,3 +308,28 @@ function returnsNestedUnsealedShape(array $a): array { return $a; } + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b): Response +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +/** + * @return array{Response} + */ +function returnsNewResponsesInArray(bool $b): array +{ + return [$b ? new RedirectResponse() : new Response()]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed index bd71dc85145..d2fe3168056 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -308,3 +308,28 @@ function returnsNestedUnsealedShape(array $a): array { return $a; } + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b): Response +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +/** + * @return array{Response} + */ +function returnsNewResponsesInArray(bool $b): array +{ + return [$b ? new RedirectResponse() : new Response()]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed index d21322e4aac..4abecd3c28d 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -302,3 +302,28 @@ function returnsNestedUnsealedShape(array $a): array { return $a; } + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b): Response +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +/** + * @return array{Response} + */ +function returnsNewResponsesInArray(bool $b): array +{ + return [$b ? new RedirectResponse() : new Response()]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed index 9136a9d71f3..8655e70e033 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -299,3 +299,28 @@ function returnsNestedUnsealedShape(array $a): array { return $a; } + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b): Response +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +/** + * @return array{Response} + */ +function returnsNewResponsesInArray(bool $b): array +{ + return [$b ? new RedirectResponse() : new Response()]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php index 43e2f790a6e..432ba32e0f8 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -259,3 +259,25 @@ function returnsNestedUnsealedShape(array $a) { return $a; } + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b) +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +function returnsNewResponsesInArray(bool $b) +{ + return [$b ? new RedirectResponse() : new Response()]; +} From d7ab25f40f0889a9a9b6f8a12965a5867e839ede Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:37:35 +0000 Subject: [PATCH 11/24] Test that fixed return types are written with self under fixer.preferSelf A method returning an instance of its own class gets self as its native type and in its @return tag. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../Rules/data/fix-missing-return-type-php74.neon | 2 ++ .../Rules/data/fix-missing-return-type-php80.neon | 2 ++ .../Rules/data/fix-missing-return-type-php81.neon | 2 ++ .../Rules/data/fix-missing-return-type-php82.neon | 2 ++ .../methods-closed-project-php74.php.fixed | 14 ++++++++++++++ .../methods-closed-project-php80.php.fixed | 14 ++++++++++++++ .../methods-closed-project-php81.php.fixed | 14 ++++++++++++++ .../methods-closed-project-php82.php.fixed | 14 ++++++++++++++ .../methods-open-project-php74.php.fixed | 14 ++++++++++++++ .../methods-open-project-php80.php.fixed | 14 ++++++++++++++ .../methods-open-project-php81.php.fixed | 14 ++++++++++++++ .../methods-open-project-php82.php.fixed | 14 ++++++++++++++ .../Rules/data/fix-missing-return-type/methods.php | 13 +++++++++++++ 13 files changed, 133 insertions(+) diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon index 8f92412bf73..9b45e935338 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon @@ -2,3 +2,5 @@ parameters: phpVersion: 70400 featureToggles: fixMissingReturnTypes: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon index bd000042fa9..7667fd50889 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon @@ -2,3 +2,5 @@ parameters: phpVersion: 80000 featureToggles: fixMissingReturnTypes: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon index 37e0a8a815e..b8f56e641e6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon @@ -2,3 +2,5 @@ parameters: phpVersion: 80100 featureToggles: fixMissingReturnTypes: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon index 0111e7acb63..84236a942f8 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon @@ -2,3 +2,5 @@ parameters: phpVersion: 80200 featureToggles: fixMissingReturnTypes: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed index a18c946aafc..e7a0d3df280 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -30,6 +30,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed index 46e8bd9afbc..dfdebd374b6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -27,6 +27,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed index 010e75de37f..da5b1064019 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -24,6 +24,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed index 010e75de37f..da5b1064019 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -24,6 +24,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed index 7543b91423d..2e9a15c4781 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -30,6 +30,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed index d254186abb4..c31bf911044 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed @@ -27,6 +27,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed index 9552ded10d9..af52d4de919 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed @@ -24,6 +24,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed index 9552ded10d9..af52d4de919 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed @@ -24,6 +24,20 @@ final class FinalClass throw new \Exception(); } + public static function create(): self + { + return new self(); + } + + /** + * @param list $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php index 864213018ca..853f236b4eb 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php @@ -24,6 +24,19 @@ public function alwaysThrows() throw new \Exception(); } + public static function create() + { + return new self(); + } + + /** + * @param list $ints + */ + public static function createMany(array $ints) + { + return array_map(static fn (int $int) => new self(), $ints); + } + } class ParentClass From 1232c1f03f8fea740514b410ea41ddbf7dc4d110 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:42:57 +0000 Subject: [PATCH 12/24] Keep fixed return types within the return types of the overridden methods A method overriding or implementing another one inherits its contract: its return type has to be within the return type the parent method declares, natively or in PHPDoc, and PHP requires its native type to be within the parent's native type. The fix of a missing return type cannot widen a declared parent return type, so a method returning something else, like an array where the parent declares WP_REST_Response|WP_Error, is not fixed. A generalized type that leaves the parent's return type falls back to the returned type. The return types of the parent methods are resolved in each class, the methods of a trait and the methods fixed after the analysis in a closed project are kept within them in every class. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- ...ingImplementedMethodReturnTypehintRule.php | 5 +- .../MissingMethodReturnTypehintRule.php | 2 + src/Rules/MissingReturnTypeCollector.php | 4 +- src/Rules/MissingReturnTypeFixRule.php | 28 +++++- src/Rules/MissingReturnTypeFixer.php | 56 ++++++++++- .../methods-closed-project-php74.php.fixed | 92 +++++++++++++++++++ .../methods-closed-project-php80.php.fixed | 92 +++++++++++++++++++ .../methods-closed-project-php81.php.fixed | 92 +++++++++++++++++++ .../methods-closed-project-php82.php.fixed | 92 +++++++++++++++++++ .../methods-open-project-php74.php.fixed | 92 +++++++++++++++++++ .../methods-open-project-php80.php.fixed | 92 +++++++++++++++++++ .../methods-open-project-php81.php.fixed | 92 +++++++++++++++++++ .../methods-open-project-php82.php.fixed | 92 +++++++++++++++++++ .../data/fix-missing-return-type/methods.php | 92 +++++++++++++++++++ 14 files changed, 918 insertions(+), 5 deletions(-) diff --git a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php index f006b921b06..5a18d245a33 100644 --- a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php @@ -117,6 +117,7 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co } $returnInfo = $this->fixer->getReturnInfo($node); + [$parentReturnType, $parentNativeReturnType] = $this->fixer->findParentReturnTypes($classReflection, $methodReflection->getName()); // the methods overriding a method in an open project are not known, it is not fixed, // and a method of a trait is fixed with what it returns in all the classes using the trait $isDeferred = $errors !== [] && ($isInTrait || ($isOverridable && $isClosedProject)); @@ -128,7 +129,7 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co if (!$isInTrait && !$isOverridable) { $type = $this->fixer->combine([$returnInfo]); if ($type !== null) { - $fix = $this->fixer->createFix($classMethod, $type, $type, $classReflection); + $fix = $this->fixer->createFix($classMethod, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType); } } @@ -161,6 +162,8 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co 'overrides' => $overrides, 'overridable' => $isOverridable, 'returnInfo' => $this->fixer->serializeReturnInfo($returnInfo), + 'parentReturnType' => $parentReturnType !== null ? $this->fixer->serialize($parentReturnType) ?? false : null, + 'parentNativeReturnType' => $parentNativeReturnType !== null ? $this->fixer->serialize($parentNativeReturnType) ?? false : null, 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, 'fixedNatively' => $fixedNatively, 'errors' => $isDeferred ? $errors : [], diff --git a/src/Rules/Methods/MissingMethodReturnTypehintRule.php b/src/Rules/Methods/MissingMethodReturnTypehintRule.php index 7613fdb0834..a368d2767d2 100644 --- a/src/Rules/Methods/MissingMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingMethodReturnTypehintRule.php @@ -138,6 +138,8 @@ private function emitOverridingMethodWithoutBody(InClassMethodNode $node, Scope& 'overrides' => $overrides, 'overridable' => true, 'returnInfo' => null, + 'parentReturnType' => null, + 'parentNativeReturnType' => null, 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, 'fixedNatively' => false, 'errors' => [], diff --git a/src/Rules/MissingReturnTypeCollector.php b/src/Rules/MissingReturnTypeCollector.php index 849a37b6446..03db2e72905 100644 --- a/src/Rules/MissingReturnTypeCollector.php +++ b/src/Rules/MissingReturnTypeCollector.php @@ -18,6 +18,8 @@ * - overrides: keys of the methods with a body the method overrides * - overridable: whether methods in other classes can override the method * - returnInfo: what the function returns, see MissingReturnTypeFixer, null when it is not known or the method has no body + * - parentReturnType, parentNativeReturnType: the return types of the methods it overrides, see MissingReturnTypeFixer::findParentReturnTypes(), + * false when they cannot be passed in collected data * - nativeReturnType: the declared native return type * - fixedNatively: whether the error of the method declares its native return type with a fix of its own * - errors: the errors of a missing return type MissingReturnTypeFixRule reports with the fix @@ -26,7 +28,7 @@ * * Not registered as a collector, the data is emitted by the rules for missing return types. * - * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> + * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> */ final class MissingReturnTypeCollector implements Collector { diff --git a/src/Rules/MissingReturnTypeFixRule.php b/src/Rules/MissingReturnTypeFixRule.php index 98a14635868..eeae46d2aa6 100644 --- a/src/Rules/MissingReturnTypeFixRule.php +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -18,7 +18,9 @@ use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; use PHPStan\Type\NeverType; use PHPStan\Type\Type; +use PHPStan\Type\TypeCombinator; use function array_key_exists; +use function count; /** * Reports the missing return types of methods that can be overridden in a closed project @@ -30,7 +32,7 @@ * so that \$this is static. Its return type covers what it returns in all of them, they share one fix. * * @phpstan-import-type ReturnInfo from MissingReturnTypeFixer - * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} + * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} * @implements Rule */ #[RegisteredRule(level: 6)] @@ -159,12 +161,27 @@ private function createFix(string $key): ?callable $returnInfos = []; $nativeReturnInfos = []; + $parentReturnTypes = []; + $parentNativeReturnTypes = []; foreach ($traitMethod !== null ? $this->traitMethodRecords[$traitMethod] : [$key] as $contextKey) { $contextRecord = $this->records[$contextKey]; if ($contextRecord['errors'] === []) { return null; } + // the fixed return type has to be within the return types of the methods it overrides in every class + if ($contextRecord['parentReturnType'] === false || $contextRecord['parentNativeReturnType'] === false) { + return null; + } + $parentReturnType = $this->resolve($contextRecord['parentReturnType'], $contextRecord['class']); + if ($parentReturnType !== null) { + $parentReturnTypes[] = $parentReturnType; + } + $parentNativeReturnType = $this->resolve($contextRecord['parentNativeReturnType'], $contextRecord['class']); + if ($parentNativeReturnType !== null) { + $parentNativeReturnTypes[] = $parentNativeReturnType; + } + $returnInfo = $this->getReturnInfo($contextKey); if ($returnInfo === null) { return null; @@ -235,7 +252,14 @@ private function createFix(string $key): ?callable ? $this->reflectionProvider->getClass($record['class']) : null; - return $this->fixer->createFix($functionNode, $phpDocType, $nativeSourceType, $classReflection); + return $this->fixer->createFix( + $functionNode, + $phpDocType, + $nativeSourceType, + $classReflection, + count($parentReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentReturnTypes), + count($parentNativeReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentNativeReturnTypes), + ); } private function willDeclareNativeReturnType(string $key): bool diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index b2e22628464..56226af9718 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -23,6 +23,7 @@ use PHPStan\PhpDocParser\Printer\Printer; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\ReflectionProvider; +use PHPStan\Rules\Methods\ParentMethodHelper; use PHPStan\Type\Accessory\AccessoryArrayListType; use PHPStan\Type\Accessory\NonEmptyArrayType; use PHPStan\Type\ArrayType; @@ -43,6 +44,7 @@ use PHPStan\Type\ParserNodeTypeToPHPStanType; use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; +use PHPStan\Type\TypehintHelper; use PHPStan\Type\TypeTraverser; use PHPStan\Type\UnionType; use PHPStan\Type\VoidType; @@ -80,6 +82,7 @@ public function __construct( private PhpVersion $phpVersion, private MissingTypehintCheck $missingTypehintCheck, private Printer $printer, + private ParentMethodHelper $parentMethodHelper, ) { } @@ -248,6 +251,42 @@ public function combine(array $returnInfos): ?Type return null; } + /** + * The return types the methods the method overrides or implements declare, resolved in the class, + * the declared one and the native one. The fixed return type has to be within both, it cannot widen them. + * Null when there is no such method, or it declares no return type, or void, which allows anything. + * + * @return array{Type|null, Type|null} + */ + public function findParentReturnTypes(ClassReflection $classReflection, string $methodName): array + { + $returnTypes = []; + $nativeReturnTypes = []; + foreach ($this->parentMethodHelper->collectParentMethods($methodName, $classReflection) as [$parentMethod]) { + $variants = $parentMethod->getVariants(); + if (count($variants) !== 1) { + continue; + } + + $nativeReturnType = $variants[0]->getNativeReturnType(); + if (!$nativeReturnType instanceof MixedType || $nativeReturnType->isExplicitMixed()) { + $nativeReturnTypes[] = $nativeReturnType; + } + + $returnType = TypehintHelper::decideType($nativeReturnType, TemplateTypeHelper::resolveToBounds($variants[0]->getPhpDocReturnType())); + if (($returnType instanceof MixedType && !$returnType->isExplicitMixed()) || $returnType->isVoid()->yes()) { + continue; + } + + $returnTypes[] = $returnType; + } + + return [ + count($returnTypes) === 0 ? null : TypeCombinator::intersect(...$returnTypes), + count($nativeReturnTypes) === 0 ? null : TypeCombinator::intersect(...$nativeReturnTypes), + ]; + } + /** * The fix that declares the return type of the function. The native type is declared when the function * does not have one, it is $nativeSourceType widened to what PHP allows, or to the closest common @@ -258,6 +297,9 @@ public function combine(array $returnInfos): ?Type * or signature only PHPDoc describes, and with the native type of the newest PHP version when the PHP version * does not allow it, like static or a union type. * + * The return type of a method has to be within the return types of the methods it overrides, + * see findParentReturnTypes(), when it is not, the method breaks their contract and is not fixed. + * * @template TNode of ClassMethod|Function_ * @param TNode $node * @return (callable(TNode): TNode)|null @@ -267,9 +309,17 @@ public function createFix( Type $phpDocType, Type $nativeSourceType, ?ClassReflection $classReflection, + ?Type $parentReturnType = null, + ?Type $parentNativeReturnType = null, ): ?callable { - $phpDocType = $this->generalize($phpDocType); + $generalizedPhpDocType = $this->generalize($phpDocType); + if ($parentReturnType === null || $parentReturnType->isSuperTypeOf($generalizedPhpDocType)->yes()) { + $phpDocType = $generalizedPhpDocType; + } elseif (!$parentReturnType->isSuperTypeOf($phpDocType)->yes()) { + return null; + } + if (!$this->canWrite($phpDocType)) { return null; } @@ -289,6 +339,10 @@ public function createFix( return null; } + if ($parentNativeReturnType !== null && !$parentNativeReturnType->isSuperTypeOf($nativeType)->yes()) { + return null; + } + $phpDocTypeNode = null; $returnedPhpDocType = $this->getPhpDocType($phpDocType, $classReflection); if (!$nativeType->equals($returnedPhpDocType)) { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed index e7a0d3df280..682e96dfc35 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -121,6 +121,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed index dfdebd374b6..1518d530236 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -112,6 +112,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed index da5b1064019..a13abea2ae4 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -109,6 +109,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed index da5b1064019..a13abea2ae4 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -109,6 +109,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed index 2e9a15c4781..a92304b27bb 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -109,6 +109,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed index c31bf911044..c023fcadf61 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed @@ -106,6 +106,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed index af52d4de919..fd1c9043111 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed @@ -103,6 +103,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed index af52d4de919..fd1c9043111 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed @@ -103,6 +103,98 @@ class ChildClass extends ParentClass } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php index 853f236b4eb..16a6906ca38 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php @@ -102,6 +102,98 @@ public function overriddenByPhpDocOnly() } +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + /** + * @return array|Dog + */ + public function getItem() + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return [new Dog()]; + } + +} + class IterableParent { From e4ccbe27b90e006d7c92aad02b5dc61b2dbfd396 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 11:44:54 +0000 Subject: [PATCH 13/24] Update the @return tag left behind by a fixed native return type When the fix of a missing return type declares a native type that says everything, it added no @return tag, but it kept the one the method had, like @return array|Dog of a method now declaring Dog. The tag contradicted the new type. It gets the new type, or it is removed when it has no description and only repeats the native type. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixer.php | 47 ++++++++++++------- .../methods-closed-project-php74.php.fixed | 18 +++++-- .../methods-closed-project-php80.php.fixed | 18 +++++-- .../methods-closed-project-php81.php.fixed | 18 +++++-- .../methods-closed-project-php82.php.fixed | 18 +++++-- .../methods-open-project-php74.php.fixed | 18 +++++-- .../methods-open-project-php80.php.fixed | 18 +++++-- .../methods-open-project-php81.php.fixed | 18 +++++-- .../methods-open-project-php82.php.fixed | 18 +++++-- .../data/fix-missing-return-type/methods.php | 15 ++++++ 10 files changed, 166 insertions(+), 40 deletions(-) diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index 56226af9718..92c2d0cce9a 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -343,39 +343,54 @@ public function createFix( return null; } - $phpDocTypeNode = null; $returnedPhpDocType = $this->getPhpDocType($phpDocType, $classReflection); - if (!$nativeType->equals($returnedPhpDocType)) { - $phpDocTypeNode = $returnedPhpDocType->toPhpDocNode(); - } + $phpDocTypeNode = $returnedPhpDocType->toPhpDocNode(); + // the native type says everything, a new @return tag would only repeat it + $addsTag = !$nativeType->equals($returnedPhpDocType); $phpDocEditor = $this->phpDocEditor; - return static function (ClassMethod|Function_ $node) use ($nativeTypeNode, $phpDocTypeNode, $phpDocEditor): ClassMethod|Function_ { + return static function (ClassMethod|Function_ $node) use ($nativeTypeNode, $phpDocTypeNode, $addsTag, $phpDocEditor): ClassMethod|Function_ { if ($nativeTypeNode !== null) { $node->returnType = $nativeTypeNode; } - if ($phpDocTypeNode === null) { + if (!$addsTag && $node->getDocComment() === null) { return $node; } - $phpDocEditor->edit($node, static function (PhpDocAstNode $phpDocNode) use ($phpDocTypeNode): PhpDocAstNode { - if ($phpDocNode instanceof ReturnTagValueNode) { - $phpDocNode->type = $phpDocTypeNode; + $phpDocEditor->edit($node, static function (PhpDocAstNode $phpDocNode) use ($phpDocTypeNode, $addsTag): PhpDocAstNode { + if (!$phpDocNode instanceof PhpDocNode) { return $phpDocNode; } - if (!$phpDocNode instanceof PhpDocNode || count($phpDocNode->getReturnTagValues()) > 0) { - return $phpDocNode; + // a return tag left behind would contradict the new return type, like @return array|Dog of a method returning Dog, + // it gets the new type, or it is removed when it only repeats the native type + $hasReturnTag = false; + $children = []; + foreach ($phpDocNode->children as $child) { + if ($child instanceof PhpDocTagNode && $child->value instanceof ReturnTagValueNode) { + $hasReturnTag = true; + if (!$addsTag && $child->value->description === '') { + continue; + } + + $child->value->type = $phpDocTypeNode; + } + + $children[] = $child; } - // the ignore tags at the end of the PHPDoc stay last - $position = count($phpDocNode->children); - while ($position > 0 && $phpDocNode->children[$position - 1] instanceof PhpDocTagNode && str_starts_with($phpDocNode->children[$position - 1]->name, '@phpstan-ignore')) { - $position--; + if (!$hasReturnTag && $addsTag) { + // the ignore tags at the end of the PHPDoc stay last + $position = count($children); + while ($position > 0 && $children[$position - 1] instanceof PhpDocTagNode && str_starts_with($children[$position - 1]->name, '@phpstan-ignore')) { + $position--; + } + array_splice($children, $position, 0, [new PhpDocTagNode('@return', new ReturnTagValueNode($phpDocTypeNode, ''))]); } - array_splice($phpDocNode->children, $position, 0, [new PhpDocTagNode('@return', new ReturnTagValueNode($phpDocTypeNode, ''))]); + + $phpDocNode->children = $children; return $phpDocNode; }); diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed index 682e96dfc35..39ecb357d45 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -154,9 +154,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -213,6 +210,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed index 1518d530236..80cc5f5937c 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -145,9 +145,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -204,6 +201,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed index a13abea2ae4..2897e856a99 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -142,9 +142,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -201,6 +198,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed index a13abea2ae4..2897e856a99 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -142,9 +142,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -201,6 +198,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed index a92304b27bb..1fc64c97f19 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -142,9 +142,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -201,6 +198,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed index c023fcadf61..cfebc2a7d0d 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed @@ -139,9 +139,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -198,6 +195,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed index fd1c9043111..61ef700f3b1 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed @@ -136,9 +136,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -195,6 +192,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed index fd1c9043111..61ef700f3b1 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed @@ -136,9 +136,6 @@ final class ChildViolatingParent extends DeclaringParent final class ChildWithinParent extends DeclaringParent { - /** - * @return array|Dog - */ public function getItem(): Dog { return new Dog(); @@ -195,6 +192,21 @@ final class ReturnsDogs implements ReturnsAnimals } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php index 16a6906ca38..85cae8e1eb6 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php @@ -194,6 +194,21 @@ public function animals(): array } +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return array|Dog The dog. + */ + public function getItem() + { + return new Dog(); + } + +} + class IterableParent { From 89cb7093500278e016244ad635b8ccb3cbf19b7a Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 12:02:31 +0000 Subject: [PATCH 14/24] Do not fix the return type of a function returning an array of mixed values The check for mixed in the written return type did not check the item type of array and iterable itself, only the types in it, so array was written as the native array type. Mixed is never written, not even as the value type of an array. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixer.php | 24 ++++++++++++------- .../functions-php74.php.fixed | 24 +++++++++++++++++++ .../functions-php80.php.fixed | 24 +++++++++++++++++++ .../functions-php81.php.fixed | 24 +++++++++++++++++++ .../functions-php82.php.fixed | 24 +++++++++++++++++++ .../fix-missing-return-type/functions.php | 24 +++++++++++++++++++ 6 files changed, 135 insertions(+), 9 deletions(-) diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index 92c2d0cce9a..d8b6409ffbd 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -469,20 +469,29 @@ private static function canStayArrayShape(ConstantArrayType $type): bool */ private function canWrite(Type $type): bool { - $canWrite = true; - TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$canWrite): Type { + return $this->isWithoutMixed($type) + && $this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($type) === [] + && $this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($type) === [] + && $this->missingTypehintCheck->getCallablesWithMissingSignature($type) === []; + } + + private function isWithoutMixed(Type $type): bool + { + $isWithoutMixed = true; + TypeTraverser::map($type, function (Type $type, callable $traverse) use (&$isWithoutMixed): Type { if ($type instanceof TemplateType) { return $type; } if ($type instanceof ErrorType || $type instanceof MixedType) { - $canWrite = false; + $isWithoutMixed = false; return $type; } - // array has a mixed key type, PHPDoc cannot say more about the keys than array-key + // array has a mixed key type, PHPDoc cannot say more about the keys than array-key, + // the item type itself is checked, $traverse would check only the types in it if (($type instanceof ArrayType || $type instanceof IterableType) && $type->getKeyType() instanceof MixedType) { - $traverse($type->getItemType()); + $isWithoutMixed = $isWithoutMixed && $this->isWithoutMixed($type->getItemType()); return $type; } @@ -499,10 +508,7 @@ private function canWrite(Type $type): bool return $traverse($type); }); - return $canWrite - && $this->missingTypehintCheck->getIterableTypesWithMissingValueTypehint($type) === [] - && $this->missingTypehintCheck->getNonGenericObjectTypesWithGenericClass($type) === [] - && $this->missingTypehintCheck->getCallablesWithMissingSignature($type) === []; + return $isWithoutMixed; } /** diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed index 805b691c887..58f41a3326c 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -333,3 +333,27 @@ function returnsNewResponsesInArray(bool $b): array { return [$b ? new RedirectResponse() : new Response()]; } + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed index d2fe3168056..db2d5c629cf 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -333,3 +333,27 @@ function returnsNewResponsesInArray(bool $b): array { return [$b ? new RedirectResponse() : new Response()]; } + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed index 4abecd3c28d..ee4576597b0 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -327,3 +327,27 @@ function returnsNewResponsesInArray(bool $b): array { return [$b ? new RedirectResponse() : new Response()]; } + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed index 8655e70e033..a8adaef90df 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -324,3 +324,27 @@ function returnsNewResponsesInArray(bool $b): array { return [$b ? new RedirectResponse() : new Response()]; } + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php index 432ba32e0f8..2dfa7b5e9ce 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -281,3 +281,27 @@ function returnsNewResponsesInArray(bool $b) { return [$b ? new RedirectResponse() : new Response()]; } + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} From cdf2c827df9f1c9a96eeaefb66dcf13d3365e51d Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 12:37:59 +0000 Subject: [PATCH 15/24] Make the fixes of MissingReturnTypeFixRule without parsing the files again The collected data carries where the method node is and its declared native return type, so the rule creates the fix without finding the node in a parse of its file. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../MissingFunctionReturnTypehintRule.php | 2 +- ...ingImplementedMethodReturnTypehintRule.php | 5 +- .../MissingMethodReturnTypehintRule.php | 3 +- src/Rules/MissingReturnTypeCollector.php | 6 +-- src/Rules/MissingReturnTypeFixRule.php | 49 +++++++------------ src/Rules/MissingReturnTypeFixer.php | 12 ++--- .../Rules/MissingReturnTypeFixTestCase.php | 1 - 7 files changed, 31 insertions(+), 47 deletions(-) diff --git a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php index 0b4c2dd3497..de49bbccde2 100644 --- a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php +++ b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php @@ -102,7 +102,7 @@ private function createReturnTypeErrors(FunctionReturnStatementsNode $node, arra if ($this->fixer->isEnabled()) { $type = $this->fixer->combine([$this->fixer->getReturnInfo($node)]); if ($type !== null) { - $fix = $this->fixer->createFix($function, $type, $type, null); + $fix = $this->fixer->createFix($function->returnType !== null ? $node->getFunctionReflection()->getNativeReturnType() : null, $type, $type, null); } } diff --git a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php index 5a18d245a33..cd09a81478c 100644 --- a/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php @@ -129,7 +129,7 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co if (!$isInTrait && !$isOverridable) { $type = $this->fixer->combine([$returnInfo]); if ($type !== null) { - $fix = $this->fixer->createFix($classMethod, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType); + $fix = $this->fixer->createFix($classMethod->returnType !== null ? $methodReflection->getNativeReturnType() : null, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType); } } @@ -164,13 +164,14 @@ private function processFixableErrors(MethodReturnStatementsNode $node, Scope&Co 'returnInfo' => $this->fixer->serializeReturnInfo($returnInfo), 'parentReturnType' => $parentReturnType !== null ? $this->fixer->serialize($parentReturnType) ?? false : null, 'parentNativeReturnType' => $parentNativeReturnType !== null ? $this->fixer->serialize($parentNativeReturnType) ?? false : null, - 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, + 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) ?? false : null, 'fixedNatively' => $fixedNatively, 'errors' => $isDeferred ? $errors : [], 'file' => $file, 'fileDescription' => $scope->getFileDescription(), 'line' => $node->getStartLine(), 'startPos' => $classMethod->getStartFilePos(), + 'endPos' => $classMethod->getEndFilePos(), ]); } diff --git a/src/Rules/Methods/MissingMethodReturnTypehintRule.php b/src/Rules/Methods/MissingMethodReturnTypehintRule.php index a368d2767d2..020de9efa5e 100644 --- a/src/Rules/Methods/MissingMethodReturnTypehintRule.php +++ b/src/Rules/Methods/MissingMethodReturnTypehintRule.php @@ -140,13 +140,14 @@ private function emitOverridingMethodWithoutBody(InClassMethodNode $node, Scope& 'returnInfo' => null, 'parentReturnType' => null, 'parentNativeReturnType' => null, - 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) : null, + 'nativeReturnType' => $classMethod->returnType !== null ? $this->fixer->serialize($methodReflection->getNativeReturnType()) ?? false : null, 'fixedNatively' => false, 'errors' => [], 'file' => $scope->getFile(), 'fileDescription' => $scope->getFileDescription(), 'line' => $node->getStartLine(), 'startPos' => $classMethod->getStartFilePos(), + 'endPos' => $classMethod->getEndFilePos(), ]); } diff --git a/src/Rules/MissingReturnTypeCollector.php b/src/Rules/MissingReturnTypeCollector.php index 03db2e72905..db8aade6112 100644 --- a/src/Rules/MissingReturnTypeCollector.php +++ b/src/Rules/MissingReturnTypeCollector.php @@ -20,15 +20,15 @@ * - returnInfo: what the function returns, see MissingReturnTypeFixer, null when it is not known or the method has no body * - parentReturnType, parentNativeReturnType: the return types of the methods it overrides, see MissingReturnTypeFixer::findParentReturnTypes(), * false when they cannot be passed in collected data - * - nativeReturnType: the declared native return type + * - nativeReturnType: the declared native return type, false when it cannot be passed in collected data * - fixedNatively: whether the error of the method declares its native return type with a fix of its own * - errors: the errors of a missing return type MissingReturnTypeFixRule reports with the fix - * - file, startPos: where the function node is, to find it in the parsed file + * - file, startPos, endPos: where the function node is, the fix finds it there * - fileDescription: the file the errors are reported in, with the class using the trait the method comes from * * Not registered as a collector, the data is emitted by the rules for missing return types. * - * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int}> + * @implements Collector, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|false|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int, endPos: int}> */ final class MissingReturnTypeCollector implements Collector { diff --git a/src/Rules/MissingReturnTypeFixRule.php b/src/Rules/MissingReturnTypeFixRule.php index eeae46d2aa6..3a8786b0cef 100644 --- a/src/Rules/MissingReturnTypeFixRule.php +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -5,14 +5,10 @@ use PhpParser\Node; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Function_; -use PhpParser\NodeFinder; use PHPStan\Analyser\NameScope; use PHPStan\Analyser\Scope; -use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Node\CollectedDataNode; -use PHPStan\Parser\Parser; -use PHPStan\Parser\ParserErrorsException; use PHPStan\PhpDoc\TypeStringResolver; use PHPStan\Reflection\ReflectionProvider; use PHPStan\Rules\TooWideTypehints\OverridableMemberHelper; @@ -32,7 +28,7 @@ * so that \$this is static. Its return type covers what it returns in all of them, they share one fix. * * @phpstan-import-type ReturnInfo from MissingReturnTypeFixer - * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int} + * @phpstan-type Record array{key: string, traitMethod: string|null, class: string|null, overrides: list, overridable: bool, returnInfo: array{values: string, void: bool, returnsValue: bool}|null, parentReturnType: string|false|null, parentNativeReturnType: string|false|null, nativeReturnType: string|false|null, fixedNatively: bool, errors: list, file: string, fileDescription: string, line: int, startPos: int, endPos: int} * @implements Rule */ #[RegisteredRule(level: 6)] @@ -61,8 +57,6 @@ public function __construct( private OverridableMemberHelper $overridableMemberHelper, private TypeStringResolver $typeStringResolver, private ReflectionProvider $reflectionProvider, - #[AutowiredParameter(ref: '@defaultAnalysisParser')] - private Parser $parser, ) { } @@ -116,10 +110,7 @@ public function processNode(Node $node, Scope $scope): array $builder->tip($tip); } if ($fix !== null) { - $functionNode = $this->findFunctionNode($record); - if ($functionNode !== null) { - $builder->fixNode($functionNode, $fix, $record['file']); - } + $builder->fixNode(self::createFunctionNode($record), $fix, $record['file']); } $errors[] = $builder->build(); @@ -153,6 +144,10 @@ private function getFix(string $key): ?callable private function createFix(string $key): ?callable { $record = $this->records[$key]; + if ($record['nativeReturnType'] === false) { + return null; + } + $traitMethod = $record['traitMethod']; // the classes using a trait might not be analysed if ($traitMethod !== null && $this->isOnlyFilesAnalysis) { @@ -170,7 +165,7 @@ private function createFix(string $key): ?callable } // the fixed return type has to be within the return types of the methods it overrides in every class - if ($contextRecord['parentReturnType'] === false || $contextRecord['parentNativeReturnType'] === false) { + if ($contextRecord['parentReturnType'] === false || $contextRecord['parentNativeReturnType'] === false || $contextRecord['nativeReturnType'] === false) { return null; } $parentReturnType = $this->resolve($contextRecord['parentReturnType'], $contextRecord['class']); @@ -210,6 +205,10 @@ private function createFix(string $key): ?callable return null; } + if ($overridingRecord['nativeReturnType'] === false) { + return null; + } + $overridingReturnInfo = $this->getReturnInfo($overridingKey); $overridingNativeType = $this->resolve($overridingRecord['nativeReturnType'], $overridingRecord['class']); $overridingNativeReturnInfo = $overridingNativeType !== null ? $this->createNativeReturnInfo($overridingNativeType) : null; @@ -243,17 +242,12 @@ private function createFix(string $key): ?callable return null; } - $functionNode = $this->findFunctionNode($record); - if ($functionNode === null) { - return null; - } - $classReflection = $record['class'] !== null && $this->reflectionProvider->hasClass($record['class']) ? $this->reflectionProvider->getClass($record['class']) : null; return $this->fixer->createFix( - $functionNode, + $this->resolve($record['nativeReturnType'], $record['class']), $phpDocType, $nativeSourceType, $classReflection, @@ -320,23 +314,14 @@ private function resolve(?string $type, ?string $className): ?Type } /** + * The node the fix is made on, found in the parsed file by its position, see ReplacingNodeVisitor. + * The records are made from the analysed nodes, so the file is not parsed again here. + * * @param Record $record */ - private function findFunctionNode(array $record): ClassMethod|Function_|null + private static function createFunctionNode(array $record): ClassMethod { - try { - $stmts = $this->parser->parseFile($record['file']); - } catch (ParserErrorsException) { - return null; - } - - $startPos = $record['startPos']; - $functionNode = (new NodeFinder())->findFirst($stmts, static fn (Node $node): bool => ($node instanceof ClassMethod || $node instanceof Function_) && $node->getStartFilePos() === $startPos); - if (!$functionNode instanceof ClassMethod && !$functionNode instanceof Function_) { - return null; - } - - return $functionNode; + return new ClassMethod('fixed', attributes: ['startFilePos' => $record['startPos'], 'endFilePos' => $record['endPos']]); } } diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index d8b6409ffbd..e232331a598 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -300,12 +300,11 @@ public function findParentReturnTypes(ClassReflection $classReflection, string $ * The return type of a method has to be within the return types of the methods it overrides, * see findParentReturnTypes(), when it is not, the method breaks their contract and is not fixed. * - * @template TNode of ClassMethod|Function_ - * @param TNode $node - * @return (callable(TNode): TNode)|null + * @param Type|null $declaredNativeType the native return type the function declares + * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null */ public function createFix( - ClassMethod|Function_ $node, + ?Type $declaredNativeType, Type $phpDocType, Type $nativeSourceType, ?ClassReflection $classReflection, @@ -325,14 +324,13 @@ public function createFix( } $nativeTypeNode = null; - if ($node->returnType === null) { + $nativeType = $declaredNativeType; + if ($nativeType === null) { $nativeTypeNode = $this->createNativeTypeNode($nativeSourceType); if ($nativeTypeNode === null) { return null; } $nativeType = ParserNodeTypeToPHPStanType::resolve($nativeTypeNode, $classReflection); - } else { - $nativeType = ParserNodeTypeToPHPStanType::resolve($node->returnType, $classReflection); } if ($nativeType->isSuperTypeOf($phpDocType)->no()) { diff --git a/tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php b/tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php index e48c6b5efc7..e022e73192c 100644 --- a/tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php +++ b/tests/PHPStan/Rules/MissingReturnTypeFixTestCase.php @@ -44,7 +44,6 @@ protected function getRule(): Rule $overridableMemberHelper, self::getContainer()->getByType(TypeStringResolver::class), self::createReflectionProvider(), - self::getContainer()->getService('defaultAnalysisParser'), ), ]; if ($this->reportMissingParameterTypes) { From 4292ca01660a8d2806af04da41788788fc56d8ba Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 13:56:51 +0000 Subject: [PATCH 16/24] Keep fixed return types invariant across the class hierarchy before PHP 7.4 Without return type covariance, a method overriding one with a native return type declares the same native type and the narrower one in @return, and an overridden method is fixed only when the methods overriding it already declare the same native type. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- src/Rules/MissingReturnTypeFixRule.php | 12 +- src/Rules/MissingReturnTypeFixer.php | 23 +- .../Rules/MissingReturnTypeFixPhp73Test.php | 13 + .../data/fix-missing-return-type-php73.neon | 6 + .../functions-php73.php.fixed | 359 ++++++++++++++++++ .../functions-with-ignores-php73.php.fixed | 43 +++ .../methods-closed-project-php73.php.fixed | 352 +++++++++++++++++ .../methods-closed-project-php74.php.fixed | 97 +++++ .../methods-closed-project-php80.php.fixed | 97 +++++ .../methods-closed-project-php81.php.fixed | 97 +++++ .../methods-closed-project-php82.php.fixed | 97 +++++ .../methods-open-project-php73.php.fixed | 343 +++++++++++++++++ .../methods-open-project-php74.php.fixed | 97 +++++ .../methods-open-project-php80.php.fixed | 97 +++++ .../methods-open-project-php81.php.fixed | 97 +++++ .../methods-open-project-php82.php.fixed | 97 +++++ .../data/fix-missing-return-type/methods.php | 97 +++++ .../traits-closed-project-php73.php.fixed | 238 ++++++++++++ .../traits-open-project-php73.php.fixed | 238 ++++++++++++ 19 files changed, 2495 insertions(+), 5 deletions(-) create mode 100644 tests/PHPStan/Rules/MissingReturnTypeFixPhp73Test.php create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type-php73.neon create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-php73.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php73.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php73.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php73.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php73.php.fixed create mode 100644 tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php73.php.fixed diff --git a/src/Rules/MissingReturnTypeFixRule.php b/src/Rules/MissingReturnTypeFixRule.php index 3a8786b0cef..75542c8a81c 100644 --- a/src/Rules/MissingReturnTypeFixRule.php +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -158,6 +158,7 @@ private function createFix(string $key): ?callable $nativeReturnInfos = []; $parentReturnTypes = []; $parentNativeReturnTypes = []; + $overridingNativeReturnTypes = []; foreach ($traitMethod !== null ? $this->traitMethodRecords[$traitMethod] : [$key] as $contextKey) { $contextRecord = $this->records[$contextKey]; if ($contextRecord['errors'] === []) { @@ -218,13 +219,15 @@ private function createFix(string $key): ?callable } $returnInfos[] = $overridingReturnInfo; - if ($overridingNativeReturnInfo !== null) { - $nativeReturnInfos[] = $overridingNativeReturnInfo; + if ($overridingNativeType !== null) { + $nativeReturnInfos[] = $this->createNativeReturnInfo($overridingNativeType); + $overridingNativeReturnTypes[] = $overridingNativeType; continue; } - // PHP requires a native return type of the overriding method when the overridden method declares one - if ($contextRecord['nativeReturnType'] === null && !$this->willDeclareNativeReturnType($overridingKey)) { + // PHP requires a native return type of the overriding method when the overridden method declares one, + // before PHP 7.4 the same one, which the fix of the overriding method does not know about + if ($contextRecord['nativeReturnType'] === null && (!$this->fixer->supportsReturnCovariance() || !$this->willDeclareNativeReturnType($overridingKey))) { return null; } @@ -253,6 +256,7 @@ private function createFix(string $key): ?callable $classReflection, count($parentReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentReturnTypes), count($parentNativeReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentNativeReturnTypes), + $overridingNativeReturnTypes, ); } diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php index e232331a598..1f01f9976dd 100644 --- a/src/Rules/MissingReturnTypeFixer.php +++ b/src/Rules/MissingReturnTypeFixer.php @@ -131,6 +131,11 @@ public function isEnabled(): bool return $this->enabled; } + public function supportsReturnCovariance(): bool + { + return $this->phpVersion->supportsReturnCovariance(); + } + /** * @return ReturnInfo */ @@ -300,7 +305,11 @@ public function findParentReturnTypes(ClassReflection $classReflection, string $ * The return type of a method has to be within the return types of the methods it overrides, * see findParentReturnTypes(), when it is not, the method breaks their contract and is not fixed. * + * Before PHP 7.4 return types are invariant: an overriding method declares the native type of the method + * it overrides, and a method is fixed only when the native types of the methods overriding it are the same. + * * @param Type|null $declaredNativeType the native return type the function declares + * @param list $overridingNativeReturnTypes the native return types of the methods overriding the method * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null */ public function createFix( @@ -310,6 +319,7 @@ public function createFix( ?ClassReflection $classReflection, ?Type $parentReturnType = null, ?Type $parentNativeReturnType = null, + array $overridingNativeReturnTypes = [], ): ?callable { $generalizedPhpDocType = $this->generalize($phpDocType); @@ -323,10 +333,12 @@ public function createFix( return null; } + $supportsReturnCovariance = $this->phpVersion->supportsReturnCovariance(); $nativeTypeNode = null; $nativeType = $declaredNativeType; if ($nativeType === null) { - $nativeTypeNode = $this->createNativeTypeNode($nativeSourceType); + // without return type covariance, the overriding method declares the same native type, the narrower type is in PHPDoc + $nativeTypeNode = $this->createNativeTypeNode(!$supportsReturnCovariance && $parentNativeReturnType !== null ? $parentNativeReturnType : $nativeSourceType); if ($nativeTypeNode === null) { return null; } @@ -341,6 +353,15 @@ public function createFix( return null; } + // without return type covariance, the overriding methods have to declare the same native type + if (!$supportsReturnCovariance) { + foreach ($overridingNativeReturnTypes as $overridingNativeReturnType) { + if (!$overridingNativeReturnType->equals($nativeType)) { + return null; + } + } + } + $returnedPhpDocType = $this->getPhpDocType($phpDocType, $classReflection); $phpDocTypeNode = $returnedPhpDocType->toPhpDocNode(); // the native type says everything, a new @return tag would only repeat it diff --git a/tests/PHPStan/Rules/MissingReturnTypeFixPhp73Test.php b/tests/PHPStan/Rules/MissingReturnTypeFixPhp73Test.php new file mode 100644 index 00000000000..7707b5a2ada --- /dev/null +++ b/tests/PHPStan/Rules/MissingReturnTypeFixPhp73Test.php @@ -0,0 +1,13 @@ + 1]; +} + +/** + * @return \Generator + */ +function generator(): \Generator +{ + yield 'a' => 1; + return true; +} + +/** + * @return never + */ +function alwaysThrows(): void +{ + throw new \Exception(); +} + +function maybeReturnsInt(bool $b) +{ + if ($b) { + return 1; + } +} + +function bareReturn(bool $b) +{ + if ($b) { + return; + } + + return 1; +} + +/** + * @return \ArrayIterator|\ArrayObject + */ +function returnsObjects(bool $b): \ArrayAccess +{ + if ($b) { + return new \ArrayObject([]); + } + + return new \ArrayIterator([]); +} + +/** + * @return false + */ +function returnsFalse(): bool +{ + return false; +} + +/** + * @return \Generator + */ +function receivesFloats(): \Generator +{ + $x = yield 'a'; + return true; +} + +/** + * @return \Generator + */ +function receivesNumbers(): \Generator +{ + $x = yield 'b'; +} + +/** + * @return \Generator + */ +function delegates(bool $b): \Generator +{ + yield from [1 => 'c']; + yield from receivesFloats(); + yield from receivesNumbers(); + yield from $b ? receivesFloats() : ['d']; +} + +/** + * @return \Generator + */ +function delegatesToIterator(): \Generator +{ + yield from new \ArrayIterator(['e' => 'f']); +} + +/** + * @param mixed $m + */ +function returnsMixed($m) +{ + return $m; +} + +/** + * @param array $a + */ +function returnsArrayOfMixed(array $a) +{ + return ['a' => $a]; +} + +/** + * @param mixed $m + */ +function yieldsMixed($m) +{ + yield $m; +} + +/** + * @param array $a + * @param iterable $i + * @return array|iterable + */ +function returnsArrayOfStrings(array $a, iterable $i, bool $b): iterable +{ + return $b ? $a : $i; +} + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +function returnsVoid() +{ + return declaredVoid(); +} + +abstract class AbstractAnimal +{ +} + +interface Named +{ +} + +interface Aged +{ +} + +function returnsAnonymousSubclass(): AbstractAnimal +{ + return new class extends AbstractAnimal { + }; +} + +function returnsAnonymousImplementation(): Named +{ + return new class implements Named { + }; +} + +/** + * @return Aged&Named + */ +function returnsAnonymousWithInterfaces(): Named +{ + return new class implements Named, Aged { + }; +} + +function returnsAnonymousClass(): object +{ + return new class { + }; +} + +function returnsAnonymousClassOrNull(bool $b): ?AbstractAnimal +{ + return $b ? new class extends AbstractAnimal { + } : null; +} + +/** + * @return array{AbstractAnimal} + */ +function returnsAnonymousInArray(): array +{ + return [new class extends AbstractAnimal { + }]; +} + +/** + * @return array{id: int, name: string, tags: array{string, string}, active: bool, parent: null} + */ +function returnsSmallShape(): array +{ + return ['id' => 1, 'name' => 'foo', 'tags' => ['a', 'b'], 'active' => true, 'parent' => null]; +} + +/** + * @return non-empty-array + */ +function returnsLargeShape(): array +{ + return ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 'eleven']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithNonAsciiKey(): array +{ + return ['příliš' => 'žluťoučký', 'kůň' => 'úpěl']; +} + +/** + * @return non-empty-array + */ +function returnsShapeWithEndOfCommentKey(): array +{ + return ['a*/' => 1]; +} + +/** + * @return array{array{string, string, bool, null}, array{string, string, bool, string}} + */ +function dataProvider(): array +{ + return [ + ['today', '+9 days', true, null], + ['-5 days', '+30 days', false, '/Requested ship date.*/'], + ]; +} + +/** + * @param list $ints + * @return list + */ +function returnsListOfConstantString(array $ints): array +{ + $strings = []; + foreach ($ints as $int) { + $strings[] = 'x'; + } + + return $strings; +} + +/** + * @return \Generator + */ +function yieldsConstantStrings(): \Generator +{ + yield 'a'; + yield 'b'; +} + +/** + * @param array{a: 'x', ...} $a + * @return array{a: string, ...} + */ +function returnsUnsealedShape(array $a): array +{ + return $a; +} + +/** + * @param array{...}>} $a + * @return array}> + */ +function returnsNestedUnsealedShape(array $a): array +{ + return $a; +} + +class Response +{ +} + +class RedirectResponse extends Response +{ +} + +function returnsNewResponses(bool $b): Response +{ + if ($b) { + return new RedirectResponse(); + } + + return new Response(); +} + +/** + * @return array{Response} + */ +function returnsNewResponsesInArray(bool $b): array +{ + return [$b ? new RedirectResponse() : new Response()]; +} + +/** + * @param array $a + */ +function returnsArrayOfMixedValues(array $a) +{ + return $a; +} + +/** + * @param iterable $i + */ +function returnsIterableOfMixedValues(iterable $i) +{ + return $i; +} + +/** + * @param array> $a + */ +function returnsNestedArrayOfMixedValues(array $a) +{ + return $a; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php73.php.fixed new file mode 100644 index 00000000000..4b20dec7a4e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-with-ignores-php73.php.fixed @@ -0,0 +1,43 @@ + $a + * @return list + * @phpstan-ignore missingType.parameter + */ +function ignoreByIdentifier(array $a, $b): array +{ + return $a; +} + +/** + * @param list $a + * @phpstan-ignore-next-line + */ +function ignoreNextLine(array $a, $b) +{ + return $a; +} + +/** + * @phpstan-ignore missingType.parameter + * @param list $a + * @return list + */ +function ignoreAboveParam(array $a, $b): array +{ + return $a; +} + +/** + * @return array{a: int} + * @phpstan-ignore missingType.parameter + */ +function ignoreOnly(int $i, $b): array +{ + return ['a' => $i]; +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php73.php.fixed new file mode 100644 index 00000000000..05f323959c8 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php73.php.fixed @@ -0,0 +1,352 @@ + $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + +} + +class ParentClass +{ + + private function privateMethod(): int + { + return 1; + } + + public function overriddenWithString() + { + return 1; + } + + public function createAnimal() + { + return new Dog(); + } + + public function overriddenByPhpDocOnly() + { + return 1; + } + + /** + * @return array{int, int} + */ + public function notOverridden(): array + { + return [1, 2]; + } + + /** + * @return \Generator + */ + public function generator(): \Generator + { + yield 1; + } + + /** + * @return static + */ + public function returnsThis(): self + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString(): string + { + return 'foo'; + } + + public function createAnimal(): Cat + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function make(): Animal + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + /** + * @return Dog + */ + public function make(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class IterableParent +{ + + /** + * @return array{int}|array{string} + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed index 39ecb357d45..4082f60c5a3 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -225,6 +225,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed index 80cc5f5937c..10b3a9be94b 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -216,6 +216,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed index 2897e856a99..d55758e994e 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -213,6 +213,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed index 2897e856a99..d55758e994e 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -213,6 +213,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get(): Animal + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php73.php.fixed new file mode 100644 index 00000000000..3ae6bdb03f0 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php73.php.fixed @@ -0,0 +1,343 @@ + $ints + * @return list + */ + public static function createMany(array $ints): array + { + return array_map(static fn (int $int) => new self(), $ints); + } + +} + +class ParentClass +{ + + private function privateMethod(): int + { + return 1; + } + + public function overriddenWithString() + { + return 1; + } + + public function createAnimal() + { + return new Dog(); + } + + public function overriddenByPhpDocOnly() + { + return 1; + } + + public function notOverridden() + { + return [1, 2]; + } + + public function generator() + { + yield 1; + } + + public function returnsThis() + { + return $this; + } + +} + +class ChildClass extends ParentClass +{ + + public function overriddenWithString() + { + return 'foo'; + } + + public function createAnimal() + { + return new Cat(); + } + + /** + * @return int + */ + public function overriddenByPhpDocOnly() + { + return 2; + } + +} + +class Error +{ +} + +class DeclaringParent +{ + + /** + * @return Dog|Error + */ + public function getItem() + { + return new Dog(); + } + +} + +final class ChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +final class ChildWithinParent extends DeclaringParent +{ + + public function getItem(): Dog + { + return new Dog(); + } + +} + +class OverridableChildViolatingParent extends DeclaringParent +{ + + /** + * @return array|Error + */ + public function getItem() + { + return ['a' => 1]; + } + +} + +interface ReturnsAnimals +{ + + /** + * @return list + */ + public function animals(): array; + +} + +final class ReturnsStrings implements ReturnsAnimals +{ + + /** + * @return array + */ + public function animals(): array + { + return ['dog']; + } + +} + +final class ReturnsDogs implements ReturnsAnimals +{ + + /** + * @return array{Dog} + */ + public function animals(): array + { + return [new Dog()]; + } + +} + +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return Dog The dog. + */ + public function getItem(): Dog + { + return new Dog(); + } + +} + +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function make(): Animal + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + /** + * @return Dog + */ + public function make(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class IterableParent +{ + + /** + * @return array + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array{string} + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed index 1fc64c97f19..782704956ac 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -213,6 +213,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed index cfebc2a7d0d..77bc6cc78aa 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed @@ -210,6 +210,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed index 61ef700f3b1..8d445f6e047 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed @@ -207,6 +207,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed index 61ef700f3b1..8d445f6e047 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed @@ -207,6 +207,103 @@ final class ChildWithDescribedReturn extends DeclaringParent } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php index 85cae8e1eb6..5c30eeb187b 100644 --- a/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php @@ -209,6 +209,103 @@ public function getItem() } +class NativeParent +{ + + public function make(): Animal + { + return new Animal(); + } + +} + +final class ChildOfNativeParent extends NativeParent +{ + + public function make() + { + return new Dog(); + } + +} + +interface MakesAnimal +{ + + public function make(): Animal; + +} + +final class MakesDog implements MakesAnimal +{ + + public function make() + { + return new Dog(); + } + +} + +class UntypedParentOfNarrowerNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class NarrowerNativeChild extends UntypedParentOfNarrowerNativeChild +{ + + public function get(): Dog + { + return new Dog(); + } + +} + +class UntypedParentOfSameNativeChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class SameNativeChild extends UntypedParentOfSameNativeChild +{ + + public function get(): Animal + { + return new Dog(); + } + +} + +class UntypedParentOfUntypedChild +{ + + public function get() + { + return new Animal(); + } + +} + +final class UntypedChild extends UntypedParentOfUntypedChild +{ + + public function get() + { + return new Dog(); + } + +} + class IterableParent { diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php73.php.fixed new file mode 100644 index 00000000000..b2f5745ad84 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php73.php.fixed @@ -0,0 +1,238 @@ +value; + } + + public function getValuePublic() + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + /** + * @return Cat|Dog + */ + public function createAnimal(): Animal + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + /** + * @return static + */ + public function fluent(): self + { + return $this; + } + + public function newSelf() + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{int, int} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden(): int + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden(): string + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php73.php.fixed new file mode 100644 index 00000000000..71cd06f18b0 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-open-project-php73.php.fixed @@ -0,0 +1,238 @@ +value; + } + + public function getValuePublic() + { + return $this->value; + } + +} + +final class IntValue +{ + + use ReturnsProperty; + + private int $value = 1; + +} + +final class StringValue +{ + + use ReturnsProperty; + + private string $value = 'foo'; + +} + +trait ReturnsAnimal +{ + + /** + * @return Cat|Dog + */ + public function createAnimal(): Animal + { + return $this->animal; + } + +} + +final class HasDog +{ + + use ReturnsAnimal; + + private Dog $animal; + +} + +final class HasCat +{ + + use ReturnsAnimal; + + private Cat $animal; + +} + +trait ReturnsThis +{ + + /** + * @return static + */ + public function fluent(): self + { + return $this; + } + + public function newSelf() + { + return new self(); + } + +} + +final class FluentOne +{ + + use ReturnsThis; + +} + +final class FluentTwo +{ + + use ReturnsThis; + +} + +trait ReturnsMixedInOneClass +{ + + private function get() + { + return $this->untyped; + } + +} + +final class TypedProperty +{ + + use ReturnsMixedInOneClass; + + private int $untyped = 1; + +} + +final class UntypedProperty +{ + + use ReturnsMixedInOneClass; + + private $untyped = 1; + +} + +trait Nothing +{ + + private function doNothing(): void + { + } + + /** + * @return array{int, int} + */ + public function list(): array + { + return [1, 2]; + } + +} + +final class UsesNothing +{ + + use Nothing; + +} + +trait Overridable +{ + + public function overridden() + { + return 1; + } + + protected function notOverridden() + { + return 1; + } + + private function privateInOverridableClass(): int + { + return 1; + } + +} + +class UsesOverridable +{ + + use Overridable; + +} + +class OverridesTraitMethod extends UsesOverridable +{ + + public function overridden() + { + return 'foo'; + } + +} + +trait Aliased +{ + + private function original(): int + { + return 1; + } + +} + +final class UsesAliased +{ + + use Aliased { + original as aliased; + } + +} + +trait Unused +{ + + public function unused() + { + return 1; + } + +} From eb1373e92b2196357147c33eea2a36dd603a733f Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 15:22:10 +0000 Subject: [PATCH 17/24] Fix too-wide return types of functions and methods that cannot be overridden Under the fixMissingReturnTypes feature toggle, return.unusedType and return.tooWideBool of functions, private methods and methods that cannot be overridden remove the members the function never returns, first from the native type, then from the @return tags, which stay subtypes of the native type. bool becomes true or false only where PHP allows it, and before PHP 7.4 the native type of an overriding method is not narrowed. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- Makefile | 1 + .../TooWideReturnTypeFixer.php | 485 ++++++++++++++++++ .../TooWideTypehints/TooWideTypeCheck.php | 167 +++++- .../TooWideReturnTypeFixPhp73Test.php | 13 + .../TooWideReturnTypeFixPhp74Test.php | 13 + .../TooWideReturnTypeFixPhp82Test.php | 13 + .../TooWideReturnTypeFixTestCase.php | 70 +++ .../data/fix-too-wide-return-type-php73.neon | 7 + .../data/fix-too-wide-return-type-php74.neon | 7 + .../data/fix-too-wide-return-type-php82.neon | 7 + .../functions-native-union-php73.php.fixed | 17 + .../functions-native-union-php74.php.fixed | 17 + .../functions-native-union-php82.php.fixed | 17 + .../functions-native-union.php | 17 + .../functions-php73.php.fixed | 60 +++ .../functions-php74.php.fixed | 60 +++ .../functions-php82.php.fixed | 60 +++ .../fix-too-wide-return-type/functions.php | 60 +++ ...thods-open-project-checked-php73.php.fixed | 111 ++++ ...thods-open-project-checked-php74.php.fixed | 111 ++++ ...thods-open-project-checked-php82.php.fixed | 111 ++++ .../methods-open-project-php73.php.fixed | 111 ++++ .../methods-open-project-php74.php.fixed | 111 ++++ .../methods-open-project-php82.php.fixed | 111 ++++ .../data/fix-too-wide-return-type/methods.php | 111 ++++ 25 files changed, 1864 insertions(+), 4 deletions(-) create mode 100644 src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp73Test.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp74Test.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp82Test.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php73.neon create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php74.neon create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php82.neon create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php diff --git a/Makefile b/Makefile index 989758c626e..618fd33268d 100644 --- a/Makefile +++ b/Makefile @@ -21,6 +21,7 @@ lint: --exclude tests/PHPStan/Rules/Methods/data \ --exclude tests/PHPStan/Rules/Functions/data \ --exclude tests/PHPStan/Rules/data/fix-missing-return-type \ + --exclude tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type \ --exclude tests/PHPStan/Rules/Names/data \ --exclude tests/PHPStan/Rules/Operators/data/invalid-inc-dec.php \ --exclude tests/PHPStan/Rules/Arrays/data/offset-access-without-dim-for-reading.php \ diff --git a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php new file mode 100644 index 00000000000..e2a866506b7 --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php @@ -0,0 +1,485 @@ +, true: int|null, false: int|null, null: bool} + * @phpstan-type Plan array{native: list|null, tags: list>} + */ +#[AutowiredService] +final class TooWideReturnTypeFixer +{ + + private const RETURN_TAG_NAMES = ['@return', '@phpstan-return', '@psalm-return']; + + public function __construct( + #[AutowiredParameter(ref: '%featureToggles.fixMissingReturnTypes%')] + private bool $enabled, + private PhpDocEditor $phpDocEditor, + private PhpDocStringResolver $phpDocStringResolver, + private TypeNodeResolver $typeNodeResolver, + private FileTypeMapper $fileTypeMapper, + private ParentMethodHelper $parentMethodHelper, + private PhpVersion $phpVersion, + ) + { + } + + public function isEnabled(): bool + { + return $this->enabled; + } + + public function supportsReturnCovariance(): bool + { + return $this->phpVersion->supportsReturnCovariance(); + } + + /** + * Whether the function declares a @return tag of its own, a method without one inherits the PHPDoc of its parent. + */ + public static function hasOwnReturnTag(ClassMethod|Function_ $node): bool + { + $docComment = $node->getDocComment(); + + return $docComment !== null && preg_match('~@(?:phpstan-|psalm-)?return\b~i', $docComment->getText()) === 1; + } + + /** + * Before PHP 7.4 the native return type of a method has to be the same as the ones of the methods it overrides. + */ + public function canNarrowNativeReturnType(?ClassReflection $classReflection, string $functionName): bool + { + if ($classReflection === null || $this->phpVersion->supportsReturnCovariance()) { + return true; + } + + foreach ($this->parentMethodHelper->collectParentMethods($functionName, $classReflection) as [$parentMethod]) { + foreach ($parentMethod->getVariants() as $variant) { + $nativeReturnType = $variant->getNativeReturnType(); + if (!$nativeReturnType instanceof MixedType || $nativeReturnType->isExplicitMixed()) { + return false; + } + } + } + + return true; + } + + /** + * @param list $members the members of the checked return type + * @param bool $checkedPhpDoc whether the checked return type is the PHPDoc one + * @return Plan|null null when the function cannot be fixed, like when its checked PHPDoc type is inherited + */ + public function createPlan( + ClassMethod|Function_ $node, + array $members, + bool $checkedPhpDoc, + bool $narrowsNative, + ?ClassReflection $classReflection, + string $file, + string $functionName, + ): ?array + { + $native = null; + if ($narrowsNative && $node->returnType !== null) { + $native = []; + foreach (self::getNativeMembers($node->returnType) as $memberNode) { + $memberType = $memberNode === null ? new NullType() : ParserNodeTypeToPHPStanType::resolve($memberNode, $classReflection); + $native[] = self::createPlanMember($memberType, $members); + } + } + + $tags = []; + $docComment = $node->getDocComment(); + if ($docComment !== null && self::hasOwnReturnTag($node)) { + $nameScope = $this->fileTypeMapper->getResolvedPhpDoc( + $file, + $classReflection?->getName(), + null, + $functionName, + $docComment->getText(), + )->getNullableNameScope(); + if ($nameScope === null) { + return null; + } + + foreach ($this->findReturnTags($this->phpDocStringResolver->resolve($docComment->getText())) as $tag) { + $tagMembers = []; + foreach (self::getPhpDocMembers($tag->type) as $memberNode) { + $memberType = $memberNode === null ? new NullType() : $this->typeNodeResolver->resolve($memberNode, $nameScope); + $tagMembers[] = self::createPlanMember($memberType, $members); + } + $tags[] = $tagMembers; + } + } elseif ($checkedPhpDoc) { + // the PHPDoc type is inherited, narrowing only the native type would make it wider than the native one + return null; + } + + if ($native === null && $tags === []) { + return null; + } + + return ['native' => $native, 'tags' => $tags]; + } + + /** + * @param Plan $plan + * @param list $kept the members of the checked return type to keep + * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null null when nothing changes or the result would be invalid + */ + public function createFix(array $plan, array $kept): ?callable + { + $changes = false; + $nativeDecisions = null; + $nativeOverlaps = null; + if ($plan['native'] !== null) { + $nativeDecisions = $this->decide($plan['native'], $kept, $this->phpVersion->supportsTrueFalseNullStandaloneType()); + if ($nativeDecisions === null) { + return null; + } + $changes = self::isChanged($nativeDecisions); + $nativeOverlaps = self::getKeptOverlaps($plan['native'], $nativeDecisions); + } + + $tagDecisions = []; + foreach ($plan['tags'] as $tagMembers) { + $decisions = $this->decide($tagMembers, $kept, true); + if ($decisions === null) { + return null; + } + + // the PHPDoc type has to stay a subtype of the native type + if ($nativeOverlaps !== null && array_diff(self::getKeptOverlaps($tagMembers, $decisions), $nativeOverlaps) !== []) { + return null; + } + + $changes = $changes || self::isChanged($decisions); + $tagDecisions[] = $decisions; + } + + if (!$changes) { + return null; + } + + $phpDocEditor = $this->phpDocEditor; + + return static function (ClassMethod|Function_ $node) use ($nativeDecisions, $tagDecisions, $phpDocEditor): ClassMethod|Function_ { + if ($nativeDecisions !== null && $node->returnType !== null) { + $node->returnType = self::narrowNativeType($node->returnType, $nativeDecisions); + } + + if ($tagDecisions === [] || $node->getDocComment() === null) { + return $node; + } + + $phpDocEditor->edit($node, static function (PhpDocAstNode $phpDocNode) use ($tagDecisions): PhpDocAstNode { + if (!$phpDocNode instanceof PhpDocNode) { + return $phpDocNode; + } + + $i = 0; + foreach ($phpDocNode->children as $child) { + if (!$child instanceof PhpDocTagNode || !$child->value instanceof ReturnTagValueNode || !self::isReturnTag($child) || !array_key_exists($i, $tagDecisions)) { + continue; + } + + $child->value->type = self::narrowPhpDocType($child->value->type, $tagDecisions[$i]); + $i++; + } + + return $phpDocNode; + }); + + return $node; + }; + } + + /** + * The fix of an error reported in a CollectedDataNode rule is made on the node at this position, see ReplacingNodeVisitor. + */ + public static function createFixedNode(int $startPos, int $endPos): ClassMethod + { + return new ClassMethod('fixed', attributes: ['startFilePos' => $startPos, 'endFilePos' => $endPos]); + } + + /** + * @param list $members + * @return PlanMember + */ + private static function createPlanMember(Type $memberType, array $members): array + { + $overlaps = []; + $true = null; + $false = null; + foreach ($members as $i => $member) { + if ($memberType->isSuperTypeOf($member)->no()) { + continue; + } + + $overlaps[] = $i; + if ($member->isTrue()->yes()) { + $true = $i; + } elseif ($member->isFalse()->yes()) { + $false = $i; + } + } + + $isBool = $memberType->isBoolean()->yes() && !$memberType->isTrue()->yes() && !$memberType->isFalse()->yes(); + + return [ + 'overlaps' => $overlaps, + 'true' => $isBool && $false !== null ? $true : null, + 'false' => $isBool && $true !== null ? $false : null, + 'null' => $memberType->isNull()->yes(), + ]; + } + + /** + * What happens to each member: kept, removed, or changed from bool to true or false. + * Null when no member would be left, or only null in a native type. + * + * @param list $planMembers + * @param list $kept + * @return list<'keep'|'remove'|'true'|'false'>|null + */ + private function decide(array $planMembers, array $kept, bool $allowsTrueAndFalse): ?array + { + $decisions = []; + $hasNonNull = false; + foreach ($planMembers as $member) { + if ($member['true'] !== null && $member['false'] !== null) { + $keepsTrue = in_array($member['true'], $kept, true); + $keepsFalse = in_array($member['false'], $kept, true); + if ($keepsTrue && $keepsFalse) { + $decision = 'keep'; + } elseif ($keepsTrue || $keepsFalse) { + $decision = $allowsTrueAndFalse ? ($keepsTrue ? 'true' : 'false') : 'keep'; + } else { + $decision = 'remove'; + } + } else { + $decision = array_intersect($member['overlaps'], $kept) === [] ? 'remove' : 'keep'; + } + + if ($decision !== 'remove' && !$member['null']) { + $hasNonNull = true; + } + $decisions[] = $decision; + } + + if (!in_array('keep', $decisions, true) && !in_array('true', $decisions, true) && !in_array('false', $decisions, true)) { + return null; + } + + if (!$hasNonNull && !$allowsTrueAndFalse) { + return null; + } + + return $decisions; + } + + /** + * @param list<'keep'|'remove'|'true'|'false'> $decisions + */ + private static function isChanged(array $decisions): bool + { + foreach ($decisions as $decision) { + if ($decision !== 'keep') { + return true; + } + } + + return false; + } + + /** + * @param list $planMembers + * @param list<'keep'|'remove'|'true'|'false'> $decisions + * @return list + */ + private static function getKeptOverlaps(array $planMembers, array $decisions): array + { + $overlaps = []; + foreach ($planMembers as $i => $member) { + $decision = $decisions[$i]; + if ($decision === 'keep') { + $overlaps[] = $member['overlaps']; + } elseif ($decision !== 'remove' && $member[$decision] !== null) { + $overlaps[] = [$member[$decision]]; + } + } + + return array_values(array_unique(array_merge([], ...$overlaps))); + } + + /** + * The members of a native type, null stands for the null of a nullable type. + * + * @return list + */ + private static function getNativeMembers(Identifier|Name|ComplexType $type): array + { + if ($type instanceof NullableType) { + return [$type->type, null]; + } + + if ($type instanceof UnionType) { + return array_values($type->types); + } + + return [$type]; + } + + /** + * @param list<'keep'|'remove'|'true'|'false'> $decisions + */ + private static function narrowNativeType(Identifier|Name|ComplexType $type, array $decisions): Identifier|Name|ComplexType + { + $kept = []; + foreach (self::getNativeMembers($type) as $i => $member) { + $decision = $decisions[$i]; + if ($decision === 'remove') { + continue; + } + + if ($member === null) { + $kept[] = new Identifier('null'); + continue; + } + + $kept[] = $decision === 'keep' ? $member : new Identifier($decision); + } + + if ($type instanceof NullableType && count($kept) === 2 && ($kept[0] instanceof Identifier || $kept[0] instanceof Name)) { + return new NullableType($kept[0]); + } + + if (count($kept) === 1) { + return $kept[0]; + } + + /** @var list $kept */ + return new UnionType($kept); + } + + /** + * @return list + */ + private static function getPhpDocMembers(TypeNode $type): array + { + if ($type instanceof NullableTypeNode) { + return [$type->type, null]; + } + + if ($type instanceof UnionTypeNode) { + return array_values($type->types); + } + + return [$type]; + } + + /** + * @param list<'keep'|'remove'|'true'|'false'> $decisions + */ + private static function narrowPhpDocType(TypeNode $type, array $decisions): TypeNode + { + $kept = []; + foreach (self::getPhpDocMembers($type) as $i => $member) { + $decision = $decisions[$i]; + if ($decision === 'remove') { + continue; + } + + if ($member === null) { + $kept[] = new IdentifierTypeNode('null'); + continue; + } + + $kept[] = $decision === 'keep' ? $member : new IdentifierTypeNode($decision); + } + + if ($type instanceof NullableTypeNode && count($kept) === 2) { + return new NullableTypeNode($kept[0]); + } + + if (count($kept) === 1) { + return $kept[0]; + } + + return new UnionTypeNode($kept); + } + + /** + * @return list + */ + private function findReturnTags(PhpDocNode $phpDocNode): array + { + $tags = []; + foreach ($phpDocNode->children as $child) { + if (!$child instanceof PhpDocTagNode || !$child->value instanceof ReturnTagValueNode || !self::isReturnTag($child)) { + continue; + } + + $tags[] = $child->value; + } + + return $tags; + } + + private static function isReturnTag(PhpDocTagNode $node): bool + { + return in_array(strtolower($node->name), self::RETURN_TAG_NAMES, true); + } + +} diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 7c8597d3123..f3aeb42e126 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -3,6 +3,8 @@ namespace PHPStan\Rules\TooWideTypehints; use PhpParser\Node\Expr\ConstFetch; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\Node\Stmt\Function_; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; @@ -33,6 +35,9 @@ use function sprintf; use function strtolower; +/** + * @phpstan-import-type Plan from TooWideReturnTypeFixer + */ #[AutowiredService] final class TooWideTypeCheck { @@ -43,6 +48,7 @@ public function __construct( private bool $reportTooWideBool, #[AutowiredParameter(ref: '%featureToggles.reportNestedTooWideType%')] private bool $reportNestedTooWideType, + private ?TooWideReturnTypeFixer $returnTypeFixer = null, ) { } @@ -195,6 +201,7 @@ public function checkFunctionReturnType( $node->getStartLine(), 'return', null, + $this->createReturnTypeFix($node, $nativeFunctionReturnType, $phpDocFunctionReturnType, $returnType, $scope), ); } @@ -236,12 +243,113 @@ public function checkFunctionReturnType( $node->getStartLine(), 'return', null, + $this->createReturnTypeFix($node, $nativeFunctionReturnType, $phpDocFunctionReturnType, $returnType, $scope), ); } return []; } + public function isReturnTypeFixEnabled(): bool + { + return $this->returnTypeFixer !== null && $this->returnTypeFixer->isEnabled(); + } + + /** + * The plan of the fix of the too-wide return type of the function, see TooWideReturnTypeFixer. + * The native type of a method that can be overridden is not narrowed before PHP 7.4, the overriding methods + * have to declare the same one. Null when the fix is not enabled or the function cannot be fixed. + * + * @return Plan|null + */ + public function createReturnTypeFixPlan( + MethodReturnStatementsNode|FunctionReturnStatementsNode $node, + Type $nativeFunctionReturnType, + Type $phpDocFunctionReturnType, + bool $overridable, + Scope $scope, + ): ?array + { + if ($this->returnTypeFixer === null || !$this->returnTypeFixer->isEnabled()) { + return null; + } + + [$declaredType, $native] = $this->getCheckedType($nativeFunctionReturnType, $phpDocFunctionReturnType); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + if ($node instanceof MethodReturnStatementsNode) { + $functionNode = $node->getClassMethod(); + $classReflection = $node->getClassReflection(); + $functionName = $functionNode->name->toString(); + } else { + $functionNode = $node->getFunction(); + $classReflection = null; + $functionName = $node->getFunctionReflection()->getName(); + } + + $narrowsNative = $this->returnTypeFixer->canNarrowNativeReturnType($classReflection, $functionName) + && (!$overridable || $this->returnTypeFixer->supportsReturnCovariance()); + + return $this->returnTypeFixer->createPlan( + $functionNode, + $members, + !$native, + $narrowsNative, + $classReflection, + $scope->getFile(), + $functionName, + ); + } + + /** + * Fixes the return type of a function or a method that cannot be overridden, by keeping the returned members. + * + * @return array{ClassMethod|Function_, callable(ClassMethod|Function_): (ClassMethod|Function_)}|null + */ + private function createReturnTypeFix( + MethodReturnStatementsNode|FunctionReturnStatementsNode $node, + Type $nativeFunctionReturnType, + Type $phpDocFunctionReturnType, + Type $returnType, + Scope $scope, + ): ?array + { + if ($this->returnTypeFixer === null) { + return null; + } + + // the fix of a method that can be overridden is coordinated with the methods overriding it, see TooWideTypeInOverridableMemberRule + if ( + $node instanceof MethodReturnStatementsNode + && !$node->getMethodReflection()->isPrivate() + && !$node->getClassReflection()->isFinal() + && !$node->getMethodReflection()->isFinal()->yes() + ) { + return null; + } + + $plan = $this->createReturnTypeFixPlan($node, $nativeFunctionReturnType, $phpDocFunctionReturnType, false, $scope); + if ($plan === null) { + return null; + } + + [$declaredType, $native] = $this->getCheckedType($nativeFunctionReturnType, $phpDocFunctionReturnType); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + $fix = $this->returnTypeFixer->createFix($plan, $this->getUsedMembers($declaredType, $members, $returnType, false)); + if ($fix === null) { + return null; + } + + return [$node instanceof MethodReturnStatementsNode ? $node->getClassMethod() : $node->getFunction(), $fix]; + } + /** * The members of the return type of a method that can be overridden, which TooWideTypeInOverridableMemberRule * reports when neither the method nor the methods overriding it return them: the members the method returns @@ -306,6 +414,42 @@ public function getUsedOverriddenReturnTypeMembers( return $this->getUsedMembers($declaredType, $members, $returnType, false); } + /** + * The members of the return type of an overridden method, as createOverridableReturnTypeErrors() lists them, + * that the declared return type of the overriding method overlaps. The fix of the overridden method keeps them, + * so that the overriding method stays covariant. Null when no member of the return type can be reported. + * + * @return list|null + */ + public function getDeclaredOverriddenReturnTypeMembers( + ExtendedParametersAcceptor $overriddenMethodVariant, + Type $declaredReturnType, + Scope $scope, + ): ?array + { + [$declaredType, $native] = $this->getCheckedReturnType($overriddenMethodVariant); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + if ($declaredReturnType instanceof MixedType && !$declaredReturnType->isExplicitMixed()) { + return []; + } + + $declaredReturnType = TypeUtils::resolveLateResolvableTypes($declaredReturnType); + $overlapping = []; + foreach ($members as $i => $member) { + if ($member->isSuperTypeOf($declaredReturnType)->no()) { + continue; + } + + $overlapping[] = $i; + } + + return $overlapping; + } + /** * Null when the function is a generator or it does not return anything. */ @@ -383,12 +527,19 @@ private function keepsWholeReturnType( */ private function getCheckedReturnType(ExtendedParametersAcceptor $variant): array { - $phpDocReturnType = $variant->getPhpDocReturnType(); - if (!$phpDocReturnType instanceof MixedType || $phpDocReturnType->isExplicitMixed()) { - return [TypeUtils::resolveLateResolvableTypes(TypehintHelper::decideType($variant->getNativeReturnType(), $phpDocReturnType)), false]; + return $this->getCheckedType($variant->getNativeReturnType(), $variant->getPhpDocReturnType()); + } + + /** + * @return array{Type, bool} + */ + private function getCheckedType(Type $nativeType, Type $phpDocType): array + { + if (!$phpDocType instanceof MixedType || $phpDocType->isExplicitMixed()) { + return [TypeUtils::resolveLateResolvableTypes(TypehintHelper::decideType($nativeType, $phpDocType)), false]; } - return [$variant->getNativeReturnType(), true]; + return [$nativeType, true]; } /** @@ -510,6 +661,7 @@ public function getUsedOverriddenParameterOutTypeMembers(Type $parameterOutType, /** * @param 'return'|'property'|'paramOut'|'parameterByRef' $identifierPart + * @param array{ClassMethod|Function_, callable(ClassMethod|Function_): (ClassMethod|Function_)}|null $fix * @return list */ private function createErrors( @@ -520,6 +672,7 @@ private function createErrors( int $startLine, string $identifierPart, ?string $tip, + ?array $fix = null, ): array { if ($originalType->isBoolean()->yes()) { @@ -533,6 +686,9 @@ private function createErrors( if ($tip !== null) { $errorBuilder->tip($tip); } + if ($fix !== null) { + $errorBuilder->fixNode($fix[0], $fix[1]); + } return [$errorBuilder->build()]; } @@ -554,6 +710,9 @@ private function createErrors( if ($tip !== null) { $errorBuilder->tip($tip); } + if ($fix !== null) { + $errorBuilder->fixNode($fix[0], $fix[1]); + } $messages[] = $errorBuilder->build(); } diff --git a/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp73Test.php b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp73Test.php new file mode 100644 index 00000000000..a03de6a8294 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixPhp73Test.php @@ -0,0 +1,13 @@ + + */ +abstract class TooWideReturnTypeFixTestCase extends RuleTestCase +{ + + /** @var 'open'|'closed' */ + private string $projectType = 'open'; + + private bool $checkProtectedAndPublicMethods = false; + + abstract protected static function getPhpVersionSuffix(): string; + + protected function getRule(): Rule + { + $check = self::getContainer()->getByType(TooWideTypeCheck::class); + $overridableMemberHelper = new OverridableMemberHelper($this->projectType); + + // @phpstan-ignore argument.type + return new CompositeRule([ + new TooWideFunctionReturnTypehintRule($check), + new TooWideMethodReturnTypehintRule($this->checkProtectedAndPublicMethods, $check, $overridableMemberHelper), + new TooWideTypeInOverridableMemberRule(), + ]); + } + + public function testFunctions(): void + { + $this->fix(__DIR__ . '/data/fix-too-wide-return-type/functions.php', $this->getFixedFile('functions')); + } + + public function testFunctionsWithNativeUnionTypes(): void + { + $this->fix(__DIR__ . '/data/fix-too-wide-return-type/functions-native-union.php', $this->getFixedFile('functions-native-union')); + } + + public function testMethodsInOpenProject(): void + { + $this->fix(__DIR__ . '/data/fix-too-wide-return-type/methods.php', $this->getFixedFile('methods-open-project')); + } + + public function testMethodsInOpenProjectCheckingProtectedAndPublic(): void + { + $this->checkProtectedAndPublicMethods = true; + $this->fix(__DIR__ . '/data/fix-too-wide-return-type/methods.php', $this->getFixedFile('methods-open-project-checked')); + } + + private function getFixedFile(string $name): string + { + return __DIR__ . '/data/fix-too-wide-return-type/' . $name . '-' . static::getPhpVersionSuffix() . '.php.fixed'; + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/data/fix-too-wide-return-type-' . static::getPhpVersionSuffix() . '.neon', + ]; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php73.neon b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php73.neon new file mode 100644 index 00000000000..d8cedde0e30 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php73.neon @@ -0,0 +1,7 @@ +parameters: + phpVersion: 70300 + featureToggles: + fixMissingReturnTypes: true + reportTooWideBool: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php74.neon b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php74.neon new file mode 100644 index 00000000000..1f87f928c00 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php74.neon @@ -0,0 +1,7 @@ +parameters: + phpVersion: 70400 + featureToggles: + fixMissingReturnTypes: true + reportTooWideBool: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php82.neon b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php82.neon new file mode 100644 index 00000000000..ddcd248867b --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type-php82.neon @@ -0,0 +1,7 @@ +parameters: + phpVersion: 80200 + featureToggles: + fixMissingReturnTypes: true + reportTooWideBool: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed new file mode 100644 index 00000000000..137cd5a4fb9 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed @@ -0,0 +1,17 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): ?Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed new file mode 100644 index 00000000000..f409fb2518f --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed new file mode 100644 index 00000000000..f409fb2518f --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed new file mode 100644 index 00000000000..cda2a068c92 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): ?Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed new file mode 100644 index 00000000000..f409fb2518f --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed new file mode 100644 index 00000000000..f409fb2518f --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php new file mode 100644 index 00000000000..f41e926e1ad --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -0,0 +1,111 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog|Cat + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog|null + */ + public function get(): ?Animal + { + return new Dog(); + } + +} From bdd8f2fe0b2b6431d741f77e3cd7e26041239e21 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 15:34:54 +0000 Subject: [PATCH 18/24] Coordinate the fixes of too-wide return types across the class hierarchy In a closed project, and in an open project with checkTooWideReturnTypesInProtectedAndPublicMethods, the return type of a method that can be overridden is fixed in TooWideTypeInOverridableMemberRule. The overriding methods emit the members of the overridden type they return and declare, the fix keeps them, so the overridden type stays as wide as the overriding ones need. Usages computed against another version of the overridden type do not take part in a fix. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../OverridableMemberHelper.php | 32 ++++ .../TooWideMethodReturnTypehintRule.php | 78 ++++++-- .../TooWideReturnTypeFixer.php | 9 +- .../TooWideTypehints/TooWideTypeCheck.php | 40 +++- ...ooWideTypeInOverridableMemberCollector.php | 4 +- .../TooWideTypeInOverridableMemberRule.php | 57 +++++- .../TypeUsedInOverridingMemberCollector.php | 2 +- .../TooWideReturnTypeFixTestCase.php | 8 +- .../methods-closed-project-php73.php.fixed | 180 ++++++++++++++++++ .../methods-closed-project-php74.php.fixed | 180 ++++++++++++++++++ .../methods-closed-project-php82.php.fixed | 180 ++++++++++++++++++ ...thods-open-project-checked-php73.php.fixed | 73 ++++++- ...thods-open-project-checked-php74.php.fixed | 73 ++++++- ...thods-open-project-checked-php82.php.fixed | 73 ++++++- .../methods-open-project-php73.php.fixed | 69 +++++++ .../methods-open-project-php74.php.fixed | 69 +++++++ .../methods-open-project-php82.php.fixed | 69 +++++++ .../data/fix-too-wide-return-type/methods.php | 69 +++++++ 18 files changed, 1229 insertions(+), 36 deletions(-) create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed create mode 100644 tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed diff --git a/src/Rules/TooWideTypehints/OverridableMemberHelper.php b/src/Rules/TooWideTypehints/OverridableMemberHelper.php index f0e1d54403c..3333dcdd19a 100644 --- a/src/Rules/TooWideTypehints/OverridableMemberHelper.php +++ b/src/Rules/TooWideTypehints/OverridableMemberHelper.php @@ -20,6 +20,8 @@ * the member uses itself with emitDeclaration(), and the members of the types of the overridden members * an overriding member uses with emitUsage(). TooWideTypeInOverridableMemberRule reports the members * of the type nobody uses. + * + * @phpstan-import-type Plan from TooWideReturnTypeFixer */ #[AutowiredService] final class OverridableMemberHelper @@ -124,6 +126,8 @@ public function findOverriddenPropertyHooks(ClassReflection $classReflection, st * @param list $memberErrors message, identifier and tip for each member of the type * @param string|null $usedMembersTip tip for the errors with %s for the used members, or void * @param list $memberDescriptions the members of the type in $usedMembersTip + * @param bool $ownOnly whether only the members the member uses itself are not reported, in an open project + * @param array{plan: Plan, startPos: int, endPos: int}|null $fix the plan of the fix of the return type, see TooWideReturnTypeFixer */ public function emitDeclaration( Scope&CollectedDataEmitter $scope, @@ -136,6 +140,8 @@ public function emitDeclaration( array $memberErrors, ?string $usedMembersTip = null, array $memberDescriptions = [], + bool $ownOnly = false, + ?array $fix = null, ): void { $file = null; @@ -159,12 +165,36 @@ public function emitDeclaration( 'errors' => $memberErrors, 'usedMembersTip' => $usedMembersTip, 'memberDescriptions' => $memberDescriptions, + 'ownOnly' => $ownOnly, + 'fix' => $fix, ]); } + /** + * emitDeclaration() of the return type of a method, with the plan of its fix. + * + * @param list $usedMembers + * @param list $memberErrors + * @param array{plan: Plan, startPos: int, endPos: int}|null $fix + */ + public function emitReturnTypeDeclaration( + Scope&CollectedDataEmitter $scope, + string $className, + string $memberKey, + int $line, + array $usedMembers, + array $memberErrors, + bool $ownOnly, + ?array $fix, + ): void + { + $this->emitDeclaration($scope, self::KIND_RETURN, $className, $memberKey, 0, $line, $usedMembers, $memberErrors, null, [], $ownOnly, $fix); + } + /** * @param self::KIND_* $kind * @param list $usedMembers the members of the type of the overridden member the overriding member uses + * @param array{list, list, int}|null $declaredMembers the members its PHPDoc and native types overlap and the number of members, for the fix of the overridden member */ public function emitUsage( CollectedDataEmitter $scope, @@ -173,6 +203,7 @@ public function emitUsage( string $overriddenMemberKey, int $slot, array $usedMembers, + ?array $declaredMembers = null, ): void { $scope->emitCollectedData(TypeUsedInOverridingMemberCollector::class, [ @@ -181,6 +212,7 @@ public function emitUsage( 'member' => $overriddenMemberKey, 'slot' => $slot, 'used' => $usedMembers, + 'declared' => $declaredMembers, ]); } diff --git a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php index 98fea3003d8..b47f6fe74de 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php @@ -8,7 +8,9 @@ use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Node\MethodReturnStatementsNode; +use PHPStan\Rules\IdentifierRuleError; use PHPStan\Rules\Rule; +use function in_array; use function sprintf; /** @@ -37,13 +39,19 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra $method = $node->getMethodReflection(); $classReflection = $node->getClassReflection(); $isClosedProject = $this->overridableMemberHelper->isClosedProject(); - if ($isClosedProject) { + $isFixEnabled = $this->check->isReturnTypeFixEnabled(); + // the fix of an overridden method keeps what the overriding methods return and declare + if ($isClosedProject || ($isFixEnabled && $this->checkProtectedAndPublicMethods)) { foreach ($this->overridableMemberHelper->findOverriddenMethods($classReflection, $method->getName()) as $overriddenMethod) { $usedMembers = $this->check->getUsedOverriddenReturnTypeMembers($node, $overriddenMethod->getOnlyVariant(), $scope); if ($usedMembers === null) { continue; } + $declaredMembers = $isFixEnabled + ? $this->check->getDeclaredOverriddenReturnTypeMembers($overriddenMethod->getOnlyVariant(), $method, TooWideReturnTypeFixer::hasOwnReturnTag($node->getClassMethod()), $scope) + : null; + $this->overridableMemberHelper->emitUsage( $scope, OverridableMemberHelper::KIND_RETURN, @@ -51,6 +59,7 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra OverridableMemberHelper::getMethodKey($overriddenMethod->getName()), 0, $usedMembers, + $declaredMembers, ); } } @@ -76,16 +85,7 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra $scope, ); if ($result !== null) { - $this->overridableMemberHelper->emitDeclaration( - $scope, - OverridableMemberHelper::KIND_RETURN, - $classReflection->getName(), - OverridableMemberHelper::getMethodKey($method->getName()), - 0, - $node->getStartLine(), - $result[0], - $result[1], - ); + $this->emitDeclaration($node, $scope, $result, false); } return []; @@ -98,6 +98,28 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra if ($isFirstDeclaration) { return []; } + + $errors = $this->check->checkFunctionReturnType( + $node, + $method->getNativeReturnType(), + $method->getPhpDocReturnType(), + $functionDescription, + $checkDescendantClass, + $scope, + ); + if (!$isFixEnabled || !self::hasRemovableMemberErrors($errors)) { + return $errors; + } + + // the same errors, reported with a fix that keeps what the analysed overriding methods need + $result = $this->check->createOverridableReturnTypeErrors($node, $method, $functionDescription, $checkDescendantClass, $scope, false); + if ($result === null) { + return $errors; + } + + $this->emitDeclaration($node, $scope, $result, true); + + return []; } } @@ -111,4 +133,38 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra ); } + /** + * @param array{list, list} $result + */ + private function emitDeclaration(MethodReturnStatementsNode $node, Scope&CollectedDataEmitter $scope, array $result, bool $ownOnly): void + { + $method = $node->getMethodReflection(); + $classMethod = $node->getClassMethod(); + $plan = $this->check->createReturnTypeFixPlan($node, $method->getNativeReturnType(), $method->getPhpDocReturnType(), true, $scope); + $this->overridableMemberHelper->emitReturnTypeDeclaration( + $scope, + $node->getClassReflection()->getName(), + OverridableMemberHelper::getMethodKey($method->getName()), + $node->getStartLine(), + $result[0], + $result[1], + $ownOnly, + $plan !== null ? ['plan' => $plan, 'startPos' => $classMethod->getStartFilePos(), 'endPos' => $classMethod->getEndFilePos()] : null, + ); + } + + /** + * @param list $errors + */ + private static function hasRemovableMemberErrors(array $errors): bool + { + foreach ($errors as $error) { + if (in_array($error->getIdentifier(), ['return.unusedType', 'return.tooWideBool'], true)) { + return true; + } + } + + return false; + } + } diff --git a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php index e2a866506b7..c8ef959eead 100644 --- a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php +++ b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php @@ -175,16 +175,17 @@ public function createPlan( /** * @param Plan $plan - * @param list $kept the members of the checked return type to keep + * @param list $phpDocKept the members of the checked return type the @return tags keep + * @param list $nativeKept the members of the checked return type the native type keeps, a superset of $phpDocKept * @return (callable(ClassMethod|Function_): (ClassMethod|Function_))|null null when nothing changes or the result would be invalid */ - public function createFix(array $plan, array $kept): ?callable + public function createFix(array $plan, array $phpDocKept, array $nativeKept): ?callable { $changes = false; $nativeDecisions = null; $nativeOverlaps = null; if ($plan['native'] !== null) { - $nativeDecisions = $this->decide($plan['native'], $kept, $this->phpVersion->supportsTrueFalseNullStandaloneType()); + $nativeDecisions = $this->decide($plan['native'], $nativeKept, $this->phpVersion->supportsTrueFalseNullStandaloneType()); if ($nativeDecisions === null) { return null; } @@ -194,7 +195,7 @@ public function createFix(array $plan, array $kept): ?callable $tagDecisions = []; foreach ($plan['tags'] as $tagMembers) { - $decisions = $this->decide($tagMembers, $kept, true); + $decisions = $this->decide($tagMembers, $phpDocKept, true); if ($decisions === null) { return null; } diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index f3aeb42e126..0a455032154 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -342,7 +342,8 @@ private function createReturnTypeFix( return null; } - $fix = $this->returnTypeFixer->createFix($plan, $this->getUsedMembers($declaredType, $members, $returnType, false)); + $usedMembers = $this->getUsedMembers($declaredType, $members, $returnType, false); + $fix = $this->returnTypeFixer->createFix($plan, $usedMembers, $usedMembers); if ($fix === null) { return null; } @@ -363,6 +364,7 @@ public function createOverridableReturnTypeErrors( string $functionDescription, bool $checkDescendantClass, Scope $scope, + ?bool $usedMembersCheckDescendantClass = null, ): ?array { $returnType = $this->getReturnedType($node); @@ -382,7 +384,7 @@ public function createOverridableReturnTypeErrors( [$unionMessagePattern, $boolMessagePattern] = $this->getReturnTypeMessagePatterns($functionDescription); return [ - $this->getUsedMembers($declaredType, $members, $returnType, $checkDescendantClass), + $this->getUsedMembers($declaredType, $members, $returnType, $usedMembersCheckDescendantClass ?? $checkDescendantClass), $this->createMemberErrors($declaredType, $members, $unionMessagePattern, $boolMessagePattern, 'return', null), ]; } @@ -416,14 +418,17 @@ public function getUsedOverriddenReturnTypeMembers( /** * The members of the return type of an overridden method, as createOverridableReturnTypeErrors() lists them, - * that the declared return type of the overriding method overlaps. The fix of the overridden method keeps them, - * so that the overriding method stays covariant. Null when no member of the return type can be reported. + * that the declared return types of the overriding method overlap: the PHPDoc one and the native one. + * The fix of the overridden method keeps them, so that the overriding method stays covariant. + * Null when no member of the return type can be reported. The last item is the number of members, + * the indexes are valid only for a declaration with the same number of them. * - * @return list|null + * @return array{list, list, int}|null */ public function getDeclaredOverriddenReturnTypeMembers( ExtendedParametersAcceptor $overriddenMethodVariant, - Type $declaredReturnType, + ExtendedParametersAcceptor $overridingMethodVariant, + bool $hasOwnReturnTag, Scope $scope, ): ?array { @@ -433,14 +438,31 @@ public function getDeclaredOverriddenReturnTypeMembers( return null; } - if ($declaredReturnType instanceof MixedType && !$declaredReturnType->isExplicitMixed()) { + // without a @return tag of its own, the overriding method inherits the narrowed PHPDoc type + [$overridingType] = $this->getCheckedReturnType($overridingMethodVariant); + + return [ + $hasOwnReturnTag ? self::getOverlappingMembers($members, $overridingType) : [], + self::getOverlappingMembers($members, $overridingMethodVariant->getNativeReturnType()), + count($members), + ]; + } + + /** + * @param list $members + * @return list + */ + private static function getOverlappingMembers(array $members, Type $type): array + { + // a method without a return type does not declare anything, what it returns is in its usage + if ($type instanceof MixedType && !$type->isExplicitMixed()) { return []; } - $declaredReturnType = TypeUtils::resolveLateResolvableTypes($declaredReturnType); + $type = TypeUtils::resolveLateResolvableTypes($type); $overlapping = []; foreach ($members as $i => $member) { - if ($member->isSuperTypeOf($declaredReturnType)->no()) { + if ($member->isSuperTypeOf($type)->no()) { continue; } diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php index 4b4f4d8f949..b1aac0fdc9b 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php @@ -8,9 +8,11 @@ use PHPStan\ShouldNotHappenException; /** + * @phpstan-import-type Plan from TooWideReturnTypeFixer + * * Not registered as a collector, the data is emitted with OverridableMemberHelper::emitDeclaration(). * - * @implements Collector, errors: list, usedMembersTip: string|null, memberDescriptions: list}> + * @implements Collector, errors: list, usedMembersTip: string|null, memberDescriptions: list, ownOnly: bool, fix: array{plan: Plan, startPos: int, endPos: int}|null}> */ final class TooWideTypeInOverridableMemberCollector implements Collector { diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php index 33499ca271d..7f5808d77f4 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php @@ -8,6 +8,7 @@ use PHPStan\Node\CollectedDataNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use function array_keys; use function count; use function implode; use function sprintf; @@ -16,6 +17,8 @@ * Reports the members of a too-wide type of a member that can be overridden in a closed project * which neither the member nor the members overriding it use - see OverridableMemberHelper. * Removing them from the types keeps the types of the overriding members covariant. + * In an open project with checkTooWideReturnTypesInProtectedAndPublicMethods, only the members the member uses + * itself count, the declaration is collected for the fix, see TooWideReturnTypeFixer. * * @implements Rule */ @@ -23,6 +26,12 @@ final class TooWideTypeInOverridableMemberRule implements Rule { + public function __construct( + private ?TooWideReturnTypeFixer $fixer = null, + ) + { + } + public function getNodeType(): string { return CollectedDataNode::class; @@ -31,24 +40,45 @@ public function getNodeType(): string public function processNode(Node $node, Scope $scope): array { $declarations = $node->get(TooWideTypeInOverridableMemberCollector::class); - // the members overriding the declarations might not be analysed - if ($declarations === [] || $node->isOnlyFilesAnalysis()) { + if ($declarations === []) { return []; } + // the members overriding the declarations might not be analysed + $isOnlyFilesAnalysis = $node->isOnlyFilesAnalysis(); + $usedByOverridingMembers = []; + $declaredByOverridingMembers = []; + $memberCounts = []; foreach ($node->get(TypeUsedInOverridingMemberCollector::class) as $usages) { foreach ($usages as $usage) { foreach ($usage['used'] as $i) { $usedByOverridingMembers[$usage['kind']][$usage['class']][$usage['member']][$usage['slot']][$i] = true; } + if ($usage['declared'] === null) { + continue; + } + [$phpDocMembers, $nativeMembers, $memberCount] = $usage['declared']; + $memberCounts[$usage['kind']][$usage['class']][$usage['member']][$usage['slot']][$memberCount] = true; + foreach ([$phpDocMembers, $nativeMembers] as $j => $declaredMembers) { + foreach ($declaredMembers as $i) { + $declaredByOverridingMembers[$usage['kind']][$usage['class']][$usage['member']][$usage['slot']][$j][$i] = true; + } + } } } $errors = []; foreach ($declarations as $file => $fileDeclarations) { foreach ($fileDeclarations as $declaration) { - $usedMembers = $usedByOverridingMembers[$declaration['kind']][$declaration['class']][$declaration['member']][$declaration['slot']] ?? []; + // in an open project only what the member uses itself is reported, as without collected data + if ($isOnlyFilesAnalysis && !$declaration['ownOnly']) { + continue; + } + + $key = [$declaration['kind'], $declaration['class'], $declaration['member'], $declaration['slot']]; + $usedByOverriding = $usedByOverridingMembers[$key[0]][$key[1]][$key[2]][$key[3]] ?? []; + $usedMembers = $declaration['ownOnly'] ? [] : $usedByOverriding; foreach ($declaration['used'] as $i) { $usedMembers[$i] = true; } @@ -57,6 +87,19 @@ public function processNode(Node $node, Scope $scope): array continue; } + // the fix keeps what the overriding members return and declare, the overridden type stays as wide as they need + $fix = null; + $phpDocKept = []; + // an overriding member that saw another type of the member, the indexes of its members do not match + $counts = $memberCounts[$key[0]][$key[1]][$key[2]][$key[3]] ?? []; + $isConsistent = $counts === [] || array_keys($counts) === [count($declaration['errors'])]; + if ($this->fixer !== null && $declaration['fix'] !== null && !$isOnlyFilesAnalysis && $isConsistent) { + $declaredByOverriding = $declaredByOverridingMembers[$key[0]][$key[1]][$key[2]][$key[3]] ?? []; + $phpDocKept = $usedMembers + $usedByOverriding + ($declaredByOverriding[0] ?? []); + $nativeKept = $phpDocKept + ($declaredByOverriding[1] ?? []); + $fix = $this->fixer->createFix($declaration['fix']['plan'], array_keys($phpDocKept), array_keys($nativeKept)); + } + $usedMembersTip = null; if ($declaration['usedMembersTip'] !== null) { $usedMemberDescriptions = []; @@ -87,6 +130,14 @@ public function processNode(Node $node, Scope $scope): array if ($tip !== null) { $builder->tip($tip); } + // a member an overriding member still needs is not removed, it is fixed in a later round + if ($fix !== null && !isset($phpDocKept[$i])) { + $builder->fixNode( + TooWideReturnTypeFixer::createFixedNode($declaration['fix']['startPos'], $declaration['fix']['endPos']), + $fix, + $declaration['file'] ?? $file, + ); + } $errors[] = $builder->build(); } diff --git a/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php index e0a5d00b981..dbdeb21c0c9 100644 --- a/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php +++ b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php @@ -10,7 +10,7 @@ /** * Not registered as a collector, the data is emitted with OverridableMemberHelper::emitUsage(). * - * @implements Collector}> + * @implements Collector, declared: array{list, list, int}|null}> */ final class TypeUsedInOverridingMemberCollector implements Collector { diff --git a/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php index 132c5c7e8f3..c87bf58fce8 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php +++ b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php @@ -30,7 +30,7 @@ protected function getRule(): Rule return new CompositeRule([ new TooWideFunctionReturnTypehintRule($check), new TooWideMethodReturnTypehintRule($this->checkProtectedAndPublicMethods, $check, $overridableMemberHelper), - new TooWideTypeInOverridableMemberRule(), + new TooWideTypeInOverridableMemberRule(self::getContainer()->getByType(TooWideReturnTypeFixer::class)), ]); } @@ -55,6 +55,12 @@ public function testMethodsInOpenProjectCheckingProtectedAndPublic(): void $this->fix(__DIR__ . '/data/fix-too-wide-return-type/methods.php', $this->getFixedFile('methods-open-project-checked')); } + public function testMethodsInClosedProject(): void + { + $this->projectType = 'closed'; + $this->fix(__DIR__ . '/data/fix-too-wide-return-type/methods.php', $this->getFixedFile('methods-closed-project')); + } + private function getFixedFile(string $name): string { return __DIR__ . '/data/fix-too-wide-return-type/' . $name . '-' . static::getPhpVersionSuffix() . '.php.fixed'; diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed new file mode 100644 index 00000000000..f15ca26f82e --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -0,0 +1,180 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): ?Animal + { + return new Dog(); + } + +} + +class GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): ?Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed new file mode 100644 index 00000000000..cacd088f8d8 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -0,0 +1,180 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} + +class GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): Animal + { + return new Dog(); + } + + public function getWithoutTag(): Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed new file mode 100644 index 00000000000..cacd088f8d8 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -0,0 +1,180 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog|null + */ + public function narrowedByChild() + { + return new Dog(); + } + + /** + * @return Dog + */ + public function childDeclaresCat() + { + return new Dog(); + } + + public function nativeNullable(): ?Dog + { + return null; + } + +} + +class NativeParent +{ + + public function get(): ?Animal + { + return null; + } + +} + +final class FinalChildOfNativeParent extends NativeParent +{ + + /** + * @return Dog + */ + public function get(): Animal + { + return new Dog(); + } + +} + +class GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): Animal + { + return new Dog(); + } + + public function getWithoutTag(): Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed index cda2a068c92..6e19dce893a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -73,7 +73,7 @@ class ChildClass extends ParentClass } /** - * @return Dog|Cat + * @return Dog */ public function childDeclaresCat() { @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): ?Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed index f409fb2518f..6d84e6c63f8 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -73,7 +73,7 @@ class ChildClass extends ParentClass } /** - * @return Dog|Cat + * @return Dog */ public function childDeclaresCat() { @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed index f409fb2518f..6d84e6c63f8 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -73,7 +73,7 @@ class ChildClass extends ParentClass } /** - * @return Dog|Cat + * @return Dog */ public function childDeclaresCat() { @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed index cda2a068c92..99f8c24bd2c 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): ?Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed index f409fb2518f..a22c42c7422 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed index f409fb2518f..a22c42c7422 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -109,3 +109,72 @@ final class FinalChildOfNativeParent extends NativeParent } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php index f41e926e1ad..2031e064663 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -109,3 +109,72 @@ public function get(): ?Animal } } + +class GrandParent +{ + + /** + * @return Dog|Cat|int|null + */ + public function chain() + { + return 1; + } + +} + +class MiddleClass extends GrandParent +{ + + /** + * @return Dog|int|null + */ + public function chain() + { + return new Dog(); + } + +} + +final class LeafClass extends MiddleClass +{ + + /** + * @return Dog|int + */ + public function chain() + { + return 2; + } + +} + +class NativeUnionParent +{ + + public function get(): ?Animal + { + return new Dog(); + } + + public function getWithoutTag(): ?Animal + { + return new Dog(); + } + +} + +final class NativeUnionChild extends NativeUnionParent +{ + + public function get(): ?Animal + { + return new Cat(); + } + + public function getWithoutTag(): Animal + { + return new Cat(); + } + +} From 023d09707e41d36df93a6a716688185c9c90d2ca Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 20:38:53 +0000 Subject: [PATCH 19/24] Narrow native return types only by the native types of the returned values A PHPDoc type is not checked at runtime: a getter of a property documented as string that a setter assigns null to, or a value narrowed by an inline @var tag, can still be null. The @return tags are narrowed by the PHPDoc types, the native type keeps the members the native types of the returned values need. --- .../OverridableMemberHelper.php | 4 +- .../TooWideMethodReturnTypehintRule.php | 7 ++- .../TooWideTypehints/TooWideTypeCheck.php | 49 +++++++++++++++++-- ...ooWideTypeInOverridableMemberCollector.php | 2 +- .../TooWideTypeInOverridableMemberRule.php | 3 ++ .../functions-php73.php.fixed | 39 +++++++++++++++ .../functions-php74.php.fixed | 39 +++++++++++++++ .../functions-php82.php.fixed | 39 +++++++++++++++ .../fix-too-wide-return-type/functions.php | 39 +++++++++++++++ .../methods-closed-project-php73.php.fixed | 28 +++++++++++ .../methods-closed-project-php74.php.fixed | 28 +++++++++++ .../methods-closed-project-php82.php.fixed | 28 +++++++++++ ...thods-open-project-checked-php73.php.fixed | 28 +++++++++++ ...thods-open-project-checked-php74.php.fixed | 28 +++++++++++ ...thods-open-project-checked-php82.php.fixed | 28 +++++++++++ .../methods-open-project-php73.php.fixed | 28 +++++++++++ .../methods-open-project-php74.php.fixed | 28 +++++++++++ .../methods-open-project-php82.php.fixed | 28 +++++++++++ .../data/fix-too-wide-return-type/methods.php | 28 +++++++++++ 19 files changed, 494 insertions(+), 7 deletions(-) diff --git a/src/Rules/TooWideTypehints/OverridableMemberHelper.php b/src/Rules/TooWideTypehints/OverridableMemberHelper.php index 3333dcdd19a..716e8aa0b78 100644 --- a/src/Rules/TooWideTypehints/OverridableMemberHelper.php +++ b/src/Rules/TooWideTypehints/OverridableMemberHelper.php @@ -127,7 +127,7 @@ public function findOverriddenPropertyHooks(ClassReflection $classReflection, st * @param string|null $usedMembersTip tip for the errors with %s for the used members, or void * @param list $memberDescriptions the members of the type in $usedMembersTip * @param bool $ownOnly whether only the members the member uses itself are not reported, in an open project - * @param array{plan: Plan, startPos: int, endPos: int}|null $fix the plan of the fix of the return type, see TooWideReturnTypeFixer + * @param array{plan: Plan, nativeUsed: list, startPos: int, endPos: int}|null $fix the plan of the fix of the return type, see TooWideReturnTypeFixer */ public function emitDeclaration( Scope&CollectedDataEmitter $scope, @@ -175,7 +175,7 @@ public function emitDeclaration( * * @param list $usedMembers * @param list $memberErrors - * @param array{plan: Plan, startPos: int, endPos: int}|null $fix + * @param array{plan: Plan, nativeUsed: list, startPos: int, endPos: int}|null $fix */ public function emitReturnTypeDeclaration( Scope&CollectedDataEmitter $scope, diff --git a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php index b47f6fe74de..2fe20005226 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php @@ -149,7 +149,12 @@ private function emitDeclaration(MethodReturnStatementsNode $node, Scope&Collect $result[0], $result[1], $ownOnly, - $plan !== null ? ['plan' => $plan, 'startPos' => $classMethod->getStartFilePos(), 'endPos' => $classMethod->getEndFilePos()] : null, + $plan !== null ? [ + 'plan' => $plan, + 'nativeUsed' => $this->check->getNativelyUsedReturnTypeMembers($node, $method, $result[0], $scope), + 'startPos' => $classMethod->getStartFilePos(), + 'endPos' => $classMethod->getEndFilePos(), + ] : null, ); } diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 0a455032154..538ccbda533 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -29,6 +29,8 @@ use PHPStan\Type\VerbosityLevel; use PHPStan\Type\VoidType; use function array_keys; +use function array_unique; +use function array_values; use function count; use function in_array; use function lcfirst; @@ -343,7 +345,7 @@ private function createReturnTypeFix( } $usedMembers = $this->getUsedMembers($declaredType, $members, $returnType, false); - $fix = $this->returnTypeFixer->createFix($plan, $usedMembers, $usedMembers); + $fix = $this->returnTypeFixer->createFix($plan, $usedMembers, $this->getNativelyUsedMembers($node, $declaredType, $members, $usedMembers)); if ($fix === null) { return null; } @@ -472,10 +474,51 @@ private static function getOverlappingMembers(array $members, Type $type): array return $overlapping; } + /** + * getNativelyUsedMembers() of a method whose errors createOverridableReturnTypeErrors() returned. + * + * @param list $usedMembers + * @return list + */ + public function getNativelyUsedReturnTypeMembers(MethodReturnStatementsNode $node, ExtendedParametersAcceptor $methodVariant, array $usedMembers, Scope $scope): array + { + [$declaredType, $native] = $this->getCheckedReturnType($methodVariant); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return $usedMembers; + } + + return $this->getNativelyUsedMembers($node, $declaredType, $members, $usedMembers); + } + + /** + * The members of the return type the native type of the function has to keep: those the native types + * of the returned values overlap, like null of a property documented as string, and $usedMembers. + * A PHPDoc type is not checked at runtime, a native return type narrowed by it could throw a TypeError. + * + * @param list $members + * @param list $usedMembers + * @return list + */ + private function getNativelyUsedMembers( + MethodReturnStatementsNode|FunctionReturnStatementsNode $node, + Type $declaredType, + array $members, + array $usedMembers, + ): array + { + $nativeReturnType = $this->getReturnedType($node, true); + if ($nativeReturnType === null) { + return $usedMembers; + } + + return array_values(array_unique([...$usedMembers, ...$this->getUsedMembers($declaredType, $members, $nativeReturnType, false)])); + } + /** * Null when the function is a generator or it does not return anything. */ - private function getReturnedType(MethodReturnStatementsNode|FunctionReturnStatementsNode $node): ?Type + private function getReturnedType(MethodReturnStatementsNode|FunctionReturnStatementsNode $node, bool $native = false): ?Type { $statementResult = $node->getStatementResult(); if ($statementResult->hasYield()) { @@ -495,7 +538,7 @@ private function getReturnedType(MethodReturnStatementsNode|FunctionReturnStatem continue; } - $returnTypes[] = $returnStatement->getScope()->getType($returnNode->expr); + $returnTypes[] = $native ? $returnStatement->getScope()->getNativeType($returnNode->expr) : $returnStatement->getScope()->getType($returnNode->expr); } if (!$statementResult->isAlwaysTerminating()) { diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php index b1aac0fdc9b..446ebccc352 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php @@ -12,7 +12,7 @@ * * Not registered as a collector, the data is emitted with OverridableMemberHelper::emitDeclaration(). * - * @implements Collector, errors: list, usedMembersTip: string|null, memberDescriptions: list, ownOnly: bool, fix: array{plan: Plan, startPos: int, endPos: int}|null}> + * @implements Collector, errors: list, usedMembersTip: string|null, memberDescriptions: list, ownOnly: bool, fix: array{plan: Plan, nativeUsed: list, startPos: int, endPos: int}|null}> */ final class TooWideTypeInOverridableMemberCollector implements Collector { diff --git a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php index 7f5808d77f4..c1f065fd038 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php @@ -97,6 +97,9 @@ public function processNode(Node $node, Scope $scope): array $declaredByOverriding = $declaredByOverridingMembers[$key[0]][$key[1]][$key[2]][$key[3]] ?? []; $phpDocKept = $usedMembers + $usedByOverriding + ($declaredByOverriding[0] ?? []); $nativeKept = $phpDocKept + ($declaredByOverriding[1] ?? []); + foreach ($declaration['fix']['nativeUsed'] as $i) { + $nativeKept[$i] = true; + } $fix = $this->fixer->createFix($declaration['fix']['plan'], array_keys($phpDocKept), array_keys($nativeKept)); } diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed index 83048f8a058..6ef901fead2 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed @@ -58,3 +58,42 @@ function nullablePhpDocAndNative(): string { return 'foo'; } + +final class PhpDocProperty +{ + + /** @var string */ + private $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + + /** + * @return string + */ + public function getNameWithTag(): ?string + { + return $this->name; + } + + public function getNameNatively(): string + { + return (string) $this->name; + } + +} + +function inlineVarTag(): ?\stdClass +{ + /** @var \stdClass $object */ + $object = rand(0, 1) ? new \stdClass() : null; + + return $object; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed index 83048f8a058..6ef901fead2 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed @@ -58,3 +58,42 @@ function nullablePhpDocAndNative(): string { return 'foo'; } + +final class PhpDocProperty +{ + + /** @var string */ + private $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + + /** + * @return string + */ + public function getNameWithTag(): ?string + { + return $this->name; + } + + public function getNameNatively(): string + { + return (string) $this->name; + } + +} + +function inlineVarTag(): ?\stdClass +{ + /** @var \stdClass $object */ + $object = rand(0, 1) ? new \stdClass() : null; + + return $object; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed index 4357534dacf..cf7c1567ce6 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed @@ -58,3 +58,42 @@ function nullablePhpDocAndNative(): string { return 'foo'; } + +final class PhpDocProperty +{ + + /** @var string */ + private $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + + /** + * @return string + */ + public function getNameWithTag(): ?string + { + return $this->name; + } + + public function getNameNatively(): string + { + return (string) $this->name; + } + +} + +function inlineVarTag(): ?\stdClass +{ + /** @var \stdClass $object */ + $object = rand(0, 1) ? new \stdClass() : null; + + return $object; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php index a7880874019..df8df2ca1f3 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php @@ -58,3 +58,42 @@ function nullablePhpDocAndNative(): ?string { return 'foo'; } + +final class PhpDocProperty +{ + + /** @var string */ + private $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + + /** + * @return string|null + */ + public function getNameWithTag(): ?string + { + return $this->name; + } + + public function getNameNatively(): ?string + { + return (string) $this->name; + } + +} + +function inlineVarTag(): ?\stdClass +{ + /** @var \stdClass $object */ + $object = rand(0, 1) ? new \stdClass() : null; + + return $object; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed index f15ca26f82e..4bcea0fe425 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): ?string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed index cacd088f8d8..b2cadddaddb 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed index cacd088f8d8..b2cadddaddb 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed index 6e19dce893a..adcd2f34b67 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): ?string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed index 6d84e6c63f8..447c5095074 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed index 6d84e6c63f8..447c5095074 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed index 99f8c24bd2c..e20886d6e4f 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): ?string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed index a22c42c7422..b9228f1df1b 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed index a22c42c7422..b9228f1df1b 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -178,3 +178,31 @@ final class NativeUnionChild extends NativeUnionParent } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): string + { + return 'child'; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php index 2031e064663..abbbf4c461d 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -178,3 +178,31 @@ public function getWithoutTag(): Animal } } + +class PhpDocPropertyParent +{ + + /** @var string */ + protected $name = 'foo'; + + public function setName(?string $name): void + { + $this->name = $name; + } + + public function getName(): ?string + { + return $this->name; + } + +} + +final class PhpDocPropertyChild extends PhpDocPropertyParent +{ + + public function getName(): ?string + { + return 'child'; + } + +} From ffd63c0e48c285e882e32c0f9ec1d4b9e3e9955c Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 20:50:19 +0000 Subject: [PATCH 20/24] Do not fix too-wide return types the returned values are not a subtype of When a value is accepted only by coercion, like int by float, or the declared type does not accept it at all, removing the members the rule reports as unused can break the function, for example ?float became null in a function returning 1. --- .../TooWideTypehints/TooWideTypeCheck.php | 15 +++++++++++++ .../functions-php73.php.fixed | 21 +++++++++++++++++++ .../functions-php74.php.fixed | 21 +++++++++++++++++++ .../functions-php82.php.fixed | 21 +++++++++++++++++++ .../fix-too-wide-return-type/functions.php | 21 +++++++++++++++++++ 5 files changed, 99 insertions(+) diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 538ccbda533..68d054f8008 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -282,6 +282,21 @@ public function createReturnTypeFixPlan( return null; } + // when the declared type accepts a returned value only by coercion, like int by float, or does not accept it at all, + // it is not known which member the value belongs to and removing members could break the function + $functionReturnType = TypeUtils::resolveLateResolvableTypes(TypehintHelper::decideType($nativeFunctionReturnType, $phpDocFunctionReturnType)); + $returnType = $this->getReturnedType($node); + if ($returnType !== null) { + $returnedNull = !(new VoidType())->isSuperTypeOf($returnType)->no(); + $returnType = TypeCombinator::remove($returnType, new VoidType()); + if ($returnedNull) { + $returnType = TypeCombinator::addNull($returnType); + } + if (!$functionReturnType->isSuperTypeOf($returnType)->yes()) { + return null; + } + } + if ($node instanceof MethodReturnStatementsNode) { $functionNode = $node->getClassMethod(); $classReflection = $node->getClassReflection(); diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed index 6ef901fead2..0fed6126473 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed @@ -97,3 +97,24 @@ function inlineVarTag(): ?\stdClass return $object; } + +function coercedToFloat(bool $b): ?float +{ + if ($b) { + return 1; + } + + return null; +} + +/** + * @return \DateTimeImmutable|\Exception|null + */ +function returnsUndeclaredType(bool $b) +{ + if ($b) { + return new \stdClass(); + } + + return null; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed index 6ef901fead2..0fed6126473 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed @@ -97,3 +97,24 @@ function inlineVarTag(): ?\stdClass return $object; } + +function coercedToFloat(bool $b): ?float +{ + if ($b) { + return 1; + } + + return null; +} + +/** + * @return \DateTimeImmutable|\Exception|null + */ +function returnsUndeclaredType(bool $b) +{ + if ($b) { + return new \stdClass(); + } + + return null; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed index cf7c1567ce6..7eac93446e1 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed @@ -97,3 +97,24 @@ function inlineVarTag(): ?\stdClass return $object; } + +function coercedToFloat(bool $b): ?float +{ + if ($b) { + return 1; + } + + return null; +} + +/** + * @return \DateTimeImmutable|\Exception|null + */ +function returnsUndeclaredType(bool $b) +{ + if ($b) { + return new \stdClass(); + } + + return null; +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php index df8df2ca1f3..2dd3564118b 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php @@ -97,3 +97,24 @@ function inlineVarTag(): ?\stdClass return $object; } + +function coercedToFloat(bool $b): ?float +{ + if ($b) { + return 1; + } + + return null; +} + +/** + * @return \DateTimeImmutable|\Exception|null + */ +function returnsUndeclaredType(bool $b) +{ + if ($b) { + return new \stdClass(); + } + + return null; +} From c51227f81a9ef9ab8300135888ebfa8229f579eb Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 20:50:19 +0000 Subject: [PATCH 21/24] Do not fix too-wide return types of methods incompatible with their parents When the return type of the overridden method does not accept the return type of the overriding one, narrowing the overriding method can make the incompatibility reported. --- .../TooWideReturnTypeFixer.php | 18 +++++++++++++ .../TooWideTypehints/TooWideTypeCheck.php | 3 +++ .../methods-closed-project-php73.php.fixed | 26 +++++++++++++++++++ .../methods-closed-project-php74.php.fixed | 26 +++++++++++++++++++ .../methods-closed-project-php82.php.fixed | 26 +++++++++++++++++++ ...thods-open-project-checked-php73.php.fixed | 26 +++++++++++++++++++ ...thods-open-project-checked-php74.php.fixed | 26 +++++++++++++++++++ ...thods-open-project-checked-php82.php.fixed | 26 +++++++++++++++++++ .../methods-open-project-php73.php.fixed | 26 +++++++++++++++++++ .../methods-open-project-php74.php.fixed | 26 +++++++++++++++++++ .../methods-open-project-php82.php.fixed | 26 +++++++++++++++++++ .../data/fix-too-wide-return-type/methods.php | 26 +++++++++++++++++++ 12 files changed, 281 insertions(+) diff --git a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php index c8ef959eead..299223e7f50 100644 --- a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php +++ b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php @@ -31,6 +31,7 @@ use PHPStan\Type\NullType; use PHPStan\Type\ParserNodeTypeToPHPStanType; use PHPStan\Type\Type; +use PHPStan\Type\TypeUtils; use function array_diff; use function array_intersect; use function array_key_exists; @@ -115,6 +116,23 @@ public function canNarrowNativeReturnType(?ClassReflection $classReflection, str return true; } + /** + * Whether the return types of the methods the method overrides accept its return type. + * When they do not, the hierarchy is already inconsistent and narrowing the method could make it incompatible. + */ + public function isCompatibleWithParentMethods(ClassReflection $classReflection, string $functionName, Type $returnType): bool + { + foreach ($this->parentMethodHelper->collectParentMethods($functionName, $classReflection) as [$parentMethod]) { + foreach ($parentMethod->getVariants() as $variant) { + if (!TypeUtils::resolveLateResolvableTypes($variant->getReturnType())->isSuperTypeOf($returnType)->yes()) { + return false; + } + } + } + + return true; + } + /** * @param list $members the members of the checked return type * @param bool $checkedPhpDoc whether the checked return type is the PHPDoc one diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 68d054f8008..7b7ebcbb7ab 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -301,6 +301,9 @@ public function createReturnTypeFixPlan( $functionNode = $node->getClassMethod(); $classReflection = $node->getClassReflection(); $functionName = $functionNode->name->toString(); + if (!$this->returnTypeFixer->isCompatibleWithParentMethods($classReflection, $functionName, $functionReturnType)) { + return null; + } } else { $functionNode = $node->getFunction(); $classReflection = null; diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed index 4bcea0fe425..fdd1ddf8724 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed index b2cadddaddb..35cb5ff8af6 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed index b2cadddaddb..35cb5ff8af6 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed index adcd2f34b67..5f3ef210011 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed index 447c5095074..b1c4e2dd815 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed index 447c5095074..b1c4e2dd815 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed index e20886d6e4f..2edf3b7bf4a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed index b9228f1df1b..b68812ecf30 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed index b9228f1df1b..b68812ecf30 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -206,3 +206,29 @@ final class PhpDocPropertyChild extends PhpDocPropertyParent } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php index abbbf4c461d..44a0374321a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -206,3 +206,29 @@ public function getName(): ?string } } + +class IncompatibleParent +{ + + /** + * @return \Exception|\DateTimeImmutable + */ + public function get() + { + return rand(0, 1) ? new \Exception() : new \DateTimeImmutable(); + } + +} + +class IncompatibleChild extends IncompatibleParent +{ + + /** + * @return array|\Exception + */ + public function get() + { + return []; + } + +} From c7a53607f143a80622f40a6472ee221754f2b039 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 21:00:53 +0000 Subject: [PATCH 22/24] Report never-returned null of overriding methods in a closed project Like the check without collected data, only nested types of a method overriding another one keep null. A method implementing Iterator::current() with @return Foo|null that never returns null was reported in an open project checking protected and public methods, but not in a closed project. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../TooWideMethodReturnTypehintRule.php | 1 + .../methods-closed-project-php73.php.fixed | 27 +++++++++++++++++-- .../methods-closed-project-php74.php.fixed | 27 +++++++++++++++++-- .../methods-closed-project-php82.php.fixed | 27 +++++++++++++++++-- ...thods-open-project-checked-php73.php.fixed | 23 ++++++++++++++++ ...thods-open-project-checked-php74.php.fixed | 23 ++++++++++++++++ ...thods-open-project-checked-php82.php.fixed | 23 ++++++++++++++++ .../methods-open-project-php73.php.fixed | 23 ++++++++++++++++ .../methods-open-project-php74.php.fixed | 23 ++++++++++++++++ .../methods-open-project-php82.php.fixed | 23 ++++++++++++++++ .../data/fix-too-wide-return-type/methods.php | 23 ++++++++++++++++ 11 files changed, 237 insertions(+), 6 deletions(-) diff --git a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php index 2fe20005226..e23b340d95c 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php @@ -83,6 +83,7 @@ public function processNode(Node $node, Scope&CollectedDataEmitter $scope): arra $functionDescription, $checkDescendantClass, $scope, + false, ); if ($result !== null) { $this->emitDeclaration($node, $scope, $result, false); diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed index fdd1ddf8724..e9f71d14775 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -127,7 +127,7 @@ class MiddleClass extends GrandParent { /** - * @return Dog|int|null + * @return Dog|int */ public function chain() { @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed index 35cb5ff8af6..24ea3949dbf 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -127,7 +127,7 @@ class MiddleClass extends GrandParent { /** - * @return Dog|int|null + * @return Dog|int */ public function chain() { @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed index 35cb5ff8af6..24ea3949dbf 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -65,7 +65,7 @@ class ChildClass extends ParentClass { /** - * @return Dog|null + * @return Dog */ public function narrowedByChild() { @@ -127,7 +127,7 @@ class MiddleClass extends GrandParent { /** - * @return Dog|int|null + * @return Dog|int */ public function chain() { @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed index 5f3ef210011..9b67a448ba3 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed index b1c4e2dd815..2a69fa7954b 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed index b1c4e2dd815..2a69fa7954b 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed index 2edf3b7bf4a..df916b01d49 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed index b68812ecf30..6bd7ccf885a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed index b68812ecf30..6bd7ccf885a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -232,3 +232,26 @@ class IncompatibleChild extends IncompatibleParent } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php index 44a0374321a..37cd18015fa 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -232,3 +232,26 @@ public function get() } } + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} From a8edab35d680bab8b41bd27a299e976b85cf6111 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 21:05:54 +0000 Subject: [PATCH 23/24] Fix too-wide return types of methods whose parents accept what they return The parent of a method implementing Iterator::current() with @return Foo|null returns Foo, which does not accept the declared type but accepts the narrowed one. Only a parent return type that does not overlap with the returned type blocks the fix. Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../TooWideReturnTypeFixer.php | 9 ++-- .../TooWideTypehints/TooWideTypeCheck.php | 2 +- .../methods-closed-project-php73.php.fixed | 44 +++++++++++++++++++ .../methods-closed-project-php74.php.fixed | 44 +++++++++++++++++++ .../methods-closed-project-php82.php.fixed | 44 +++++++++++++++++++ ...thods-open-project-checked-php73.php.fixed | 44 +++++++++++++++++++ ...thods-open-project-checked-php74.php.fixed | 44 +++++++++++++++++++ ...thods-open-project-checked-php82.php.fixed | 44 +++++++++++++++++++ .../methods-open-project-php73.php.fixed | 44 +++++++++++++++++++ .../methods-open-project-php74.php.fixed | 44 +++++++++++++++++++ .../methods-open-project-php82.php.fixed | 44 +++++++++++++++++++ .../data/fix-too-wide-return-type/methods.php | 44 +++++++++++++++++++ 12 files changed, 446 insertions(+), 5 deletions(-) diff --git a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php index 299223e7f50..741413ab71c 100644 --- a/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php +++ b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php @@ -117,14 +117,15 @@ public function canNarrowNativeReturnType(?ClassReflection $classReflection, str } /** - * Whether the return types of the methods the method overrides accept its return type. - * When they do not, the hierarchy is already inconsistent and narrowing the method could make it incompatible. + * Whether the return types of the methods the method overrides overlap with the type it returns. + * A narrowed return type keeps what the method returns, so when they do not overlap, + * narrowing the method would make it incompatible with its parents. */ - public function isCompatibleWithParentMethods(ClassReflection $classReflection, string $functionName, Type $returnType): bool + public function isCompatibleWithParentMethods(ClassReflection $classReflection, string $functionName, Type $returnedType): bool { foreach ($this->parentMethodHelper->collectParentMethods($functionName, $classReflection) as [$parentMethod]) { foreach ($parentMethod->getVariants() as $variant) { - if (!TypeUtils::resolveLateResolvableTypes($variant->getReturnType())->isSuperTypeOf($returnType)->yes()) { + if (TypeUtils::resolveLateResolvableTypes($variant->getReturnType())->isSuperTypeOf($returnedType)->no()) { return false; } } diff --git a/src/Rules/TooWideTypehints/TooWideTypeCheck.php b/src/Rules/TooWideTypehints/TooWideTypeCheck.php index 7b7ebcbb7ab..51b66f65947 100644 --- a/src/Rules/TooWideTypehints/TooWideTypeCheck.php +++ b/src/Rules/TooWideTypehints/TooWideTypeCheck.php @@ -301,7 +301,7 @@ public function createReturnTypeFixPlan( $functionNode = $node->getClassMethod(); $classReflection = $node->getClassReflection(); $functionName = $functionNode->name->toString(); - if (!$this->returnTypeFixer->isCompatibleWithParentMethods($classReflection, $functionName, $functionReturnType)) { + if ($returnType !== null && !$this->returnTypeFixer->isCompatibleWithParentMethods($classReflection, $functionName, $returnType)) { return null; } } else { diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed index e9f71d14775..eadd154d89c 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed index 24ea3949dbf..12456ccafc1 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed index 24ea3949dbf..12456ccafc1 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed index 9b67a448ba3..626c20e7263 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed index 2a69fa7954b..65e02a5a3c2 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed index 2a69fa7954b..65e02a5a3c2 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed index df916b01d49..501e7f3dfb7 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass|null + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed index 6bd7ccf885a..cc57cbda87d 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass|null + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed index 6bd7ccf885a..cc57cbda87d 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -255,3 +255,47 @@ class ImplementsCurrent implements HasCurrent } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass|null + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php index 37cd18015fa..59a2c17f40a 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -255,3 +255,47 @@ public function current() } } + +/** + * @implements \Iterator + */ +class GenericParentWithoutNull implements \Iterator +{ + + /** @var list<\stdClass> */ + private $items = []; + + /** @var int */ + private $i = 0; + + /** + * @return \stdClass|null + */ + #[\ReturnTypeWillChange] + public function current() + { + return $this->items[$this->i]; + } + + #[\ReturnTypeWillChange] + public function key() + { + return $this->i; + } + + public function next(): void + { + $this->i++; + } + + public function rewind(): void + { + $this->i = 0; + } + + public function valid(): bool + { + return isset($this->items[$this->i]); + } + +} From 15add591942e7e389e20c9bb7125c7396e7da5e9 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Tue, 1 Dec 2026 21:34:34 +0000 Subject: [PATCH 24/24] Run the native union type fixture of too-wide fixes only on PHP 8.0+ Amp-Thread-ID: https://ampcode.com/threads/T-01a22c96-9e21-771f-9a29-4627539ba301 --- .../Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php | 2 ++ .../functions-native-union-php73.php.fixed | 2 +- .../functions-native-union-php74.php.fixed | 2 +- .../functions-native-union-php82.php.fixed | 2 +- .../data/fix-too-wide-return-type/functions-native-union.php | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php index c87bf58fce8..fc5e1054d90 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php +++ b/tests/PHPStan/Rules/TooWideTypehints/TooWideReturnTypeFixTestCase.php @@ -5,6 +5,7 @@ use PHPStan\Rules\Rule; use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; +use PHPUnit\Framework\Attributes\RequiresPhp; /** * Fixes of too-wide return types for the PHP version set by the configuration file of each subclass. @@ -39,6 +40,7 @@ public function testFunctions(): void $this->fix(__DIR__ . '/data/fix-too-wide-return-type/functions.php', $this->getFixedFile('functions')); } + #[RequiresPhp('>= 8.0.0')] public function testFunctionsWithNativeUnionTypes(): void { $this->fix(__DIR__ . '/data/fix-too-wide-return-type/functions-native-union.php', $this->getFixedFile('functions-native-union')); diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed index 137cd5a4fb9..60b8dd159fa 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed @@ -1,4 +1,4 @@ -= 8.0 namespace FixTooWideReturnTypeFunctionNativeUnion; diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed index 137cd5a4fb9..60b8dd159fa 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed @@ -1,4 +1,4 @@ -= 8.0 namespace FixTooWideReturnTypeFunctionNativeUnion; diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed index 137cd5a4fb9..60b8dd159fa 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed @@ -1,4 +1,4 @@ -= 8.0 namespace FixTooWideReturnTypeFunctionNativeUnion; diff --git a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php index 74fc31c396f..365bd36b931 100644 --- a/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php @@ -1,4 +1,4 @@ -= 8.0 namespace FixTooWideReturnTypeFunctionNativeUnion;