diff --git a/Makefile b/Makefile index 32ae3cd51f9..618fd33268d 100644 --- a/Makefile +++ b/Makefile @@ -20,6 +20,8 @@ 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/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/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 2a9f2e621ae..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 @@ -97,6 +98,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..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() @@ -94,6 +95,7 @@ parametersSchema: checkPhpDocMethodSignatures: bool() checkExtraArguments: bool() checkMissingTypehints: bool() + projectType: anyOf('open', 'closed') checkTooWideParameterOutInProtectedAndPublicMethods: bool() checkTooWideReturnTypesInProtectedAndPublicMethods: bool() checkTooWideThrowTypesInProtectedAndPublicMethods: bool() 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/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/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/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); 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/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/Functions/MissingFunctionReturnTypehintRule.php b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php index 09c276a9b49..de49bbccde2 100644 --- a/src/Rules/Functions/MissingFunctionReturnTypehintRule.php +++ b/src/Rules/Functions/MissingFunctionReturnTypehintRule.php @@ -6,7 +6,9 @@ use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; -use PHPStan\Node\InFunctionNode; +use PHPStan\Node\FunctionReturnStatementsNode; +use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Rules\MissingReturnTypeFixer; use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; @@ -15,7 +17,7 @@ use function sprintf; /** - * @implements Rule + * @implements Rule */ #[RegisteredRule(level: 6)] #[ValidatesStubFiles] @@ -24,13 +26,14 @@ final class MissingFunctionReturnTypehintRule implements Rule public function __construct( private MissingTypehintCheck $missingTypehintCheck, + private MissingReturnTypeFixer $fixer, ) { } public function getNodeType(): string { - return InFunctionNode::class; + return FunctionReturnStatementsNode::class; } public function processNode(Node $node, Scope $scope): array @@ -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->returnType !== null ? $node->getFunctionReflection()->getNativeReturnType() : null, $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 new file mode 100644 index 00000000000..cd09a81478c --- /dev/null +++ b/src/Rules/Methods/MissingImplementedMethodReturnTypehintRule.php @@ -0,0 +1,195 @@ + + */ +#[RegisteredRule(level: 6)] +#[ValidatesStubFiles] +final class MissingImplementedMethodReturnTypehintRule implements Rule +{ + + public function __construct( + private MissingTypehintCheck $missingTypehintCheck, + private MissingReturnTypeFixer $fixer, + private OverridableMemberHelper $overridableMemberHelper, + ) + { + } + + public function getNodeType(): string + { + return MethodReturnStatementsNode::class; + } + + public function processNode(Node $node, Scope&CollectedDataEmitter $scope): array + { + if ( + $scope->isInTrait() + && $node->getClassMethod()->getAttribute('originalTraitMethodName') === '__construct' + ) { + return []; + } + + $methodReflection = $node->getMethodReflection(); + $returnType = $methodReflection->getReturnType(); + + $errors = []; + if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + $errors[] = [ + sprintf( + 'Method %s::%s() has no return type specified.', + $methodReflection->getDeclaringClass()->getDisplayName(), + $methodReflection->getName(), + ), + '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()); + } + } + + $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)); + + $ruleErrors = []; + $fixedNatively = false; + if (!$isDeferred) { + $fix = null; + if (!$isInTrait && !$isOverridable) { + $type = $this->fixer->combine([$returnInfo]); + if ($type !== null) { + $fix = $this->fixer->createFix($classMethod->returnType !== null ? $methodReflection->getNativeReturnType() : null, $type, $type, $classReflection, $parentReturnType, $parentNativeReturnType); + } + } + + $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), + '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()) ?? false : null, + 'fixedNatively' => $fixedNatively, + 'errors' => $isDeferred ? $errors : [], + 'file' => $file, + 'fileDescription' => $scope->getFileDescription(), + 'line' => $node->getStartLine(), + 'startPos' => $classMethod->getStartFilePos(), + 'endPos' => $classMethod->getEndFilePos(), + ]); + } + + 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 $builder; + } + +} diff --git a/src/Rules/Methods/MissingMethodReturnTypehintRule.php b/src/Rules/Methods/MissingMethodReturnTypehintRule.php index ea40b006706..020de9efa5e 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()) { @@ -43,7 +51,16 @@ 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 (!$hasBody) { + $this->emitOverridingMethodWithoutBody($node, $scope); + } if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + if ($hasBody) { + return []; + } + return [ RuleErrorBuilder::message(sprintf( 'Method %s::%s() has no return type specified.', @@ -54,16 +71,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]) { @@ -90,4 +109,46 @@ 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, + 'parentReturnType' => null, + 'parentNativeReturnType' => 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 new file mode 100644 index 00000000000..db8aade6112 --- /dev/null +++ b/src/Rules/MissingReturnTypeCollector.php @@ -0,0 +1,46 @@ +, 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 +{ + + 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..75542c8a81c --- /dev/null +++ b/src/Rules/MissingReturnTypeFixRule.php @@ -0,0 +1,331 @@ +, 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)] +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, + ) + { + } + + 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) { + $builder->fixNode(self::createFunctionNode($record), $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]; + if ($record['nativeReturnType'] === false) { + return null; + } + + $traitMethod = $record['traitMethod']; + // the classes using a trait might not be analysed + if ($traitMethod !== null && $this->isOnlyFilesAnalysis) { + return null; + } + + $returnInfos = []; + $nativeReturnInfos = []; + $parentReturnTypes = []; + $parentNativeReturnTypes = []; + $overridingNativeReturnTypes = []; + 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 || $contextRecord['nativeReturnType'] === 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; + } + + $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; + } + + if ($overridingRecord['nativeReturnType'] === false) { + 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 ($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, + // 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; + } + + $nativeReturnInfos[] = $overridingReturnInfo; + } + } + + if ($nativeReturnInfos === []) { + return null; + } + + $phpDocType = $this->fixer->combine($returnInfos); + $nativeSourceType = $this->fixer->combine($nativeReturnInfos); + if ($phpDocType === null || $nativeSourceType === null) { + return null; + } + + $classReflection = $record['class'] !== null && $this->reflectionProvider->hasClass($record['class']) + ? $this->reflectionProvider->getClass($record['class']) + : null; + + return $this->fixer->createFix( + $this->resolve($record['nativeReturnType'], $record['class']), + $phpDocType, + $nativeSourceType, + $classReflection, + count($parentReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentReturnTypes), + count($parentNativeReturnTypes) === 0 ? null : TypeCombinator::intersect(...$parentNativeReturnTypes), + $overridingNativeReturnTypes, + ); + } + + 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'], + 'returnsValue' => $record['returnInfo']['returnsValue'], + ]; + } + } + + 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, 'returnsValue' => false]; + } + + return ['values' => $nativeType, 'void' => false, 'returnsValue' => false]; + } + + private function resolve(?string $type, ?string $className): ?Type + { + if ($type === null) { + return null; + } + + return $this->typeStringResolver->resolve($type, new NameScope(null, [], $className)); + } + + /** + * 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 static function createFunctionNode(array $record): ClassMethod + { + return new ClassMethod('fixed', attributes: ['startFilePos' => $record['startPos'], 'endFilePos' => $record['endPos']]); + } + +} diff --git a/src/Rules/MissingReturnTypeFixer.php b/src/Rules/MissingReturnTypeFixer.php new file mode 100644 index 00000000000..1f01f9976dd --- /dev/null +++ b/src/Rules/MissingReturnTypeFixer.php @@ -0,0 +1,635 @@ +hasTemplateOrLateResolvableType()) { + return null; + } + + return $this->printer->print($type->toPhpDocNode()); + } + + /** + * @param ReturnInfo $returnInfo + * @return array{values: string, void: bool, returnsValue: bool}|null + */ + public function serializeReturnInfo(array $returnInfo): ?array + { + $values = $this->serialize($returnInfo['values']); + if ($values === null) { + return null; + } + + return ['values' => $values, 'void' => $returnInfo['void'], 'returnsValue' => $returnInfo['returnsValue']]; + } + + public function isEnabled(): bool + { + return $this->enabled; + } + + public function supportsReturnCovariance(): bool + { + return $this->phpVersion->supportsReturnCovariance(); + } + + /** + * @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) : TemplateTypeHelper::removeFinalByKeywordOverrides(TypeCombinator::union(...$values)), + 'void' => $void || !$node->getStatementResult()->isAlwaysTerminating(), + 'returnsValue' => count($values) > 0, + ]; + 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( + TemplateTypeHelper::removeFinalByKeywordOverrides(TypeCombinator::union(...$keyTypes)), + TemplateTypeHelper::removeFinalByKeywordOverrides(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, + 'returnsValue' => 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. + * 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 + */ + 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; + } + + if ($type instanceof NeverType) { + return new VoidType(); + } + + 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 + * 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. + * + * 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( + ?Type $declaredNativeType, + Type $phpDocType, + Type $nativeSourceType, + ?ClassReflection $classReflection, + ?Type $parentReturnType = null, + ?Type $parentNativeReturnType = null, + array $overridingNativeReturnTypes = [], + ): ?callable + { + $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; + } + + $supportsReturnCovariance = $this->phpVersion->supportsReturnCovariance(); + $nativeTypeNode = null; + $nativeType = $declaredNativeType; + if ($nativeType === null) { + // 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; + } + $nativeType = ParserNodeTypeToPHPStanType::resolve($nativeTypeNode, $classReflection); + } + + if ($nativeType->isSuperTypeOf($phpDocType)->no()) { + return null; + } + + if ($parentNativeReturnType !== null && !$parentNativeReturnType->isSuperTypeOf($nativeType)->yes()) { + 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 + $addsTag = !$nativeType->equals($returnedPhpDocType); + + $phpDocEditor = $this->phpDocEditor; + + return static function (ClassMethod|Function_ $node) use ($nativeTypeNode, $phpDocTypeNode, $addsTag, $phpDocEditor): ClassMethod|Function_ { + if ($nativeTypeNode !== null) { + $node->returnType = $nativeTypeNode; + } + + if (!$addsTag && $node->getDocComment() === null) { + return $node; + } + + $phpDocEditor->edit($node, static function (PhpDocAstNode $phpDocNode) use ($phpDocTypeNode, $addsTag): PhpDocAstNode { + if (!$phpDocNode instanceof PhpDocNode) { + 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; + } + + 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, ''))]); + } + + $phpDocNode->children = $children; + + return $phpDocNode; + }); + + return $node; + }; + } + + /** + * 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. + * + * 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 + { + 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) { + $isWithoutMixed = false; + return $type; + } + + // 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) { + $isWithoutMixed = $isWithoutMixed && $this->isWithoutMixed($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 $isWithoutMixed; + } + + /** + * 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 + * and intersection types before PHP 8.1. + */ + private function findCommonParentType(Type $type): ?Type + { + if (!$type->isObject()->yes()) { + return null; + } + + $classNames = $type->getObjectClassNames(); + 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; + } + + return $candidateType; + } + + return null; + } + +} diff --git a/src/Rules/TooWideTypehints/OverridableMemberHelper.php b/src/Rules/TooWideTypehints/OverridableMemberHelper.php new file mode 100644 index 00000000000..716e8aa0b78 --- /dev/null +++ b/src/Rules/TooWideTypehints/OverridableMemberHelper.php @@ -0,0 +1,219 @@ +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 + * @param bool $ownOnly whether only the members the member uses itself are not reported, in an open project + * @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, + string $kind, + string $className, + string $memberKey, + int $slot, + int $line, + array $usedMembers, + array $memberErrors, + ?string $usedMembersTip = null, + array $memberDescriptions = [], + bool $ownOnly = false, + ?array $fix = null, + ): 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, + '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, nativeUsed: list, 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, + string $kind, + string $overriddenClassName, + string $overriddenMemberKey, + int $slot, + array $usedMembers, + ?array $declaredMembers = null, + ): void + { + $scope->emitCollectedData(TypeUsedInOverridingMemberCollector::class, [ + 'kind' => $kind, + 'class' => $overriddenClassName, + 'member' => $overriddenMemberKey, + 'slot' => $slot, + 'used' => $usedMembers, + 'declared' => $declaredMembers, + ]); + } + +} 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..e23b340d95c 100644 --- a/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php +++ b/src/Rules/TooWideTypehints/TooWideMethodReturnTypehintRule.php @@ -3,11 +3,14 @@ namespace PHPStan\Rules\TooWideTypehints; use PhpParser\Node; +use PHPStan\Analyser\CollectedDataEmitter; use PHPStan\Analyser\Scope; 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; /** @@ -21,6 +24,7 @@ public function __construct( #[AutowiredParameter(ref: '%checkTooWideReturnTypesInProtectedAndPublicMethods%')] private bool $checkProtectedAndPublicMethods, private TooWideTypeCheck $check, + private OverridableMemberHelper $overridableMemberHelper, ) { } @@ -30,15 +34,64 @@ 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(); + $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, + $overriddenMethod->getDeclaringClass()->getName(), + OverridableMemberHelper::getMethodKey($overriddenMethod->getName()), + 0, + $usedMembers, + $declaredMembers, + ); + } + } + 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, + false, + ); + if ($result !== null) { + $this->emitDeclaration($node, $scope, $result, false); + } + + return []; + } + if (!$this->checkProtectedAndPublicMethods) { return []; } @@ -46,6 +99,28 @@ public function processNode(Node $node, Scope $scope): array 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 []; } } @@ -53,14 +128,49 @@ 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, ); } + /** + * @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, + 'nativeUsed' => $this->check->getNativelyUsedReturnTypeMembers($node, $method, $result[0], $scope), + '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/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/TooWideReturnTypeFixer.php b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php new file mode 100644 index 00000000000..741413ab71c --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideReturnTypeFixer.php @@ -0,0 +1,505 @@ +, 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; + } + + /** + * 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 $returnedType): bool + { + foreach ($this->parentMethodHelper->collectParentMethods($functionName, $classReflection) as [$parentMethod]) { + foreach ($parentMethod->getVariants() as $variant) { + if (TypeUtils::resolveLateResolvableTypes($variant->getReturnType())->isSuperTypeOf($returnedType)->no()) { + 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 $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 $phpDocKept, array $nativeKept): ?callable + { + $changes = false; + $nativeDecisions = null; + $nativeOverlaps = null; + if ($plan['native'] !== null) { + $nativeDecisions = $this->decide($plan['native'], $nativeKept, $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, $phpDocKept, 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 307a3ec5280..51b66f65947 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; @@ -11,6 +13,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,12 +28,18 @@ use PHPStan\Type\UnionType; 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; use function sprintf; use function strtolower; +/** + * @phpstan-import-type Plan from TooWideReturnTypeFixer + */ #[AutowiredService] final class TooWideTypeCheck { @@ -41,6 +50,7 @@ public function __construct( private bool $reportTooWideBool, #[AutowiredParameter(ref: '%featureToggles.reportNestedTooWideType%')] private bool $reportNestedTooWideType, + private ?TooWideReturnTypeFixer $returnTypeFixer = null, ) { } @@ -170,66 +180,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)); @@ -244,6 +203,7 @@ public function checkFunctionReturnType( $node->getStartLine(), 'return', null, + $this->createReturnTypeFix($node, $nativeFunctionReturnType, $phpDocFunctionReturnType, $returnType, $scope), ); } @@ -285,12 +245,397 @@ 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; + } + + // 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(); + $functionName = $functionNode->name->toString(); + if ($returnType !== null && !$this->returnTypeFixer->isCompatibleWithParentMethods($classReflection, $functionName, $returnType)) { + return null; + } + } 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; + } + + $usedMembers = $this->getUsedMembers($declaredType, $members, $returnType, false); + $fix = $this->returnTypeFixer->createFix($plan, $usedMembers, $this->getNativelyUsedMembers($node, $declaredType, $members, $usedMembers)); + 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 + * 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, + ?bool $usedMembersCheckDescendantClass = null, + ): ?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, $usedMembersCheckDescendantClass ?? $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); + } + + /** + * The members of the return type of an overridden method, as createOverridableReturnTypeErrors() lists them, + * 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 array{list, list, int}|null + */ + public function getDeclaredOverriddenReturnTypeMembers( + ExtendedParametersAcceptor $overriddenMethodVariant, + ExtendedParametersAcceptor $overridingMethodVariant, + bool $hasOwnReturnTag, + Scope $scope, + ): ?array + { + [$declaredType, $native] = $this->getCheckedReturnType($overriddenMethodVariant); + $members = $this->getRemovableMembers($declaredType, $scope, $native); + if ($members === null) { + return null; + } + + // 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 []; + } + + $type = TypeUtils::resolveLateResolvableTypes($type); + $overlapping = []; + foreach ($members as $i => $member) { + if ($member->isSuperTypeOf($type)->no()) { + continue; + } + + $overlapping[] = $i; + } + + 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, bool $native = false): ?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[] = $native ? $returnStatement->getScope()->getNativeType($returnNode->expr) : $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 + { + 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 [$nativeType, 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,8 +693,58 @@ 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 + * @param array{ClassMethod|Function_, callable(ClassMethod|Function_): (ClassMethod|Function_)}|null $fix * @return list */ private function createErrors( @@ -360,6 +755,7 @@ private function createErrors( int $startLine, string $identifierPart, ?string $tip, + ?array $fix = null, ): array { if ($originalType->isBoolean()->yes()) { @@ -373,6 +769,9 @@ private function createErrors( if ($tip !== null) { $errorBuilder->tip($tip); } + if ($fix !== null) { + $errorBuilder->fixNode($fix[0], $fix[1]); + } return [$errorBuilder->build()]; } @@ -394,6 +793,9 @@ private function createErrors( if ($tip !== null) { $errorBuilder->tip($tip); } + if ($fix !== null) { + $errorBuilder->fixNode($fix[0], $fix[1]); + } $messages[] = $errorBuilder->build(); } @@ -435,76 +837,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..446ebccc352 --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberCollector.php @@ -0,0 +1,30 @@ +, 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 +{ + + 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..c1f065fd038 --- /dev/null +++ b/src/Rules/TooWideTypehints/TooWideTypeInOverridableMemberRule.php @@ -0,0 +1,153 @@ + + */ +#[RegisteredRule(level: 4)] +final class TooWideTypeInOverridableMemberRule implements Rule +{ + + public function __construct( + private ?TooWideReturnTypeFixer $fixer = null, + ) + { + } + + public function getNodeType(): string + { + return CollectedDataNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $declarations = $node->get(TooWideTypeInOverridableMemberCollector::class); + 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) { + // 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; + } + + if (count($usedMembers) >= count($declaration['errors'])) { + 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] ?? []); + foreach ($declaration['fix']['nativeUsed'] as $i) { + $nativeKept[$i] = true; + } + $fix = $this->fixer->createFix($declaration['fix']['plan'], array_keys($phpDocKept), array_keys($nativeKept)); + } + + $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); + } + // 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(); + } + } + } + + return $errors; + } + +} diff --git a/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php new file mode 100644 index 00000000000..dbdeb21c0c9 --- /dev/null +++ b/src/Rules/TooWideTypehints/TypeUsedInOverridingMemberCollector.php @@ -0,0 +1,28 @@ +, declared: array{list, list, int}|null}> + */ +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/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/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/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/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 new file mode 100644 index 00000000000..50d97933b3b --- /dev/null +++ b/tests/PHPStan/Rules/Methods/MissingImplementedMethodReturnTypehintRuleTest.php @@ -0,0 +1,117 @@ + + */ +class MissingImplementedMethodReturnTypehintRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + return new MissingImplementedMethodReturnTypehintRule( + new MissingTypehintCheck(true, [], true), + self::getContainer()->getByType(MissingReturnTypeFixer::class), + new OverridableMemberHelper('open'), + ); + } + + 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..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 @@ -25,23 +31,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 +43,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 +92,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')] 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 @@ + + */ +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(), + ), + ]; + 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/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/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(self::getContainer()->getByType(TooWideReturnTypeFixer::class)), + ]); + } + + 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')); + } + + 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')); + } + + 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'; + } + + 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..60b8dd159fa --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php73.php.fixed @@ -0,0 +1,17 @@ += 8.0 + +namespace FixTooWideReturnTypeFunctionNativeUnion; + +function nativeUnion(): int +{ + return 1; +} + +function alwaysFalse(): bool|int +{ + if (rand(0, 1)) { + return 1; + } + + return false; +} 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 new file mode 100644 index 00000000000..60b8dd159fa --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php74.php.fixed @@ -0,0 +1,17 @@ += 8.0 + +namespace FixTooWideReturnTypeFunctionNativeUnion; + +function nativeUnion(): int +{ + return 1; +} + +function alwaysFalse(): bool|int +{ + if (rand(0, 1)) { + return 1; + } + + return false; +} 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 new file mode 100644 index 00000000000..60b8dd159fa --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union-php82.php.fixed @@ -0,0 +1,17 @@ += 8.0 + +namespace FixTooWideReturnTypeFunctionNativeUnion; + +function nativeUnion(): int +{ + return 1; +} + +function alwaysFalse(): bool|int +{ + if (rand(0, 1)) { + return 1; + } + + return false; +} 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 new file mode 100644 index 00000000000..365bd36b931 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-native-union.php @@ -0,0 +1,17 @@ += 8.0 + +namespace FixTooWideReturnTypeFunctionNativeUnion; + +function nativeUnion(): string|int|null +{ + return 1; +} + +function alwaysFalse(): bool|int +{ + if (rand(0, 1)) { + return 1; + } + + return false; +} 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 new file mode 100644 index 00000000000..0fed6126473 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php73.php.fixed @@ -0,0 +1,120 @@ +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; +} + +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 new file mode 100644 index 00000000000..0fed6126473 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php74.php.fixed @@ -0,0 +1,120 @@ +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; +} + +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 new file mode 100644 index 00000000000..7eac93446e1 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions-php82.php.fixed @@ -0,0 +1,120 @@ +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; +} + +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 new file mode 100644 index 00000000000..2dd3564118b --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/functions.php @@ -0,0 +1,120 @@ +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; +} + +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/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..eadd154d89c --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php73.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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 + */ + 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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..12456ccafc1 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php74.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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 + */ + 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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..12456ccafc1 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-closed-project-php82.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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 + */ + 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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..626c20e7263 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php73.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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|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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..65e02a5a3c2 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php74.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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|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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..65e02a5a3c2 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-checked-php82.php.fixed @@ -0,0 +1,301 @@ +privateMethod(); + return new Dog(); + } + +} + +class ChildClass extends ParentClass +{ + + /** + * @return Dog + */ + 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|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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..501e7f3dfb7 --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php73.php.fixed @@ -0,0 +1,301 @@ +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(); + } + +} + +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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..cc57cbda87d --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php74.php.fixed @@ -0,0 +1,301 @@ +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(); + } + +} + +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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..cc57cbda87d --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods-open-project-php82.php.fixed @@ -0,0 +1,301 @@ +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(); + } + +} + +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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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 new file mode 100644 index 00000000000..59a2c17f40a --- /dev/null +++ b/tests/PHPStan/Rules/TooWideTypehints/data/fix-too-wide-return-type/methods.php @@ -0,0 +1,301 @@ +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(); + } + +} + +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(); + } + +} + +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'; + } + +} + +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 []; + } + +} + +interface HasCurrent +{ + + /** + * @return mixed + */ + public function current(); + +} + +class ImplementsCurrent implements HasCurrent +{ + + /** + * @return \stdClass|null + */ + public function current() + { + return new \stdClass(); + } + +} + +/** + * @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/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; + } + +} diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type-php73.neon b/tests/PHPStan/Rules/data/fix-missing-return-type-php73.neon new file mode 100644 index 00000000000..49ea62cacfd --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php73.neon @@ -0,0 +1,6 @@ +parameters: + phpVersion: 70300 + featureToggles: + fixMissingReturnTypes: true + fixer: + preferSelf: true 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..9b45e935338 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php74.neon @@ -0,0 +1,6 @@ +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 new file mode 100644 index 00000000000..7667fd50889 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php80.neon @@ -0,0 +1,6 @@ +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 new file mode 100644 index 00000000000..b8f56e641e6 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php81.neon @@ -0,0 +1,6 @@ +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 new file mode 100644 index 00000000000..84236a942f8 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type-php82.neon @@ -0,0 +1,6 @@ +parameters: + phpVersion: 80200 + featureToggles: + fixMissingReturnTypes: true + fixer: + preferSelf: true diff --git a/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php73.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php73.php.fixed new file mode 100644 index 00000000000..58f41a3326c --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php73.php.fixed @@ -0,0 +1,359 @@ + 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-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed new file mode 100644 index 00000000000..58f41a3326c --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php74.php.fixed @@ -0,0 +1,359 @@ + 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-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed new file mode 100644 index 00000000000..db2d5c629cf --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php80.php.fixed @@ -0,0 +1,359 @@ + 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): \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; +} + +/** + * @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-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed new file mode 100644 index 00000000000..ee4576597b0 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php81.php.fixed @@ -0,0 +1,353 @@ + 1]; +} + +/** + * @return \Generator + */ +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; +} + +/** + * @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 { + }; +} + +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 { + }]; +} + +/** + * @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-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed new file mode 100644 index 00000000000..a8adaef90df --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions-php82.php.fixed @@ -0,0 +1,350 @@ + 1]; +} + +/** + * @return \Generator + */ +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; +} + +/** + * @return never + */ +function declaredNever() +{ + throw new \Exception(); +} + +function returnsNever() +{ + return declaredNever(); +} + +/** + * @return void + */ +function declaredVoid() +{ +} + +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 { + }]; +} + +/** + * @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/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..2dfa7b5e9ce --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/functions.php @@ -0,0 +1,307 @@ + 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; +} + +/** + * @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() +{ + 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 { + }]; +} + +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; +} + +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()]; +} + +/** + * @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/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 new file mode 100644 index 00000000000..4082f60c5a3 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php74.php.fixed @@ -0,0 +1,349 @@ + $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; + } + + /** + * @return Cat|Dog + */ + public function createAnimal(): Animal + { + 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 +{ + + 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 +{ + + /** + * @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..10b3a9be94b --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php80.php.fixed @@ -0,0 +1,340 @@ + $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(): int|string + { + return 1; + } + + public function createAnimal(): Dog|Cat + { + 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; + } + + 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 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 +{ + + 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 +{ + + /** + * @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..d55758e994e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php81.php.fixed @@ -0,0 +1,337 @@ + $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(): int|string + { + return 1; + } + + public function createAnimal(): Dog|Cat + { + 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; + } + + 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 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 +{ + + 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 +{ + + /** + * @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..d55758e994e --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-closed-project-php82.php.fixed @@ -0,0 +1,337 @@ + $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(): int|string + { + return 1; + } + + public function createAnimal(): Dog|Cat + { + 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; + } + + 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 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 +{ + + 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 +{ + + /** + * @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-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 new file mode 100644 index 00000000000..782704956ac --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php74.php.fixed @@ -0,0 +1,337 @@ + $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 +{ + + 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 +{ + + /** + * @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-php80.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed new file mode 100644 index 00000000000..77bc6cc78aa --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php80.php.fixed @@ -0,0 +1,334 @@ + $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 +{ + + 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 +{ + + /** + * @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-php81.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed new file mode 100644 index 00000000000..8d445f6e047 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php81.php.fixed @@ -0,0 +1,331 @@ + $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 +{ + + 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 +{ + + /** + * @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-php82.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed new file mode 100644 index 00000000000..8d445f6e047 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods-open-project-php82.php.fixed @@ -0,0 +1,331 @@ + $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 +{ + + 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 +{ + + /** + * @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.php b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php new file mode 100644 index 00000000000..5c30eeb187b --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/methods.php @@ -0,0 +1,333 @@ + $ints + */ + public static function createMany(array $ints) + { + return array_map(static fn (int $int) => new self(), $ints); + } + +} + +class ParentClass +{ + + private function privateMethod() + { + 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 +{ + + /** + * @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()]; + } + +} + +final class ChildWithDescribedReturn extends DeclaringParent +{ + + /** + * Returns the item. + * + * @return array|Dog The dog. + */ + public function getItem() + { + return new Dog(); + } + +} + +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 +{ + + /** + * @return array + */ + public function items(int $i, string $s): array + { + return [$i]; + } + +} + +final class IterableChild extends IterableParent +{ + + /** + * @return array + */ + public function items(int $i, string $s): array + { + return [$s]; + } + +} 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-closed-project-php74.php.fixed b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-project-php74.php.fixed new file mode 100644 index 00000000000..b2f5745ad84 --- /dev/null +++ b/tests/PHPStan/Rules/data/fix-missing-return-type/traits-closed-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{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-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..3f579c8edd2 --- /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{int, int} + */ + 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..3f579c8edd2 --- /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{int, int} + */ + 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..3f579c8edd2 --- /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{int, int} + */ + 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-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; + } + +} 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..71cd06f18b0 --- /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{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; + } + +} 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..f9b477cb4d6 --- /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{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; + } + +} 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..f9b477cb4d6 --- /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{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; + } + +} 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..f9b477cb4d6 --- /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{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; + } + +} 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; + } + +} 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/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 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,