|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Methods; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\StaticCall; |
| 7 | +use PhpParser\Node\Name; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Rules\Rule; |
| 10 | +use PHPStan\Rules\RuleErrorBuilder; |
| 11 | + |
| 12 | +/** |
| 13 | + * @implements Rule<StaticCall> |
| 14 | + */ |
| 15 | +class CallPrivateMethodThroughStaticRule implements Rule |
| 16 | +{ |
| 17 | + |
| 18 | + public function getNodeType(): string |
| 19 | + { |
| 20 | + return StaticCall::class; |
| 21 | + } |
| 22 | + |
| 23 | + public function processNode(Node $node, Scope $scope): array |
| 24 | + { |
| 25 | + if (!$node->name instanceof Node\Identifier) { |
| 26 | + return []; |
| 27 | + } |
| 28 | + if (!$node->class instanceof Name) { |
| 29 | + return []; |
| 30 | + } |
| 31 | + |
| 32 | + $methodName = $node->name->name; |
| 33 | + $className = $node->class; |
| 34 | + if ($className->toLowerString() !== 'static') { |
| 35 | + return []; |
| 36 | + } |
| 37 | + |
| 38 | + $classType = $scope->resolveTypeByName($className); |
| 39 | + if (!$classType->hasMethod($methodName)->yes()) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + $method = $classType->getMethod($methodName, $scope); |
| 44 | + if (!$method->isPrivate()) { |
| 45 | + return []; |
| 46 | + } |
| 47 | + |
| 48 | + if ($scope->isInClass() && $scope->getClassReflection()->isFinal()) { |
| 49 | + return []; |
| 50 | + } |
| 51 | + |
| 52 | + return [ |
| 53 | + RuleErrorBuilder::message(sprintf( |
| 54 | + 'Unsafe call to private method %s::%s() through static::.', |
| 55 | + $method->getDeclaringClass()->getDisplayName(), |
| 56 | + $method->getName() |
| 57 | + ))->build(), |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments