|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace mglaman\PHPStanDrupal\Rules\Drupal; |
| 6 | + |
| 7 | +use Drupal\Core\Cache\CacheableDependencyInterface; |
| 8 | +use Drupal\Core\Cache\CacheableResponseInterface; |
| 9 | +use Drupal\Core\Cache\RefinableCacheableDependencyInterface; |
| 10 | +use Drupal\Core\Plugin\Context\ContextInterface; |
| 11 | +use Drupal\Core\Render\RendererInterface; |
| 12 | +use PhpParser\Node; |
| 13 | +use PhpParser\Node\Identifier; |
| 14 | +use PHPStan\Analyser\Scope; |
| 15 | +use PHPStan\Rules\Rule; |
| 16 | +use PHPStan\Rules\RuleErrorBuilder; |
| 17 | +use PHPStan\Type\ObjectType; |
| 18 | + |
| 19 | +/** |
| 20 | + * @implements Rule<Node\Expr\MethodCall> |
| 21 | + */ |
| 22 | +class CacheableDependencyRule implements Rule |
| 23 | +{ |
| 24 | + |
| 25 | + public function getNodeType(): string |
| 26 | + { |
| 27 | + return Node\Expr\MethodCall::class; |
| 28 | + } |
| 29 | + |
| 30 | + public function processNode(Node $node, Scope $scope): array |
| 31 | + { |
| 32 | + if (!$node->name instanceof Identifier || $node->name->toString() !== 'addCacheableDependency') { |
| 33 | + return []; |
| 34 | + } |
| 35 | + |
| 36 | + $receiverType = $scope->getType($node->var); |
| 37 | + |
| 38 | + $allowedInterfaces = [ |
| 39 | + RefinableCacheableDependencyInterface::class => 0, |
| 40 | + CacheableResponseInterface::class => 0, |
| 41 | + ContextInterface::class => 0, |
| 42 | + RendererInterface::class => 1, |
| 43 | + ]; |
| 44 | + |
| 45 | + $argumentIndex = null; |
| 46 | + foreach ($allowedInterfaces as $interfaceName => $argPosition) { |
| 47 | + $interfaceType = new ObjectType($interfaceName); |
| 48 | + if ($interfaceType->isSuperTypeOf($receiverType)->yes()) { |
| 49 | + $argumentIndex = $argPosition; |
| 50 | + break; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if ($argumentIndex === null) { |
| 55 | + return []; |
| 56 | + } |
| 57 | + |
| 58 | + $args = $node->getArgs(); |
| 59 | + if (count($args) <= $argumentIndex) { |
| 60 | + return []; |
| 61 | + } |
| 62 | + |
| 63 | + $dependencyArg = $args[$argumentIndex]->value; |
| 64 | + $object = $scope->getType($dependencyArg); |
| 65 | + |
| 66 | + $interfaceType = new ObjectType(CacheableDependencyInterface::class); |
| 67 | + $implementsInterface = $interfaceType->isSuperTypeOf($object); |
| 68 | + |
| 69 | + if (!$implementsInterface->no()) { |
| 70 | + return []; |
| 71 | + } |
| 72 | + |
| 73 | + return [ |
| 74 | + RuleErrorBuilder::message('Calling addCacheableDependency($object) when $object does not implement CacheableDependencyInterface effectively disables caching and should be avoided.') |
| 75 | + ->identifier('cacheable.dependency') |
| 76 | + ->build(), |
| 77 | + ]; |
| 78 | + } |
| 79 | +} |
0 commit comments