Skip to content

Commit 029c183

Browse files
committed
string cast might throw exception
1 parent 178939a commit 029c183

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Analyser/NodeScopeResolver.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3619,6 +3619,12 @@ static function (): void {
36193619
$exprType = $scope->getType($expr->expr);
36203620
$toStringMethod = $scope->getMethodReflection($exprType, '__toString');
36213621
if ($toStringMethod !== null) {
3622+
if ($toStringMethod->getThrowType() !== null) {
3623+
$throwPoints[] = InternalThrowPoint::createExplicit($scope, $toStringMethod->getThrowType(), $expr, false);
3624+
} else {
3625+
$throwPoints[] = InternalThrowPoint::createImplicit($scope, $expr);
3626+
}
3627+
36223628
if (!$toStringMethod->hasSideEffects()->no()) {
36233629
$impurePoints[] = new ImpurePoint(
36243630
$scope,

tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,4 +643,9 @@ public function testPropertyHooks(): void
643643
]);
644644
}
645645

646+
public function testBug13806(): void
647+
{
648+
$this->analyse([__DIR__ . '/data/bug-13806.php'], []);
649+
}
650+
646651
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Bug13806;
4+
5+
function doFoo(MyString $myVariable): void
6+
{
7+
try {
8+
(string) $myVariable;
9+
} catch (\InvalidArgumentException) {
10+
// Reported as dead catch, even though the `__toString()` method
11+
// in `$myVariable` might throw an exception.
12+
}
13+
}
14+
15+
class MyString {
16+
/** @throws \InvalidArgumentException */
17+
public function __toString() {
18+
throw new \InvalidArgumentException();
19+
}
20+
}

0 commit comments

Comments
 (0)