1
0
Fork 0

feat(diagnostics): emit error when $this is used in a static method, or outside a class method.

pull/528/head
Maarten Staa 2017-11-15 22:01:32 +01:00
parent 1ec8d8d8e2
commit 988ce0358a
1 changed files with 19 additions and 0 deletions

View File

@ -68,6 +68,7 @@ class TreeAnalyzer
*/ */
private function collectDiagnostics($node) private function collectDiagnostics($node)
{ {
// Get errors from the parser.
if (($error = PhpParser\DiagnosticsProvider::checkDiagnostics($node)) !== null) { if (($error = PhpParser\DiagnosticsProvider::checkDiagnostics($node)) !== null) {
$range = PhpParser\PositionUtilities::getRangeFromPosition($error->start, $error->length, $this->sourceFileNode->fileContents); $range = PhpParser\PositionUtilities::getRangeFromPosition($error->start, $error->length, $this->sourceFileNode->fileContents);
@ -92,6 +93,24 @@ class TreeAnalyzer
'php' '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'
);
}
}
} }
/** /**