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

Flag class constant references where LHS is ordinary string #9302

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
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Psalm\Issue\InternalClass;
use Psalm\Issue\InvalidClassConstantType;
use Psalm\Issue\InvalidConstantAssignmentValue;
use Psalm\Issue\InvalidStringClass;
use Psalm\Issue\LessSpecificClassConstantType;
use Psalm\Issue\NonStaticSelfCall;
use Psalm\Issue\OverriddenFinalConstant;
Expand All @@ -41,6 +42,7 @@
use Psalm\Type\Atomic\TMixed;
use Psalm\Type\Atomic\TNamedObject;
use Psalm\Type\Atomic\TObject;
use Psalm\Type\Atomic\TString;
use Psalm\Type\Atomic\TTemplateParam;
use Psalm\Type\Atomic\TTemplateParamClass;
use Psalm\Type\Union;
Expand Down Expand Up @@ -467,6 +469,17 @@ public static function analyzeFetch(
} elseif ($atomic_type instanceof TLiteralClassString) {
$fq_class_name = $atomic_type->value;
$lhs_type_definite_class = $atomic_type->definite_class;
} elseif ($atomic_type instanceof TString
&& !$atomic_type instanceof TClassString
&& !$codebase->config->allow_string_standin_for_class
) {
IssueBuffer::maybeAdd(
new InvalidStringClass(
'String cannot be used as a class',
new CodeLocation($statements_analyzer->getSource(), $stmt->class),
),
$statements_analyzer->getSuppressedIssues(),
);
}
}

Expand Down
12 changes: 12 additions & 0 deletions tests/ConstantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2030,6 +2030,18 @@ class Foo
'ignored_issues' => [],
'php_version' => '8.0',
],
'classStringIsRequiredToAccessClassConstant' => [
'code' => '<?php
class Foo {
public const BAR = "bar";
}

$class = "Foo";

$class::BAR;
',
'error_message' => 'InvalidStringClass',
],
];
}
}
1 change: 1 addition & 0 deletions tests/DocumentationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ public function testShortcodesAreUnique(): void
$all_shortcodes = [];

foreach ($all_issues as $issue_type) {
/** @var class-string $issue_class */
$issue_class = '\\Psalm\\Issue\\' . $issue_type;
/** @var int $shortcode */
$shortcode = $issue_class::SHORTCODE;
Expand Down