Skip to content

Commit f18aaac

Browse files
authored
[DeadCode] Skip assert() enforcement that produce NeverType on NarrowWideUnionReturnTypeRector (#8282)
* [DeadCode] Skip assert() enforcement that produce NeverType on NarrowWideUnionReturnTypeRector * [DeadCode] Skip assert() enforcement that produce NeverType on NarrowWideUnionReturnTypeRector
1 parent 760f8c0 commit f18aaac

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\FunctionLike\NarrowWideUnionReturnTypeRector\Fixture;
4+
5+
final class SkipAssert
6+
{
7+
/**
8+
* @var array{
9+
* cache: array{directory: null}
10+
* }
11+
*/
12+
protected array $config = [
13+
'cache' => [
14+
'directory' => null,
15+
],
16+
];
17+
18+
public function getCacheDirectory(): ?string
19+
{
20+
$dir = $this->config['cache']['directory'] ?? null;
21+
\assert(\is_string($dir) || $dir === null, 'Invalid cache directory.');
22+
23+
return $dir;
24+
}
25+
}
26+

‎rules/DeadCode/Rector/FunctionLike/NarrowWideUnionReturnTypeRector.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use PhpParser\Node\UnionType;
2121
use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
2222
use PHPStan\Reflection\ClassReflection;
23+
use PHPStan\Type\NeverType;
2324
use PHPStan\Type\NullType;
2425
use PHPStan\Type\ObjectType;
2526
use PHPStan\Type\Type;
@@ -272,6 +273,13 @@ private function collectActualReturnTypes(array $returnStatements): array
272273
private function resolveNativeReturnTypes(Expr $expr): array
273274
{
274275
if (! $expr instanceof Ternary || ! $this->hasVendorClassConstFetch($expr->cond)) {
276+
$type = $this->nodeTypeResolver->getType($expr);
277+
278+
// native type may be narrowed by assertions even when the resolved scope is unreachable
279+
if ($type instanceof NeverType) {
280+
return [$type];
281+
}
282+
275283
return [$this->nodeTypeResolver->getNativeType($expr)];
276284
}
277285

0 commit comments

Comments
 (0)