Skip to content

Commit

Permalink
Flag class constant references where LHS is ordinary string
Browse files Browse the repository at this point in the history
Fixes #2185
  • Loading branch information
weirdan committed Feb 15, 2023
1 parent d9161c3 commit 8c491e9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
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
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',
],
];
}
}

0 comments on commit 8c491e9

Please sign in to comment.