forked from phpactor/language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandDispatcher.php
More file actions
60 lines (52 loc) · 1.43 KB
/
CommandDispatcher.php
File metadata and controls
60 lines (52 loc) · 1.43 KB
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
51
52
53
54
55
56
57
58
59
60
<?php
namespace Phpactor\LanguageServer\Core\Command;
use Amp\Promise;
use RuntimeException;
/**
* Commands can be registered using this class.
*/
class CommandDispatcher
{
/**
* @param array<string,Command> $commandMap Map of command names to invokable objects
*/
public function __construct(private array $commandMap = [])
{
foreach ($commandMap as $id => $command) {
$this->addCommand($id, $command);
}
}
/**
* @return array<string>
*/
public function registeredCommands(): array
{
return array_keys($this->commandMap);
}
/**
* @param array<int,mixed> $args
*
* @return Promise<mixed>
*/
public function dispatch(string $command, array $args = []): Promise
{
if (!isset($this->commandMap[$command])) {
throw new RuntimeException(sprintf(
'Command "%s" not found, known commands: "%s"',
$command,
implode('", "', array_keys($this->commandMap))
));
}
return $this->commandMap[$command]->__invoke(...$args);
}
private function addCommand(string $id, Command $invokable): void
{
if (!is_callable($invokable)) {
throw new RuntimeException(sprintf(
'Object "%s" is not invokable',
$invokable::class
));
}
$this->commandMap[$id] = $invokable;
}
}