forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestrictedUsageOfDeprecatedStringCastRule.php
More file actions
74 lines (59 loc) · 1.82 KB
/
RestrictedUsageOfDeprecatedStringCastRule.php
File metadata and controls
74 lines (59 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php declare(strict_types = 1);
namespace PHPStan\Rules\RestrictedUsage;
use PhpParser\Node;
use PhpParser\Node\Expr\Cast;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<Cast\String_>
*/
#[AutowiredService]
final class RestrictedUsageOfDeprecatedStringCastRule implements Rule
{
/** @var RestrictedMethodUsageExtension[] $extensions */
private ?array $extensions = null;
public function __construct(
private Container $container,
private ReflectionProvider $reflectionProvider,
)
{
}
public function getNodeType(): string
{
return Cast\String_::class;
}
public function processNode(Node $node, Scope $scope): array
{
$extensions = $this->extensions ??= $this->container->getServicesByTag(RestrictedMethodUsageExtension::METHOD_EXTENSION_TAG);
if ($extensions === []) {
return [];
}
$exprType = $scope->getType($node->expr);
$referencedClasses = $exprType->getObjectClassNames();
$errors = [];
foreach ($referencedClasses as $referencedClass) {
if (!$this->reflectionProvider->hasClass($referencedClass)) {
continue;
}
$classReflection = $this->reflectionProvider->getClass($referencedClass);
if (!$classReflection->hasNativeMethod('__toString')) {
continue;
}
$methodReflection = $classReflection->getNativeMethod('__toString');
foreach ($extensions as $extension) {
$restrictedUsage = $extension->isRestrictedMethodUsage($methodReflection, $scope);
if ($restrictedUsage === null) {
continue;
}
$errors[] = RuleErrorBuilder::message($restrictedUsage->errorMessage)
->identifier($restrictedUsage->identifier)
->build();
}
}
return $errors;
}
}