Skip to content

Commit

Permalink
Refactor SprintfFunctionDynamicReturnTypeExtension
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored Jun 25, 2024
1 parent 36e60f4 commit 466e677
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/Type/Php/SprintfFunctionDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PHPStan\Type\Php;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Internal\CombinationsHelper;
Expand Down Expand Up @@ -108,6 +109,14 @@ public function getTypeFromFunctionCall(
$returnType = new StringType();
}

return $this->getConstantType($args, $returnType, $functionReflection, $scope);
}

/**
* @param Arg[] $args
*/
private function getConstantType(array $args, Type $fallbackReturnType, FunctionReflection $functionReflection, Scope $scope): Type
{
$values = [];
$combinationsCount = 1;
foreach ($args as $arg) {
Expand All @@ -123,23 +132,23 @@ public function getTypeFromFunctionCall(
}

if (count($constantScalarValues) === 0) {
return $returnType;
return $fallbackReturnType;
}

$values[] = $constantScalarValues;
$combinationsCount *= count($constantScalarValues);
}

if ($combinationsCount > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
return $returnType;
return $fallbackReturnType;
}

$combinations = CombinationsHelper::combinations($values);
$returnTypes = [];
foreach ($combinations as $combination) {
$format = array_shift($combination);
if (!is_string($format)) {
return $returnType;
return $fallbackReturnType;
}

try {
Expand All @@ -149,12 +158,12 @@ public function getTypeFromFunctionCall(
$returnTypes[] = $scope->getTypeFromValue(@vsprintf($format, $combination));
}
} catch (Throwable) {
return $returnType;
return $fallbackReturnType;
}
}

if (count($returnTypes) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
return $returnType;
return $fallbackReturnType;
}

return TypeCombinator::union(...$returnTypes);
Expand Down

0 comments on commit 466e677

Please sign in to comment.