|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Php; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr; |
| 6 | +use PhpParser\Node\Expr\FuncCall; |
| 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\DependencyInjection\AutowiredService; |
| 13 | +use PHPStan\Reflection\FunctionReflection; |
| 14 | +use PHPStan\Type\Constant\ConstantBooleanType; |
| 15 | +use PHPStan\ShouldNotHappenException; |
| 16 | +use PHPStan\Type\ArrayType; |
| 17 | +use PHPStan\Type\FunctionTypeSpecifyingExtension; |
| 18 | +use PHPStan\Type\MixedType; |
| 19 | +use function strtolower; |
| 20 | + |
| 21 | +#[AutowiredService] |
| 22 | +final class ArrayAllFunctionTypeSpecifyingExtension implements FunctionTypeSpecifyingExtension, TypeSpecifierAwareExtension |
| 23 | +{ |
| 24 | + |
| 25 | + private TypeSpecifier $typeSpecifier; |
| 26 | + |
| 27 | + public function isFunctionSupported(FunctionReflection $functionReflection, FuncCall $node, TypeSpecifierContext $context): bool |
| 28 | + { |
| 29 | + return strtolower($functionReflection->getName()) === 'array_all' |
| 30 | + && !$context->null(); |
| 31 | + } |
| 32 | + |
| 33 | + public function specifyTypes(FunctionReflection $functionReflection, FuncCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes |
| 34 | + { |
| 35 | + $args = $node->getArgs(); |
| 36 | + if (!$context->true() || count($args) < 2) { |
| 37 | + return new SpecifiedTypes(); |
| 38 | + } |
| 39 | + |
| 40 | + $array = $args[0]->value; |
| 41 | + $callable = $args[1]->value; |
| 42 | + if ($callable instanceof Expr\ArrowFunction && $callable->expr instanceof Expr\FuncCall) { |
| 43 | + $specifiedTypesInCallable = $this->typeSpecifier->specifyTypesInCondition($scope, $callable->expr, $context)->getSureTypes(); |
| 44 | + $callableParm = $callable->params[0]; |
| 45 | + if (!$callableParm instanceof Expr\Variable || !key_exists("$" . $callableParm->name, $specifiedTypesInCallable)) { |
| 46 | + return new SpecifiedTypes(); |
| 47 | + } |
| 48 | + $ItemType = $specifiedTypesInCallable["$" . $callableParm->name][1]; |
| 49 | + return $this->typeSpecifier->create( |
| 50 | + $array, |
| 51 | + new ArrayType(new MixedType(), $ItemType), |
| 52 | + $context, |
| 53 | + $scope |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + return new SpecifiedTypes(); |
| 58 | + } |
| 59 | + |
| 60 | + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void |
| 61 | + { |
| 62 | + $this->typeSpecifier = $typeSpecifier; |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments