|
| 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\Accessory\AccessoryNonEmptyStringType; |
| 14 | +use PHPStan\Type\IntersectionType; |
| 15 | +use PHPStan\Type\StaticMethodTypeSpecifyingExtension; |
| 16 | +use PHPStan\Type\StringType; |
| 17 | + |
| 18 | +class StringsLengthTypeSpecifiyingExtension implements StaticMethodTypeSpecifyingExtension, TypeSpecifierAwareExtension |
| 19 | +{ |
| 20 | + |
| 21 | + private TypeSpecifier $typeSpecifier; |
| 22 | + |
| 23 | + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void |
| 24 | + { |
| 25 | + $this->typeSpecifier = $typeSpecifier; |
| 26 | + } |
| 27 | + |
| 28 | + public function getClass(): string |
| 29 | + { |
| 30 | + return Strings::class; |
| 31 | + } |
| 32 | + |
| 33 | + public function isStaticMethodSupported(MethodReflection $staticMethodReflection, StaticCall $node, TypeSpecifierContext $context): bool |
| 34 | + { |
| 35 | + return $context->true() && $staticMethodReflection->getName() === 'length'; |
| 36 | + } |
| 37 | + |
| 38 | + public function specifyTypes(MethodReflection $staticMethodReflection, StaticCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes |
| 39 | + { |
| 40 | + $args = $node->getArgs(); |
| 41 | + $stringArg = $args[0] ?? null; |
| 42 | + |
| 43 | + if ($stringArg === null) { |
| 44 | + return new SpecifiedTypes(); |
| 45 | + } |
| 46 | + |
| 47 | + $type = $scope->getType($stringArg->value); |
| 48 | + if (!$type->isString()->yes()) { |
| 49 | + return new SpecifiedTypes(); |
| 50 | + } |
| 51 | + |
| 52 | + return $this->typeSpecifier->create( |
| 53 | + $stringArg->value, |
| 54 | + new IntersectionType([new StringType(), new AccessoryNonEmptyStringType()]), |
| 55 | + $context, |
| 56 | + $scope, |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments