|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Composer\Pcre\PHPStan; |
| 4 | + |
| 5 | +use Composer\Pcre\Preg; |
| 6 | +use Composer\Pcre\Regex; |
| 7 | +use PhpParser\Node\Expr\StaticCall; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Reflection\MethodReflection; |
| 10 | +use PHPStan\Reflection\Native\NativeParameterReflection; |
| 11 | +use PHPStan\Reflection\ParameterReflection; |
| 12 | +use PHPStan\TrinaryLogic; |
| 13 | +use PHPStan\Type\ClosureType; |
| 14 | +use PHPStan\Type\Php\RegexArrayShapeMatcher; |
| 15 | +use PHPStan\Type\StaticMethodParameterClosureTypeExtension; |
| 16 | +use PHPStan\Type\StringType; |
| 17 | +use PHPStan\Type\Type; |
| 18 | + |
| 19 | +final class PregReplaceCallbackClosureTypeExtension implements StaticMethodParameterClosureTypeExtension |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @var RegexArrayShapeMatcher |
| 23 | + */ |
| 24 | + private $regexShapeMatcher; |
| 25 | + |
| 26 | + public function __construct(RegexArrayShapeMatcher $regexShapeMatcher) |
| 27 | + { |
| 28 | + $this->regexShapeMatcher = $regexShapeMatcher; |
| 29 | + } |
| 30 | + |
| 31 | + public function isStaticMethodSupported(MethodReflection $methodReflection, ParameterReflection $parameter): bool |
| 32 | + { |
| 33 | + return in_array($methodReflection->getDeclaringClass()->getName(), [Preg::class, Regex::class], true) |
| 34 | + && in_array($methodReflection->getName(), ['replaceCallback'], true) |
| 35 | + && $parameter->getName() === 'replacement'; |
| 36 | + } |
| 37 | + |
| 38 | + public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, ParameterReflection $parameter, Scope $scope): ?Type |
| 39 | + { |
| 40 | + $args = $methodCall->getArgs(); |
| 41 | + $patternArg = $args[0] ?? null; |
| 42 | + $flagsArg = $args[5] ?? null; |
| 43 | + |
| 44 | + if ( |
| 45 | + $patternArg === null |
| 46 | + ) { |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + $flagsType = null; |
| 51 | + if ($flagsArg !== null) { |
| 52 | + $flagsType = $scope->getType($flagsArg->value); |
| 53 | + } |
| 54 | + |
| 55 | + $matchesType = $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createYes(), $scope); |
| 56 | + if ($matchesType === null) { |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + return new ClosureType( |
| 61 | + [ |
| 62 | + new NativeParameterReflection($parameter->getName(), $parameter->isOptional(), $matchesType, $parameter->passedByReference(), $parameter->isVariadic(), $parameter->getDefaultValue()), |
| 63 | + ], |
| 64 | + new StringType() |
| 65 | + ); |
| 66 | + } |
| 67 | +} |
0 commit comments