1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Rules\RestrictedUsage;
4:
5: use PhpParser\Node;
6: use PhpParser\Node\Expr\MethodCall;
7: use PhpParser\Node\Identifier;
8: use PHPStan\Analyser\Scope;
9: use PHPStan\DependencyInjection\AutowiredExtensions;
10: use PHPStan\DependencyInjection\AutowiredService;
11: use PHPStan\DependencyInjection\ExtensionsCollection;
12: use PHPStan\Reflection\ReflectionProvider;
13: use PHPStan\Rules\Rule;
14: use PHPStan\Rules\RuleErrorBuilder;
15: use PHPStan\Type\ObjectWithoutClassType;
16: use PHPStan\Type\TypeCombinator;
17:
18: /**
19: * @implements Rule<MethodCall>
20: */
21: #[AutowiredService]
22: final class RestrictedMethodUsageRule implements Rule
23: {
24:
25: /**
26: * @param ExtensionsCollection<RestrictedMethodUsageExtension> $extensions
27: */
28: public function __construct(
29: #[AutowiredExtensions(of: RestrictedMethodUsageExtension::class)]
30: private ExtensionsCollection $extensions,
31: private ReflectionProvider $reflectionProvider,
32: )
33: {
34: }
35:
36: public function getNodeType(): string
37: {
38: return MethodCall::class;
39: }
40:
41: /**
42: * @api
43: */
44: public function processNode(Node $node, Scope $scope): array
45: {
46: if (!$node->name instanceof Identifier) {
47: return [];
48: }
49:
50: $extensions = $this->extensions->getAll();
51: if ($extensions === []) {
52: return [];
53: }
54:
55: $methodName = $node->name->name;
56: $methodCalledOnType = $scope->getType($node->var);
57: // the intersection only removes what is not an object, such as the null of a nullable type
58: $objectType = $methodCalledOnType->isObject()->yes() ? $methodCalledOnType : TypeCombinator::intersect($methodCalledOnType, new ObjectWithoutClassType());
59: $referencedClasses = $objectType->getObjectClassNames();
60:
61: $errors = [];
62:
63: foreach ($referencedClasses as $referencedClass) {
64: if (!$this->reflectionProvider->hasClass($referencedClass)) {
65: continue;
66: }
67:
68: $classReflection = $this->reflectionProvider->getClass($referencedClass);
69: if (!$classReflection->hasMethod($methodName)) {
70: continue;
71: }
72:
73: $methodReflection = $classReflection->getMethod($methodName, $scope);
74: foreach ($extensions as $extension) {
75: $restrictedUsage = $extension->isRestrictedMethodUsage($methodReflection, $scope);
76: if ($restrictedUsage === null) {
77: continue;
78: }
79:
80: $errorBuilder = RuleErrorBuilder::message($restrictedUsage->errorMessage)
81: ->identifier($restrictedUsage->identifier);
82: if ($restrictedUsage->tip !== null) {
83: $errorBuilder->tip($restrictedUsage->tip);
84: }
85:
86: $errors[] = $errorBuilder->build();
87: }
88: }
89:
90: return $errors;
91: }
92:
93: }
94: