forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPregMatchParameterOutTypeExtension.php
More file actions
68 lines (56 loc) · 1.99 KB
/
PregMatchParameterOutTypeExtension.php
File metadata and controls
68 lines (56 loc) · 1.99 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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\FunctionParameterOutTypeExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function in_array;
use function strtolower;
#[AutowiredService]
final class PregMatchParameterOutTypeExtension implements FunctionParameterOutTypeExtension
{
public function __construct(
private RegexArrayShapeMatcher $regexShapeMatcher,
)
{
}
public function isFunctionSupported(FunctionReflection $functionReflection, ParameterReflection $parameter): bool
{
return in_array(strtolower($functionReflection->getName()), ['preg_match', 'preg_match_all'], true)
// the parameter is named different, depending on PHP version.
&& in_array($parameter->getName(), ['subpatterns', 'matches'], true);
}
public function getParameterOutTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, ParameterReflection $parameter, Scope $scope): ?Type
{
$args = $funcCall->getArgs();
$patternArg = $args[0] ?? null;
$matchesArg = $args[2] ?? null;
$flagsArg = $args[3] ?? null;
if (
$patternArg === null || $matchesArg === null
) {
return null;
}
$flagsType = null;
if ($flagsArg !== null) {
$flagsType = $scope->getType($flagsArg->value);
}
if ($functionReflection->getName() === 'preg_match') {
$matchedType = $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createYes(), $scope);
if ($matchedType === null) {
return null;
}
return TypeCombinator::union(
ConstantArrayTypeBuilder::createEmpty()->getArray(),
$matchedType,
);
}
return $this->regexShapeMatcher->matchAllExpr($patternArg->value, $flagsType, TrinaryLogic::createMaybe(), $scope);
}
}