|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Nette; |
| 4 | + |
| 5 | +use Nette\Utils\Strings; |
| 6 | +use PhpParser\Node\Expr\StaticCall; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Analyser\SpecifiedTypes; |
| 9 | +use PHPStan\Analyser\TypeSpecifier; |
| 10 | +use PHPStan\Analyser\TypeSpecifierAwareExtension; |
| 11 | +use PHPStan\Analyser\TypeSpecifierContext; |
| 12 | +use PHPStan\Reflection\MethodReflection; |
| 13 | +use PHPStan\Type\Php\RegexArrayShapeMatcher; |
| 14 | +use PHPStan\Type\StaticMethodTypeSpecifyingExtension; |
| 15 | +use function in_array; |
| 16 | + |
| 17 | +class StringsMatchTypeSpecifiyingExtension implements StaticMethodTypeSpecifyingExtension, TypeSpecifierAwareExtension |
| 18 | +{ |
| 19 | + |
| 20 | + private RegexArrayShapeMatcher $regexArrayShapeMatcher; |
| 21 | + |
| 22 | + private TypeSpecifier $typeSpecifier; |
| 23 | + |
| 24 | + public function __construct(RegexArrayShapeMatcher $regexArrayShapeMatcher) |
| 25 | + { |
| 26 | + $this->regexArrayShapeMatcher = $regexArrayShapeMatcher; |
| 27 | + } |
| 28 | + |
| 29 | + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void |
| 30 | + { |
| 31 | + $this->typeSpecifier = $typeSpecifier; |
| 32 | + } |
| 33 | + |
| 34 | + public function getClass(): string |
| 35 | + { |
| 36 | + return Strings::class; |
| 37 | + } |
| 38 | + |
| 39 | + public function isStaticMethodSupported(MethodReflection $staticMethodReflection, StaticCall $node, TypeSpecifierContext $context): bool |
| 40 | + { |
| 41 | + return $context->true() && in_array($staticMethodReflection->getName(), ['match', 'matchAll'], true); |
| 42 | + } |
| 43 | + |
| 44 | + public function specifyTypes(MethodReflection $staticMethodReflection, StaticCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes |
| 45 | + { |
| 46 | + $args = $node->getArgs(); |
| 47 | + $subjectArg = $args[0] ?? null; |
| 48 | + $patternArg = $args[1] ?? null; |
| 49 | + |
| 50 | + $subjectTypes = new SpecifiedTypes(); |
| 51 | + if ($patternArg === null || $subjectArg === null) { |
| 52 | + return $subjectTypes; |
| 53 | + } |
| 54 | + |
| 55 | + if ($scope->getType($subjectArg->value)->isString()->yes()) { |
| 56 | + $subjectType = $this->regexArrayShapeMatcher->matchSubjectExpr($patternArg->value, $scope); |
| 57 | + if ($subjectType !== null) { |
| 58 | + $subjectTypes = $this->typeSpecifier->create( |
| 59 | + $subjectArg->value, |
| 60 | + $subjectType, |
| 61 | + $context, |
| 62 | + $scope, |
| 63 | + )->setRootExpr($node); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return $subjectTypes; |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments