Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/issue 5903 #1051

Merged
merged 5 commits into from
Mar 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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) {
}
}
}