|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Variables; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Rules\RuleLevelHelper; |
| 8 | +use PHPStan\Type\ErrorType; |
| 9 | +use PHPStan\Type\ObjectType; |
| 10 | +use PHPStan\Type\Type; |
| 11 | +use PHPStan\Type\VerbosityLevel; |
| 12 | + |
| 13 | +class ThrowTypeRule implements \PHPStan\Rules\Rule |
| 14 | +{ |
| 15 | + |
| 16 | +/** @var \PHPStan\Rules\RuleLevelHelper */ |
| 17 | +private $ruleLevelHelper; |
| 18 | + |
| 19 | +public function __construct( |
| 20 | +RuleLevelHelper $ruleLevelHelper |
| 21 | +) |
| 22 | +{ |
| 23 | +$this->ruleLevelHelper = $ruleLevelHelper; |
| 24 | +} |
| 25 | + |
| 26 | +public function getNodeType(): string |
| 27 | +{ |
| 28 | +return \PhpParser\Node\Stmt\Throw_::class; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * @param \PhpParser\Node\Stmt\Throw_ $node |
| 33 | + * @param \PHPStan\Analyser\Scope $scope |
| 34 | + * @return string[] |
| 35 | + */ |
| 36 | +public function processNode(Node $node, Scope $scope): array |
| 37 | +{ |
| 38 | +$throwableType = new ObjectType(\Throwable::class); |
| 39 | +$typeResult = $this->ruleLevelHelper->findTypeToCheck( |
| 40 | +$scope, |
| 41 | +$node->expr, |
| 42 | +'Throwing object of an unknown class %s.', |
| 43 | +function (Type $type) use ($throwableType): bool { |
| 44 | +return $throwableType->isSuperTypeOf($type)->yes(); |
| 45 | +} |
| 46 | +); |
| 47 | + |
| 48 | +$foundType = $typeResult->getType(); |
| 49 | +if ($foundType instanceof ErrorType) { |
| 50 | +return $typeResult->getUnknownClassErrors(); |
| 51 | +} |
| 52 | + |
| 53 | +$isSuperType = $throwableType->isSuperTypeOf($foundType); |
| 54 | +if ($isSuperType->yes()) { |
| 55 | +return []; |
| 56 | +} |
| 57 | + |
| 58 | +return [ |
| 59 | +sprintf('Invalid type %s to throw.', $foundType->describe(VerbosityLevel::typeOnly())), |
| 60 | +]; |
| 61 | +} |
| 62 | + |
| 63 | +} |
0 commit comments