Skip to content

Commit

Permalink
Fix ::class on string expression
Browse files Browse the repository at this point in the history
  • Loading branch information
rvanvelzen committed Sep 2, 2022
1 parent c057aa9 commit bb30737
Show file tree
Hide file tree
Showing 5 changed files with 9 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Reflection/InitializerExprTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,8 @@ public function getClassConstFetchTypeByReflection(Name|Expr $class, string $con
if (strtolower($constantName) === 'class') {
return new ConstantStringType($constantClassType->getClassName(), true);
}
} elseif ($class instanceof String_ && strtolower($constantName) === 'class') {
return new ConstantStringType($class->value, true);
} else {
$constantClassType = $getTypeCallback($class);
$isObject = true;
Expand Down
2 changes: 1 addition & 1 deletion src/Rules/Classes/ClassConstantRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public function processNode(Node $node, Scope $scope): array
];
}

if ($classType->isString()->yes()) {
if (!$class instanceof Node\Scalar\String_ && $classType->isString()->yes()) {
return [
RuleErrorBuilder::message('Accessing ::class constant on a dynamic string is not supported in PHP.')
->nonIgnorable()
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/data/class-constant-on-expr.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public function doFoo(
assertType('*ERROR*', $string::class);
assertType('class-string<stdClass>|null', $stdOrNull::class);
assertType('*ERROR*', $stringOrNull::class);
assertType("'Foo'", 'Foo'::class);
}

}
4 changes: 4 additions & 0 deletions tests/PHPStan/Rules/Classes/ClassConstantRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ public function dataClassConstantOnExpression(): array
'Accessing ::class constant on an expression is supported only on PHP 8.0 and later.',
18,
],
[
'Accessing ::class constant on an expression is supported only on PHP 8.0 and later.',
19,
],
],
],
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public function doFoo(
echo $string::class;
echo $stdOrNull::class;
echo $stringOrNull::class;
echo 'Foo'::class;
}

}

0 comments on commit bb30737

Please sign in to comment.