Skip to content

Commit

Permalink
Fix dead catch when iterating objects
Browse files Browse the repository at this point in the history
  • Loading branch information
rajyan committed Mar 6, 2022
1 parent 6525d68 commit d32942a
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
use PHPStan\Type\UnionType;
use PHPStan\Type\VoidType;
use Throwable;
use Traversable;
use function array_fill_keys;
use function array_filter;
use function array_key_exists;
Expand Down Expand Up @@ -823,6 +824,9 @@ private function processStmtNode(
if (!$isIterableAtLeastOnce->no()) {
$throwPoints = array_merge($throwPoints, $finalScopeResult->getThrowPoints());
}
if (!(new ObjectType(Traversable::class))->isSuperTypeOf($scope->getType($stmt->expr))->no()) {
$throwPoints[] = ThrowPoint::createImplicit($scope, $stmt->expr);
}

return new StatementResult(
$finalScope,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,20 @@ public function testFirstClassCallables(): void
]);
}

public function testBug5903(): void
{
$this->analyse([__DIR__ . '/data/bug-5903.php'], [
[
'Dead catch - Throwable is never thrown in the try block.',
47,
],
[
'Dead catch - Throwable is never thrown in the try block.',
54,
],
]);
}

public function testBug6262(): void
{
$this->analyse([__DIR__ . '/data/bug-6262.php'], []);
Expand Down
64 changes: 64 additions & 0 deletions tests/PHPStan/Rules/Exceptions/data/bug-5903.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace Bug5903;

class Test
{
/** @var \Traversable<string> */
protected $traversable;
/** @var \Iterator<string> */
protected $iterator;
/** @var iterable<string> */
protected $iterable;
/** @var array<string> */
protected $array;
/** @var array<string>|null */
protected $maybeArray;
/** @var \Iterator<string>|null */
protected $maybeIterable;

public function foo()
{
try {
foreach ($this->traversable as $val) {
echo $val;
}
} catch (\Throwable $e) {
}

try {
foreach ($this->iterator as $val) {
echo $val;
}
} catch (\Throwable $e) {
}

try {
foreach ($this->iterable as $val) {
echo $val;
}
} catch (\Throwable $e) {
}

try {
foreach ($this->array as $val) {
echo $val;
}
} catch (\Throwable $e) {
}

try {
foreach ($this->maybeArray as $val) {
echo $val;
}
} catch (\Throwable $e) {
}

try {
foreach ($this->maybeIterable as $val) {
echo $val;
}
} catch (\Throwable $e) {
}
}
}

0 comments on commit d32942a

Please sign in to comment.