Skip to content

Commit 9154368

Browse files
Support switch on ::class
1 parent 02066c7 commit 9154368

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/Analyser/TypeSpecifier.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,13 +1656,11 @@ private function findTypeExpressionsFromBinaryOperation(Scope $scope, Node\Expr\
16561656
if (
16571657
$leftType instanceof ConstantScalarType
16581658
&& !$rightExpr instanceof ConstFetch
1659-
&& !$rightExpr instanceof ClassConstFetch
16601659
) {
16611660
return [$binaryOperation->right, $leftType, $rightType];
16621661
} elseif (
16631662
$rightType instanceof ConstantScalarType
16641663
&& !$leftExpr instanceof ConstFetch
1665-
&& !$leftExpr instanceof ClassConstFetch
16661664
) {
16671665
return [$binaryOperation->left, $rightType, $leftType];
16681666
}
@@ -2061,6 +2059,16 @@ public function resolveEqual(Expr\BinaryOp\Equal $expr, Scope $scope, TypeSpecif
20612059
) {
20622060
return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
20632061
}
2062+
2063+
if (
2064+
$context->true()
2065+
&& $exprNode instanceof ClassConstFetch
2066+
&& $exprNode->name instanceof Node\Identifier
2067+
&& strtolower($exprNode->name->toString()) === 'class'
2068+
&& $constantType->isString()->yes()
2069+
) {
2070+
return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context)->setRootExpr($expr);
2071+
}
20642072
}
20652073

20662074
$leftType = $scope->getType($expr->left);
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace Bug13069;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
interface ResourceInterface {}
8+
9+
class Person implements ResourceInterface
10+
{
11+
public function getName(): string { return 'Name'; }
12+
}
13+
14+
class Account implements ResourceInterface
15+
{
16+
public function getMail(): string { return 'Mail'; }
17+
}
18+
19+
function foo(?ResourceInterface $object = null): void
20+
{
21+
switch ($object::class) {
22+
case Person::class:
23+
assertType(Person::class, $object);
24+
echo $object->getName();
25+
break;
26+
case Account::class:
27+
assertType(Account::class, $object);
28+
echo $object->getMail();
29+
break;
30+
}
31+
}

0 commit comments

Comments
 (0)