diff --git a/config/set/throws-tag.php b/config/set/throws-tag.php new file mode 100644 index 00000000000..6cab9f3893a --- /dev/null +++ b/config/set/throws-tag.php @@ -0,0 +1,15 @@ +withPreparedSets(throwsTag: true) and add yours with + * ->withConfiguredRule(AddThrowsTagRector::class, [LogicException::class]). + */ +return static function (RectorConfig $rectorConfig): void { + $rectorConfig->rules([AddThrowsTagRector::class]); +}; diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/AddThrowsTagRectorTest.php b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/AddThrowsTagRectorTest.php new file mode 100644 index 00000000000..c577763674a --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/AddThrowsTagRectorTest.php @@ -0,0 +1,28 @@ +doTestFile($filePath); + } + + public static function provideData(): Iterator + { + return self::yieldFilesFromDirectory(__DIR__ . '/Fixture'); + } + + public function provideConfigFilePath(): string + { + return __DIR__ . '/config/configured_rule.php'; + } +} diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/basic_transformation.php.inc b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/basic_transformation.php.inc new file mode 100644 index 00000000000..54a056ec665 --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/basic_transformation.php.inc @@ -0,0 +1,26 @@ +fail(); + } + + /** + * @throws \RuntimeException + */ + private function fail(): void + { + throw new \RuntimeException('boom'); + } +} +----- +fail(); + } + + /** + * @throws \RuntimeException + */ + private function fail(): void + { + throw new \RuntimeException('boom'); + } +} diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_constructor.php.inc b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_constructor.php.inc new file mode 100644 index 00000000000..7dbca068eb1 --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_constructor.php.inc @@ -0,0 +1,48 @@ +callerProvider->get(); + } +} +----- +callerProvider->get(); + } +} diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_static_call.php.inc b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_static_call.php.inc new file mode 100644 index 00000000000..ab4590222ea --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/propagated_from_static_call.php.inc @@ -0,0 +1,48 @@ +work(); + } catch (\RuntimeException | \JsonException $exception) { + throw $exception; + } + } + + /** + * @throws \RuntimeException + * @throws \JsonException + */ + private function work(): void + { + throw new \RuntimeException('boom'); + } +} +----- +work(); + } catch (\RuntimeException | \JsonException $exception) { + throw $exception; + } + } + + /** + * @throws \RuntimeException + * @throws \JsonException + */ + private function work(): void + { + throw new \RuntimeException('boom'); + } +} diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_already_documented.php.inc b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_already_documented.php.inc new file mode 100644 index 00000000000..a34496b0ae4 --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_already_documented.php.inc @@ -0,0 +1,14 @@ +fail(...); + } + + public static function staticCallable(): \Closure + { + return self::create(...); + } + + /** + * @throws \RuntimeException + */ + public static function create(): self + { + throw new \RuntimeException('boom'); + } +} diff --git a/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_throws_inherited_from_interface.php.inc b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_throws_inherited_from_interface.php.inc new file mode 100644 index 00000000000..6eeee22b869 --- /dev/null +++ b/rules-tests/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector/Fixture/skip_throws_inherited_from_interface.php.inc @@ -0,0 +1,20 @@ +ruleWithConfiguration( + AddThrowsTagRector::class, + [ + 'LogicException', + 'ValueError', + ], + ); +}; diff --git a/rules/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector.php b/rules/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector.php new file mode 100644 index 00000000000..03def644e66 --- /dev/null +++ b/rules/TypeDeclarationDocblocks/Rector/ClassMethod/AddThrowsTagRector.php @@ -0,0 +1,327 @@ + exceptions (and their subclasses) that are never documented + */ + private array $uncheckedExceptions = []; + + public function __construct( + private readonly PhpDocInfoFactory $phpDocInfoFactory, + private readonly DocBlockUpdater $docBlockUpdater, + private readonly StaticTypeMapper $staticTypeMapper, + private readonly ReflectionResolver $reflectionResolver, + ) {} + + public function getRuleDefinition(): RuleDefinition + { + return new RuleDefinition( + 'Add a @throws tag for every checked exception a method lets escape', + [ + new CodeSample( + <<<'PHP' + final class SomeClass + { + public function run(): void + { + throw new \RuntimeException('boom'); + } + } + PHP + , + <<<'PHP' + final class SomeClass + { + /** + * @throws \RuntimeException + */ + public function run(): void + { + throw new \RuntimeException('boom'); + } + } + PHP + , + ), + ], + ); + } + + /** + * @return array> + */ + public function getNodeTypes(): array + { + return [ClassMethod::class]; + } + + /** + * @param ClassMethod $node + */ + public function refactor(Node $node): ?Node + { + $escapingClassNames = $this->escapingClassNames((array) $node->stmts); + if ($escapingClassNames === []) { + return null; + } + + $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node); + $hasChanged = false; + foreach ($escapingClassNames as $className) { + if ($this->isDocumented($phpDocInfo, $node, $className)) { + continue; + } + + $this->addThrowsTag($phpDocInfo, $className); + $hasChanged = true; + } + + if (! $hasChanged) { + return null; + } + + $this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($node); + + return $node; + } + + /** + * @param list $configuration the unchecked exceptions + */ + public function configure(array $configuration): void + { + Assert::allString($configuration); + + $this->uncheckedExceptions = $configuration; + } + + /** + * @param array $statements + * + * @return list + */ + private function escapingClassNames(array $statements): array + { + return $this->withoutInstancesOf( + array_values(array_unique($this->thrownBySubNode($statements))), + $this->uncheckedExceptions, + ); + } + + /** + * Walks a node, never entering a nested closure or class: what they throw is not the method's. + * + * @return list + */ + private function thrownBy(Node $node): array + { + if ($node instanceof Closure || $node instanceof ArrowFunction || $node instanceof ClassLike) { + return []; + } + + if ($node instanceof TryCatch) { + return $this->thrownByTry($node); + } + + $classNames = $this->thrownByNode($node); + foreach ($node->getSubNodeNames() as $subNodeName) { + $classNames = [...$classNames, ...$this->thrownBySubNode($node->{$subNodeName})]; + } + + return $classNames; + } + + /** + * @return list + */ + private function thrownBySubNode(mixed $subNode): array + { + if ($subNode instanceof Node) { + return $this->thrownBy($subNode); + } + + if (! is_array($subNode)) { + return []; + } + + $classNames = []; + foreach ($subNode as $item) { + $classNames = [...$classNames, ...$this->thrownBySubNode($item)]; + } + + return $classNames; + } + + /** + * Only the `try` body is covered by its catches: what a `catch` or `finally` throws leaves the method. + * + * @return list + */ + private function thrownByTry(TryCatch $try): array + { + $escapingFromBody = $this->withoutInstancesOf( + $this->thrownBySubNode($try->stmts), + $this->caughtClassNames($try), + ); + + return [ + ...$escapingFromBody, + ...$this->thrownBySubNode($try->catches), + ...$this->thrownBySubNode($try->finally), + ]; + } + + /** + * @return list + */ + private function caughtClassNames(TryCatch $try): array + { + $caughtClassNames = []; + foreach ($try->catches as $catch) { + foreach ($catch->types as $type) { + $caughtClassName = $this->getName($type); + if ($caughtClassName !== null) { + $caughtClassNames[] = $caughtClassName; + } + } + } + + return $caughtClassNames; + } + + /** + * What the node itself throws: a `throw`, or what a called method or constructor declares in its own + * `@throws` (the rule is meant to be run again to climb a call chain one level at a time). + * + * @return list + */ + private function thrownByNode(Node $node): array + { + if ($node instanceof Throw_) { + return $this->getType($node->expr)->getObjectClassNames(); + } + + if ($node instanceof MethodCall || $node instanceof StaticCall || $node instanceof New_) { + return $this->declaredByCallee($node); + } + + return []; + } + + /** + * @return list + */ + private function declaredByCallee(MethodCall|StaticCall|New_ $call): array + { + if (! $call instanceof New_ && ($call->isFirstClassCallable() || ! $call->name instanceof Identifier)) { + return []; + } + + $methodReflection = match (true) { + $call instanceof MethodCall => $this->reflectionResolver->resolveMethodReflectionFromMethodCall($call), + $call instanceof StaticCall => $this->reflectionResolver->resolveMethodReflectionFromStaticCall($call), + default => $this->reflectionResolver->resolveMethodReflectionFromNew($call), + }; + + return $methodReflection?->getThrowType()?->getObjectClassNames() ?? []; + } + + private function addThrowsTag(PhpDocInfo $phpDocInfo, string $className): void + { + $phpDocInfo->addPhpDocTagNode( + new PhpDocTagNode('@throws', new ThrowsTagValueNode(new IdentifierTypeNode('\\' . $className), '')), + ); + } + + /** + * @param list $classNames + * @param list $excludedClassNames + * + * @return list + */ + private function withoutInstancesOf(array $classNames, array $excludedClassNames): array + { + return array_values(array_filter( + $classNames, + fn (string $className): bool => ! $this->isInstanceOfAny(new ObjectType($className), $excludedClassNames), + )); + } + + /** + * @param list $classNames + */ + private function isInstanceOfAny(ObjectType $type, array $classNames): bool + { + return array_any($classNames, fn (string $className): bool => new ObjectType($className)->isSuperTypeOf($type)->yes()); + } + + private function isDocumented(PhpDocInfo $phpDocInfo, ClassMethod $classMethod, string $className): bool + { + foreach ($phpDocInfo->getTagsByName('throws') as $throwsTag) { + if (! $throwsTag->value instanceof ThrowsTagValueNode) { + continue; + } + + $documentedType = $this->staticTypeMapper->mapPHPStanPhpDocTypeNodeToPHPStanType( + $throwsTag->value->type, + $classMethod, + ); + if ($documentedType->isSuperTypeOf(new ObjectType($className))->yes()) { + return true; + } + } + + return $this->isInheritedThrowType($classMethod, $className); + } + + /** + * An overriding method inherits the `@throws` of the method it implements or overrides. + */ + private function isInheritedThrowType(ClassMethod $classMethod, string $className): bool + { + $scope = $classMethod->getAttribute(AttributeKey::SCOPE); + if (! $scope instanceof Scope) { + return false; + } + + $throwType = $this->reflectionResolver->resolveMethodReflectionFromClassMethod($classMethod, $scope)?->getThrowType(); + + return $throwType?->isSuperTypeOf(new ObjectType($className))->yes() ?? false; + } +} diff --git a/src/Configuration/RectorConfigBuilder.php b/src/Configuration/RectorConfigBuilder.php index 473a1215bac..a279cfab834 100644 --- a/src/Configuration/RectorConfigBuilder.php +++ b/src/Configuration/RectorConfigBuilder.php @@ -628,6 +628,7 @@ public function withPreparedSets( bool $doctrineCodeQuality = false, bool $symfonyCodeQuality = false, bool $symfonyConfigs = false, + bool $throwsTag = false, ): self { Notifier::notifyNotSuitableMethodForPHP74(__METHOD__); @@ -655,6 +656,7 @@ public function withPreparedSets( SetList::PRIVATIZATION => $privatization, SetList::NAMED_ARGS => $namedArgs, SetList::CARBON => $carbon, + SetList::THROWS_TAG => $throwsTag, SetList::RECTOR_PRESET => $rectorPreset, PHPUnitSetList::PHPUNIT_CODE_QUALITY => $phpunitCodeQuality, PHPUnitSetList::PHPUNIT_NARROW_ASSERTS => $phpunitNarrowAsserts, diff --git a/src/Set/ValueObject/SetList.php b/src/Set/ValueObject/SetList.php index 03a20d9e7ad..8e4328846b8 100644 --- a/src/Set/ValueObject/SetList.php +++ b/src/Set/ValueObject/SetList.php @@ -34,6 +34,11 @@ final class SetList public const string BEHAT_ANNOTATIONS_TO_ATTRIBUTES = __DIR__ . '/../../../config/set/behat-annotations-to-attributes.php'; + /** + * Opt-in: ->withPreparedSets(throwsTag: true), plus the project's unchecked exceptions via ->withConfiguredRule(AddThrowsTagRector::class, [...]) + */ + public const string THROWS_TAG = __DIR__ . '/../../../config/set/throws-tag.php'; + /** * All PHP version rules in one set; each rule gates itself by PHP version at runtime */