|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Analyser\Generator\ExprHandler; |
| 4 | + |
| 5 | +use Generator; |
| 6 | +use PhpParser\Node\Expr; |
| 7 | +use PhpParser\Node\Scalar\Int_; |
| 8 | +use PhpParser\Node\Stmt; |
| 9 | +use PHPStan\Analyser\ExpressionContext; |
| 10 | +use PHPStan\Analyser\Generator\ExprAnalysisRequest; |
| 11 | +use PHPStan\Analyser\Generator\ExprAnalysisResult; |
| 12 | +use PHPStan\Analyser\Generator\ExprHandler; |
| 13 | +use PHPStan\Analyser\Generator\GeneratorScope; |
| 14 | +use PHPStan\Analyser\Generator\NoopNodeCallback; |
| 15 | +use PHPStan\Analyser\SpecifiedTypes; |
| 16 | +use PHPStan\DependencyInjection\AutowiredService; |
| 17 | +use PHPStan\Reflection\InitializerExprTypeResolver; |
| 18 | +use PHPStan\Type\IntegerRangeType; |
| 19 | + |
| 20 | +/** |
| 21 | + * @implements ExprHandler<Expr\UnaryMinus> |
| 22 | + */ |
| 23 | +#[AutowiredService] |
| 24 | +final class UnaryMinusHandler implements ExprHandler |
| 25 | +{ |
| 26 | + |
| 27 | + public function __construct(private InitializerExprTypeResolver $initializerExprTypeResolver) |
| 28 | + { |
| 29 | + } |
| 30 | + |
| 31 | + public function supports(Expr $expr): bool |
| 32 | + { |
| 33 | + return $expr instanceof Expr\UnaryMinus; |
| 34 | + } |
| 35 | + |
| 36 | + public function analyseExpr(Stmt $stmt, Expr $expr, GeneratorScope $scope, ExpressionContext $context, ?callable $alternativeNodeCallback): Generator |
| 37 | + { |
| 38 | + $result = yield new ExprAnalysisRequest($stmt, $expr->expr, $scope, $context->enterDeep(), $alternativeNodeCallback); |
| 39 | + |
| 40 | + $type = $this->initializerExprTypeResolver->getUnaryMinusTypeFromType($expr->expr, $result->type); |
| 41 | + $nativeType = $this->initializerExprTypeResolver->getUnaryMinusTypeFromType($expr->expr, $result->nativeType); |
| 42 | + if ($type instanceof IntegerRangeType) { |
| 43 | + $mulResult = yield new ExprAnalysisRequest($stmt, new Expr\BinaryOp\Mul($expr, new Int_(-1)), $scope, $context->enterDeep(), new NoopNodeCallback()); |
| 44 | + $type = $mulResult->type; |
| 45 | + $nativeType = $mulResult->nativeType; |
| 46 | + } |
| 47 | + |
| 48 | + return new ExprAnalysisResult( |
| 49 | + $type, |
| 50 | + $nativeType, |
| 51 | + $result->scope, |
| 52 | + hasYield: $result->hasYield, |
| 53 | + isAlwaysTerminating: $result->isAlwaysTerminating, |
| 54 | + throwPoints: $result->throwPoints, |
| 55 | + impurePoints: $result->impurePoints, |
| 56 | + specifiedTruthyTypes: new SpecifiedTypes(), |
| 57 | + specifiedFalseyTypes: new SpecifiedTypes(), |
| 58 | + specifiedNullTypes: new SpecifiedTypes(), |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments