|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +/* |
| 4 | +Blatantly copy-pasted from PHPStan's source code but with isFunctionSupported changed |
| 5 | +
|
| 6 | +https://github.com/phpstan/phpstan-src/blob/e664bed7b62e2a58d571fb631ddf47030914a2b5/src/Type/Php/PregMatchParameterOutTypeExtension.php |
| 7 | +*/ |
| 8 | +namespace TheCodingMachine\Safe\PHPStan\Type\Php; |
| 9 | + |
| 10 | +use PHPStan\Type\Php\RegexArrayShapeMatcher; |
| 11 | +use PhpParser\Node\Expr\FuncCall; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Reflection\FunctionReflection; |
| 14 | +use PHPStan\Reflection\ParameterReflection; |
| 15 | +use PHPStan\TrinaryLogic; |
| 16 | +use PHPStan\Type\FunctionParameterOutTypeExtension; |
| 17 | +use PHPStan\Type\Type; |
| 18 | +use function in_array; |
| 19 | + |
| 20 | +final class PregMatchParameterOutTypeExtension implements FunctionParameterOutTypeExtension |
| 21 | +{ |
| 22 | + |
| 23 | + public function __construct( |
| 24 | + private RegexArrayShapeMatcher $regexShapeMatcher, |
| 25 | + ) { |
| 26 | + } |
| 27 | + |
| 28 | + public function isFunctionSupported(FunctionReflection $functionReflection, ParameterReflection $parameter): bool |
| 29 | + { |
| 30 | + return in_array($functionReflection->getName(), ['Safe\preg_match', 'Safe\preg_match_all'], true) |
| 31 | + // the parameter is named different, depending on PHP version. |
| 32 | + && in_array($parameter->getName(), ['subpatterns', 'matches'], true); |
| 33 | + } |
| 34 | + |
| 35 | + public function getParameterOutTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, ParameterReflection $parameter, Scope $scope): ?Type |
| 36 | + { |
| 37 | + $args = $funcCall->getArgs(); |
| 38 | + $patternArg = $args[0] ?? null; |
| 39 | + $matchesArg = $args[2] ?? null; |
| 40 | + $flagsArg = $args[3] ?? null; |
| 41 | + |
| 42 | + if ($patternArg === null || $matchesArg === null |
| 43 | + ) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + $flagsType = null; |
| 48 | + if ($flagsArg !== null) { |
| 49 | + $flagsType = $scope->getType($flagsArg->value); |
| 50 | + } |
| 51 | + |
| 52 | + if ($functionReflection->getName() === 'Safe\preg_match') { |
| 53 | + return $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createMaybe(), $scope); |
| 54 | + } |
| 55 | + return $this->regexShapeMatcher->matchAllExpr($patternArg->value, $flagsType, TrinaryLogic::createMaybe(), $scope); |
| 56 | + } |
| 57 | +} |
0 commit comments