|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Php; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr\FuncCall; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Analyser\SpecifiedTypes; |
| 8 | +use PHPStan\Analyser\TypeSpecifier; |
| 9 | +use PHPStan\Analyser\TypeSpecifierAwareExtension; |
| 10 | +use PHPStan\Analyser\TypeSpecifierContext; |
| 11 | +use PHPStan\Reflection\FunctionReflection; |
| 12 | +use PHPStan\TrinaryLogic; |
| 13 | +use PHPStan\Type\FunctionTypeSpecifyingExtension; |
| 14 | +use function in_array; |
| 15 | +use function strtolower; |
| 16 | + |
| 17 | +final class PregMatchTypeSpecifyingExtension implements FunctionTypeSpecifyingExtension, TypeSpecifierAwareExtension |
| 18 | +{ |
| 19 | + |
| 20 | + private TypeSpecifier $typeSpecifier; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + private RegexArrayShapeMatcher $regexShapeMatcher, |
| 24 | + ) |
| 25 | + { |
| 26 | + } |
| 27 | + |
| 28 | + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void |
| 29 | + { |
| 30 | + $this->typeSpecifier = $typeSpecifier; |
| 31 | + } |
| 32 | + |
| 33 | + public function isFunctionSupported(FunctionReflection $functionReflection, FuncCall $node, TypeSpecifierContext $context): bool |
| 34 | + { |
| 35 | + return in_array(strtolower($functionReflection->getName()), ['preg_match'], true) && !$context->null(); |
| 36 | + } |
| 37 | + |
| 38 | + public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes |
| 39 | + { |
| 40 | + $args = $node->getArgs(); |
| 41 | + $patternArg = $args[0] ?? null; |
| 42 | + $matchesArg = $args[2] ?? null; |
| 43 | + $flagsArg = $args[3] ?? null; |
| 44 | + |
| 45 | + if ( |
| 46 | + $patternArg === null || $matchesArg === null |
| 47 | + ) { |
| 48 | + return new SpecifiedTypes(); |
| 49 | + } |
| 50 | + |
| 51 | + $patternType = $scope->getType($patternArg->value); |
| 52 | + $flagsType = null; |
| 53 | + if ($flagsArg !== null) { |
| 54 | + $flagsType = $scope->getType($flagsArg->value); |
| 55 | + } |
| 56 | + |
| 57 | + $matchedType = $this->regexShapeMatcher->matchType($patternType, $flagsType, TrinaryLogic::createFromBoolean($context->true())); |
| 58 | + if ($matchedType === null) { |
| 59 | + return new SpecifiedTypes(); |
| 60 | + } |
| 61 | + |
| 62 | + $overwrite = false; |
| 63 | + if ($context->false()) { |
| 64 | + $overwrite = true; |
| 65 | + $context = $context->negate(); |
| 66 | + } |
| 67 | + |
| 68 | + return $this->typeSpecifier->create( |
| 69 | + $matchesArg->value, |
| 70 | + $matchedType, |
| 71 | + $context, |
| 72 | + $overwrite, |
| 73 | + $scope, |
| 74 | + $node, |
| 75 | + ); |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments