forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintfPlaceholder.php
More file actions
71 lines (65 loc) · 2.57 KB
/
PrintfPlaceholder.php
File metadata and controls
71 lines (65 loc) · 2.57 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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Functions;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\NullType;
use PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
final class PrintfPlaceholder
{
/** @phpstan-param 'strict-int'|'int'|'float'|'string'|'mixed' $acceptingType */
public function __construct(
public readonly string $label,
public readonly int $parameterIndex,
public readonly int $placeholderNumber,
public readonly string $acceptingType,
)
{
}
public function doesArgumentTypeMatchPlaceholder(Type $argumentType, bool $strictPlaceholderTypes): bool
{
switch ($this->acceptingType) {
case 'strict-int':
return (new IntegerType())->accepts($argumentType, true)->yes();
case 'int':
return $strictPlaceholderTypes
? (new UnionType([
new IntegerType(),
// numeric-string is allowed for consistency with the float placeholder.
new IntersectionType([new StringType(), new AccessoryNumericStringType()]),
]))->accepts($argumentType, true)->yes()
: ! $argumentType->toInteger() instanceof ErrorType;
case 'float':
return $strictPlaceholderTypes
? (new UnionType([
new FloatType(),
// numeric-string is allowed for consistency with phpstan-strict-rules.
new IntersectionType([new StringType(), new AccessoryNumericStringType()]),
]))->accepts($argumentType, true)->yes()
: ! $argumentType->toFloat() instanceof ErrorType;
case 'string':
case 'mixed':
// The function signature already limits the parameters to stringable types, so there's
// no point in checking string again here.
return !$strictPlaceholderTypes
// Don't accept null or bool. It's likely to be a mistake.
|| (new UnionType([
new StringAlwaysAcceptingObjectWithToStringType(),
// float also accepts int.
new FloatType(),
// null is allowed for consistency with phpstan-strict-rules (e.g. $string . $null).
new NullType(),
]))->accepts($argumentType, true)->yes();
// Without this PHPStan with PHP 7.4 reports "...should return bool but return statement is missing."
// Presumably, because promoted properties are turned into regular properties and the phpdoc isn't applied to the property.
default:
throw new ShouldNotHappenException('Unexpected type ' . $this->acceptingType);
}
}
}