|
| 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\Reflection\FunctionReflection; |
| 8 | +use PHPStan\Reflection\ParametersAcceptorSelector; |
| 9 | +use PHPStan\Type\Accessory\NonEmptyArrayType; |
| 10 | +use PHPStan\Type\ArrayType; |
| 11 | +use PHPStan\Type\Type; |
| 12 | +use PHPStan\Type\TypeCombinator; |
| 13 | + |
| 14 | +class ArrayFlipFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension |
| 15 | +{ |
| 16 | + |
| 17 | + public function isFunctionSupported(FunctionReflection $functionReflection): bool |
| 18 | + { |
| 19 | + return $functionReflection->getName() === 'array_flip'; |
| 20 | + } |
| 21 | + |
| 22 | + public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type |
| 23 | + { |
| 24 | + if (count($functionCall->args) !== 1) { |
| 25 | + return ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType(); |
| 26 | + } |
| 27 | + |
| 28 | + $array = $functionCall->args[0]->value; |
| 29 | + $argType = $scope->getType($array); |
| 30 | + |
| 31 | + if ($argType->isArray()->yes()) { |
| 32 | + $keyType = $argType->getIterableKeyType(); |
| 33 | + $itemType = $argType->getIterableValueType(); |
| 34 | + |
| 35 | + $itemType = ArrayType::castToArrayKeyType($itemType); |
| 36 | + |
| 37 | + $flippedArrayType = new ArrayType( |
| 38 | + $itemType, |
| 39 | + $keyType |
| 40 | + ); |
| 41 | + |
| 42 | + if ($argType->isIterableAtLeastOnce()->yes()) { |
| 43 | + $flippedArrayType = TypeCombinator::intersect($flippedArrayType, new NonEmptyArrayType()); |
| 44 | + } |
| 45 | + |
| 46 | + return $flippedArrayType; |
| 47 | + } |
| 48 | + |
| 49 | + return ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType(); |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments