Code Action Provider

Code action providers can be implemented to enable you to suggest commands which can be executed on a given text document and range.

Example

Example of a command:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

namespace Phpactor\LanguageServer\Example\CodeAction;

use Amp\CancellationToken;
use Amp\Promise;
use Phpactor\LanguageServerProtocol\CodeAction;
use Phpactor\LanguageServerProtocol\CodeActionKind;
use Phpactor\LanguageServerProtocol\Command;
use Phpactor\LanguageServerProtocol\Range;
use Phpactor\LanguageServerProtocol\TextDocumentItem;
use Phpactor\LanguageServer\Core\CodeAction\CodeActionProvider;
use function Amp\call;

class SayHelloCodeActionProvider implements CodeActionProvider
{
    public function provideActionsFor(TextDocumentItem $textDocument, Range $range, CancellationToken $cancel): Promise
    {
        /** @phpstan-ignore-next-line */
        return call(function (): array {
            return [
                CodeAction::fromArray([
                    'title' => 'Alice',
                    'command' => new Command('Hello Alice', 'phpactor.say_hello', [
                        'Alice',
                    ])
                ]),
                CodeAction::fromArray([
                    'title' => 'Bob',
                    'command' => new Command('Hello Bob', 'phpactor.say_hello', [
                        'Bob',
                    ])
                ])
            ];
        });
    }

    /**
     * {@inheritDoc}
     */
    public function kinds(): array
    {
        return [CodeActionKind::QUICK_FIX];
    }

    public function describe(): string
    {
        return 'says hello!';
    }
}

It unconditionally provides two code actions: Alice and Bob. It references a previously registered commands such as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

namespace Phpactor\LanguageServer\Example\Command;

use Phpactor\LanguageServer\Core\Command\Command;
use Phpactor\LanguageServer\Core\Server\ClientApi;

class SayHelloCommand implements Command
{
    /**
     * @var ClientApi
     */
    private $api;

    public function __construct(ClientApi $api)
    {
        $this->api = $api;
    }

    public function __invoke(string $name): void
    {
        $this->api->window()->showMessage()->info(sprintf('Hello %s!', $name));
    }
}