|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DaveLiddament\PhpstanPhpLanguageExtensions\Rules; |
| 4 | + |
| 5 | +use DaveLiddament\PhpLanguageExtensions\MustUseResult; |
| 6 | +use DaveLiddament\PhpstanPhpLanguageExtensions\AttributeValueReaders\AttributeFinder; |
| 7 | +use DaveLiddament\PhpstanPhpLanguageExtensions\Helpers\Cache; |
| 8 | +use PhpParser\Node; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Reflection\ReflectionProvider; |
| 11 | +use PHPStan\Rules\Rule; |
| 12 | +use PHPStan\Rules\RuleErrorBuilder; |
| 13 | + |
| 14 | +/** |
| 15 | + * @implements Rule<Node\Stmt\Expression> |
| 16 | + */ |
| 17 | +final class MustUseResultRule implements Rule |
| 18 | +{ |
| 19 | + /** @var Cache<bool> */ |
| 20 | + private Cache $cache; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + private ReflectionProvider $reflectionProvider, |
| 24 | + ) { |
| 25 | + $this->cache = new Cache(); |
| 26 | + } |
| 27 | + |
| 28 | + public function getNodeType(): string |
| 29 | + { |
| 30 | + return Node\Stmt\Expression::class; |
| 31 | + } |
| 32 | + |
| 33 | + /** @param Node\Stmt\Expression $node */ |
| 34 | + public function processNode(Node $node, Scope $scope): array |
| 35 | + { |
| 36 | + $expr = $node->expr; |
| 37 | + |
| 38 | + if ($expr instanceof Node\Expr\MethodCall) { |
| 39 | + $classReflections = $scope->getType($expr->var)->getObjectClassReflections(); |
| 40 | + } elseif ($expr instanceof Node\Expr\StaticCall) { |
| 41 | + $class = $expr->class; |
| 42 | + if (!$class instanceof Node\Name) { |
| 43 | + return []; |
| 44 | + } |
| 45 | + |
| 46 | + $classReflections = [ |
| 47 | + $this->reflectionProvider->getClass($class->toCodeString()), |
| 48 | + ]; |
| 49 | + } else { |
| 50 | + return []; |
| 51 | + } |
| 52 | + |
| 53 | + $methodNameNode = $expr->name; |
| 54 | + if (!$methodNameNode instanceof Node\Identifier) { |
| 55 | + return []; |
| 56 | + } |
| 57 | + |
| 58 | + $methodName = $methodNameNode->toLowerString(); |
| 59 | + |
| 60 | + foreach ($classReflections as $classReflection) { |
| 61 | + $className = $classReflection->getName(); |
| 62 | + $fullMethodName = "{$className}::{$methodName}"; |
| 63 | + |
| 64 | + if ($this->cache->hasEntry($fullMethodName)) { |
| 65 | + $mustUseResult = $this->cache->getEntry($fullMethodName); |
| 66 | + } else { |
| 67 | + $mustUseResult = AttributeFinder::hasAttributeOnMethod( |
| 68 | + $classReflection->getNativeReflection(), |
| 69 | + $methodName, |
| 70 | + MustUseResult::class, |
| 71 | + ); |
| 72 | + $this->cache->addEntry($fullMethodName, $mustUseResult); |
| 73 | + } |
| 74 | + |
| 75 | + if ($mustUseResult) { |
| 76 | + return [ |
| 77 | + RuleErrorBuilder::message('Result returned by method must be used') |
| 78 | + ->identifier('phpExtensionLibrary.mustUseResult') |
| 79 | + ->build(), |
| 80 | + ]; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return []; |
| 85 | + } |
| 86 | +} |
0 commit comments