1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-26 12:24:49 +01:00

Support completions on class references (#5085)

* Support compleitions on class references

This provides completions on class references (as opposed to initiated objects via the type map), so you can do `MyClass::` and get completitions for static methods and constants etc.

* Only provide completions for references that don't exist
This commit is contained in:
Joe Hoyle 2021-01-24 13:29:21 -05:00 committed by Daniil Gentili
parent c9129b5c4c
commit ed9043b43c
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
3 changed files with 45 additions and 1 deletions

View File

@ -1279,7 +1279,16 @@ class Codebase
} }
foreach ($reference_map as $start_pos => [$end_pos, $possible_reference]) { foreach ($reference_map as $start_pos => [$end_pos, $possible_reference]) {
if ($offset < $start_pos || $possible_reference[0] !== '*') { if ($offset < $start_pos) {
continue;
}
// If the reference precedes a "::" then treat it as a class reference.
if ($offset - $end_pos === 2 && substr($file_contents, $end_pos, 2) === '::') {
return [$possible_reference, '::', $offset];
}
// Only continue for references that are partial / don't exist.
if ($possible_reference[0] !== '*') {
continue; continue;
} }

View File

@ -1172,6 +1172,9 @@ class Analyzer
]; ];
} }
/**
* @param string $reference The symbol name for the reference. Prepend with an asterisk (*) to signify a reference that doesn't exist.
*/
public function addNodeReference(string $file_path, PhpParser\Node $node, string $reference): void public function addNodeReference(string $file_path, PhpParser\Node $node, string $reference): void
{ {
if (!$reference) { if (!$reference) {

View File

@ -766,4 +766,36 @@ class CompletionTest extends \Psalm\Tests\TestCase
$this->assertCount(2, $completion_items); $this->assertCount(2, $completion_items);
} }
public function testCompletionOnClassReference(): void
{
$codebase = $this->project_analyzer->getCodebase();
$config = $codebase->config;
$config->throw_exception = false;
$this->addFile(
'somefile.php',
'<?php
namespace Bar;
class Alpha {
const FOO = "123";
static function add() : void {
}
}
Alpha::'
);
$codebase->file_provider->openFile('somefile.php');
$codebase->scanFiles();
$this->analyzeFile('somefile.php', new Context());
$completion_data = $codebase->getCompletionDataAtPosition('somefile.php', new Position(8, 23));
$this->assertSame(['Bar\Alpha', '::', 221], $completion_data);
$completion_items = $codebase->getCompletionItemsForClassishThing($completion_data[0], $completion_data[1]);
$this->assertCount(2, $completion_items);
}
} }