forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParameterCastableToStringCheck.php
More file actions
84 lines (69 loc) · 2.12 KB
/
ParameterCastableToStringCheck.php
File metadata and controls
84 lines (69 loc) · 2.12 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
75
76
77
78
79
80
81
82
83
84
<?php declare(strict_types = 1);
namespace PHPStan\Rules;
use PhpParser\Node\Arg;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\TypeExpr;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
#[AutowiredService]
final class ParameterCastableToStringCheck
{
public function __construct(private RuleLevelHelper $ruleLevelHelper)
{
}
/** @param callable(Type): Type $castFn */
public function checkParameter(
Arg $parameter,
Scope $scope,
string $errorMessageTemplate,
callable $castFn,
string $functionName,
string $parameterName,
): ?IdentifierRuleError
{
if ($parameter->unpack) {
return null;
}
$arrayTypeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$parameter->value,
'',
static fn (Type $type): bool => $type->isArray()->yes(),
);
$arrayType = $arrayTypeResult->getType();
if (!$arrayType->isArray()->yes()) {
return null;
}
$typeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
new TypeExpr($arrayType->getIterableValueType()),
'',
static fn (Type $type): bool => !$castFn($type) instanceof ErrorType,
);
if (!$castFn($typeResult->getType()) instanceof ErrorType) {
return null;
}
return RuleErrorBuilder::message(
sprintf($errorMessageTemplate, $parameterName, $functionName, $arrayTypeResult->getType()->describe(VerbosityLevel::typeOnly())),
)->identifier('argument.type')->build();
}
public function getParameterName(Arg $parameter, int $parameterIdx, ?ParameterReflection $parameterReflection): string
{
if ($parameterReflection === null) {
return sprintf('#%d', $parameterIdx + 1);
}
$paramName = $parameterReflection->getName();
$origParameter = $parameter->getAttributes()[ArgumentsNormalizer::ORIGINAL_ARG_ATTRIBUTE] ?? null;
if (!$origParameter instanceof Arg) {
$origParameter = $parameter;
}
return $origParameter->name !== null
? sprintf('$%s', $paramName)
: sprintf('#%d $%s', $parameterIdx + 1, $paramName);
}
}