From 565888d6e2d73216c32572837866c1e6133d0cff Mon Sep 17 00:00:00 2001 From: orklah Date: Wed, 1 Dec 2021 23:15:29 +0100 Subject: [PATCH 1/2] flag usage of get_class outside class without args --- src/Psalm/Context.php | 1 + .../Expression/Call/ArgumentsAnalyzer.php | 16 ++++++++++++++++ tests/FunctionCallTest.php | 6 ++++++ 3 files changed, 23 insertions(+) diff --git a/src/Psalm/Context.php b/src/Psalm/Context.php index e4d57d3cd9f..e62a04fe1e8 100644 --- a/src/Psalm/Context.php +++ b/src/Psalm/Context.php @@ -107,6 +107,7 @@ class Context /** * @var string|null + * The name of the current class. Null if outside a class. */ public $self; diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php index 7c2b3d0d3df..7df88bf2778 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php @@ -868,6 +868,22 @@ public static function checkArgumentsMatch( return null; } + if ($method_id === 'get_class' && $args === []) { + //get_class without args only works when inside a class + if (!$context->self) { + IssueBuffer::maybeAdd( + new TooFewArguments( + 'Cannot call get_class() without argument outside of class scope', + $code_location, + $method_id + ), + $statements_analyzer->getSuppressedIssues() + ); + } + + return null; + } + self::checkArgCount( $statements_analyzer, $codebase, diff --git a/tests/FunctionCallTest.php b/tests/FunctionCallTest.php index 19b40baf1bb..4896559321f 100644 --- a/tests/FunctionCallTest.php +++ b/tests/FunctionCallTest.php @@ -2273,6 +2273,12 @@ function takesAString(string $s): void{ takesAString(false);', 'error_message' => 'InvalidArgument' ], + 'getClassWithoutArgsOutsideClass' => [ + ' 'TooFewArguments', + ], ]; } From ac0f1df018ceba95d89bf032b65512838b0c9415 Mon Sep 17 00:00:00 2001 From: orklah Date: Wed, 1 Dec 2021 23:23:00 +0100 Subject: [PATCH 2/2] only return when we found an error --- .../Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php index 7df88bf2778..debc0eaa0ad 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/Call/ArgumentsAnalyzer.php @@ -879,9 +879,9 @@ public static function checkArgumentsMatch( ), $statements_analyzer->getSuppressedIssues() ); - } - return null; + return null; + } } self::checkArgCount(