Skip to content

Commit

Permalink
prevent false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Sep 9, 2024
1 parent 1ca86c3 commit f8faf37
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Parser/TryCatchTypeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ public function beforeTraverse(array $nodes): ?array

public function enterNode(Node $node): ?Node
{
if ($node instanceof Node\Stmt || $node instanceof Node\Expr\Match_) {
if (
$node instanceof Node\Stmt
|| $node instanceof Node\Expr\Match_
|| $node instanceof Node\Expr\AssignOp\Div
|| $node instanceof Node\Expr\AssignOp\Mod
|| $node instanceof Node\Expr\BinaryOp\Div
|| $node instanceof Node\Expr\BinaryOp\Mod
) {
if (count($this->typeStack) > 0) {
$node->setAttribute(self::ATTRIBUTE_NAME, $this->typeStack[count($this->typeStack) - 1]);
}
Expand Down
18 changes: 18 additions & 0 deletions src/Rules/Operators/InvalidBinaryOperationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@

namespace PHPStan\Rules\Operators;

use DivisionByZeroError;
use PhpParser\Node;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\Parser\TryCatchTypeVisitor;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\VerbosityLevel;
use function array_map;
use function sprintf;
use function strlen;
use function substr;
Expand Down Expand Up @@ -118,6 +123,7 @@ public function processNode(Node $node, Scope $scope): array
|| $node instanceof Node\Expr\BinaryOp\Div
|| $node instanceof Node\Expr\BinaryOp\Mod
)
&& !$this->isDivisionByZeroCaught($node)
) {
$zeroType = new ConstantIntegerType(0);
if ($zeroType->isSuperTypeOf($rightType)->maybe()) {
Expand Down Expand Up @@ -151,4 +157,16 @@ public function processNode(Node $node, Scope $scope): array
];
}

private function isDivisionByZeroCaught(Node $node): bool
{
$tryCatchTypes = $node->getAttribute(TryCatchTypeVisitor::ATTRIBUTE_NAME);
if ($tryCatchTypes === null) {
return false;
}

$tryCatchType = TypeCombinator::union(...array_map(static fn (string $class) => new ObjectType($class), $tryCatchTypes));

return $tryCatchType->isSuperTypeOf(new ObjectType(DivisionByZeroError::class))->yes();
}

}

0 comments on commit f8faf37

Please sign in to comment.