From 988ce0358a5d8db9e0fd051bd1c674fc9e84a2c0 Mon Sep 17 00:00:00 2001 From: Maarten Staa Date: Wed, 15 Nov 2017 22:01:32 +0100 Subject: [PATCH] feat(diagnostics): emit error when $this is used in a static method, or outside a class method. --- src/TreeAnalyzer.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/TreeAnalyzer.php b/src/TreeAnalyzer.php index 58de8db..08b7c12 100644 --- a/src/TreeAnalyzer.php +++ b/src/TreeAnalyzer.php @@ -68,6 +68,7 @@ class TreeAnalyzer */ private function collectDiagnostics($node) { + // Get errors from the parser. if (($error = PhpParser\DiagnosticsProvider::checkDiagnostics($node)) !== null) { $range = PhpParser\PositionUtilities::getRangeFromPosition($error->start, $error->length, $this->sourceFileNode->fileContents); @@ -92,6 +93,24 @@ class TreeAnalyzer 'php' ); } + + // Check for invalid usage of $this. + if ($node instanceof Node\Expression\Variable && $node->getName() === 'this') { + // Find the first ancestor that's a class method. Return an error + // if there is none, or if the method is static. + $method = $node->getFirstAncestor(Node\MethodDeclaration::class); + if ($method === null || $method->isStatic()) { + $this->diagnostics[] = new Diagnostic( + $method === null + ? "\$this can only be used in an object context." + : "\$this can not be used in static methods.", + Range::fromNode($node), + null, + DiagnosticSeverity::ERROR, + 'php' + ); + } + } } /**