|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Exceptions; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Node\MethodReturnStatementsNode; |
| 8 | +use PHPStan\Reflection\MethodReflection; |
| 9 | +use PHPStan\Rules\Rule; |
| 10 | +use PHPStan\Rules\RuleErrorBuilder; |
| 11 | +use PHPStan\Type\TypeUtils; |
| 12 | +use PHPStan\Type\TypeWithClassName; |
| 13 | +use PHPStan\Type\VerbosityLevel; |
| 14 | +use PHPStan\Type\VoidType; |
| 15 | + |
| 16 | +/** |
| 17 | + * @implements Rule<MethodReturnStatementsNode> |
| 18 | + */ |
| 19 | +class ThrowsVoidMethodWithExplicitThrowPointRule implements Rule |
| 20 | +{ |
| 21 | + |
| 22 | + private ExceptionTypeResolver $exceptionTypeResolver; |
| 23 | + |
| 24 | + private bool $missingCheckedExceptionInThrows; |
| 25 | + |
| 26 | + public function __construct( |
| 27 | + ExceptionTypeResolver $exceptionTypeResolver, |
| 28 | + bool $missingCheckedExceptionInThrows |
| 29 | + ) |
| 30 | + { |
| 31 | + $this->exceptionTypeResolver = $exceptionTypeResolver; |
| 32 | + $this->missingCheckedExceptionInThrows = $missingCheckedExceptionInThrows; |
| 33 | + } |
| 34 | + |
| 35 | + public function getNodeType(): string |
| 36 | + { |
| 37 | + return MethodReturnStatementsNode::class; |
| 38 | + } |
| 39 | + |
| 40 | + public function processNode(Node $node, Scope $scope): array |
| 41 | + { |
| 42 | + if ($this->missingCheckedExceptionInThrows) { |
| 43 | + return []; |
| 44 | + } |
| 45 | + |
| 46 | + $statementResult = $node->getStatementResult(); |
| 47 | + $methodReflection = $scope->getFunction(); |
| 48 | + if (!$methodReflection instanceof MethodReflection) { |
| 49 | + throw new \PHPStan\ShouldNotHappenException(); |
| 50 | + } |
| 51 | + |
| 52 | + if (!$methodReflection->getThrowType() instanceof VoidType) { |
| 53 | + return []; |
| 54 | + } |
| 55 | + |
| 56 | + $errors = []; |
| 57 | + foreach ($statementResult->getThrowPoints() as $throwPoint) { |
| 58 | + if (!$throwPoint->isExplicit()) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + foreach (TypeUtils::flattenTypes($throwPoint->getType()) as $throwPointType) { |
| 63 | + if ( |
| 64 | + $throwPointType instanceof TypeWithClassName |
| 65 | + && $this->exceptionTypeResolver->isCheckedException($throwPointType->getClassName(), $throwPoint->getScope()) |
| 66 | + ) { |
| 67 | + continue; |
| 68 | + } |
| 69 | + |
| 70 | + $errors[] = RuleErrorBuilder::message(sprintf( |
| 71 | + 'Method %s::%s() throws exception %s but the PHPDoc contains @throws void.', |
| 72 | + $methodReflection->getDeclaringClass()->getDisplayName(), |
| 73 | + $methodReflection->getName(), |
| 74 | + $throwPointType->describe(VerbosityLevel::typeOnly()) |
| 75 | + ))->line($throwPoint->getNode()->getLine())->build(); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return $errors; |
| 80 | + } |
| 81 | + |
| 82 | +} |
0 commit comments