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 ::class on string expression #1425

Merged
merged 1 commit into from
Sep 2, 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
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;
}

}