|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Api; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Reflection\ReflectionProvider; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use function array_keys; |
| 11 | +use function in_array; |
| 12 | +use function sprintf; |
| 13 | +use function strpos; |
| 14 | + |
| 15 | +/** |
| 16 | + * @implements Rule<Node\Expr\FuncCall> |
| 17 | + */ |
| 18 | +class RuntimeReflectionFunctionRule implements Rule |
| 19 | +{ |
| 20 | + |
| 21 | + public function __construct(private ReflectionProvider $reflectionProvider) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + public function getNodeType(): string |
| 26 | + { |
| 27 | + return Node\Expr\FuncCall::class; |
| 28 | + } |
| 29 | + |
| 30 | + public function processNode(Node $node, Scope $scope): array |
| 31 | + { |
| 32 | + if (!$node->name instanceof Node\Name) { |
| 33 | + return []; |
| 34 | + } |
| 35 | + |
| 36 | + if (!$this->reflectionProvider->hasFunction($node->name, $scope)) { |
| 37 | + return []; |
| 38 | + } |
| 39 | + |
| 40 | + $functionReflection = $this->reflectionProvider->getFunction($node->name, $scope); |
| 41 | + if (!in_array($functionReflection->getName(), [ |
| 42 | + 'is_a', |
| 43 | + 'is_subclass_of', |
| 44 | + 'class_parents', |
| 45 | + 'class_implements', |
| 46 | + 'class_uses', |
| 47 | + ], true)) { |
| 48 | + return []; |
| 49 | + } |
| 50 | + |
| 51 | + if (!$scope->isInClass()) { |
| 52 | + return []; |
| 53 | + } |
| 54 | + |
| 55 | + $classReflection = $scope->getClassReflection(); |
| 56 | + $hasPhpStanInterface = false; |
| 57 | + foreach (array_keys($classReflection->getInterfaces()) as $interfaceName) { |
| 58 | + if (strpos($interfaceName, 'PHPStan\\') !== 0) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + $hasPhpStanInterface = true; |
| 63 | + } |
| 64 | + |
| 65 | + if (!$hasPhpStanInterface) { |
| 66 | + return []; |
| 67 | + } |
| 68 | + |
| 69 | + return [ |
| 70 | + RuleErrorBuilder::message( |
| 71 | + sprintf('Function %s() is a runtime reflection concept that might not work in PHPStan because it uses fully static reflection engine. Use objects retrieved from ReflectionProvider instead.', $functionReflection->getName()), |
| 72 | + )->build(), |
| 73 | + ]; |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments