|
| 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\DependencyInjection\AutowiredService; |
| 8 | +use PHPStan\Php\PhpVersion; |
| 9 | +use PHPStan\Reflection\FunctionReflection; |
| 10 | +use PHPStan\Type\DynamicFunctionThrowTypeExtension; |
| 11 | +use PHPStan\Type\IntegerRangeType; |
| 12 | +use PHPStan\Type\ObjectType; |
| 13 | +use PHPStan\Type\Type; |
| 14 | +use PHPStan\Type\TypeCombinator; |
| 15 | +use PHPStan\Type\VoidType; |
| 16 | +use function count; |
| 17 | + |
| 18 | +/** |
| 19 | + * round() throws ValueError only on PHP 8.4+, for an int $mode that is not |
| 20 | + * one of the eight rounding modes (1-8). |
| 21 | + */ |
| 22 | +#[AutowiredService] |
| 23 | +final class RoundFunctionThrowTypeExtension implements DynamicFunctionThrowTypeExtension |
| 24 | +{ |
| 25 | + |
| 26 | + public function __construct(private PhpVersion $phpVersion) |
| 27 | + { |
| 28 | + } |
| 29 | + |
| 30 | + public function isFunctionSupported(FunctionReflection $functionReflection): bool |
| 31 | + { |
| 32 | + return $functionReflection->getName() === 'round'; |
| 33 | + } |
| 34 | + |
| 35 | + public function getThrowTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, Scope $scope): ?Type |
| 36 | + { |
| 37 | + if (!$this->phpVersion->throwsValueErrorForInvalidRoundingMode()) { |
| 38 | + return new VoidType(); |
| 39 | + } |
| 40 | + |
| 41 | + $args = $funcCall->getArgs(); |
| 42 | + foreach ($args as $arg) { |
| 43 | + if ($arg->unpack || $arg->name !== null) { |
| 44 | + return $functionReflection->getThrowType(); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if (count($args) < 3) { |
| 49 | + return new VoidType(); |
| 50 | + } |
| 51 | + |
| 52 | + $validModeType = TypeCombinator::union( |
| 53 | + new ObjectType('RoundingMode'), |
| 54 | + IntegerRangeType::fromInterval(1, 8), |
| 55 | + ); |
| 56 | + if ($validModeType->isSuperTypeOf($scope->getNativeType($args[2]->value))->yes()) { |
| 57 | + return new VoidType(); |
| 58 | + } |
| 59 | + |
| 60 | + return $functionReflection->getThrowType(); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments