-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCallableMapProvider.php
More file actions
71 lines (60 loc) · 2.05 KB
/
CallableMapProvider.php
File metadata and controls
71 lines (60 loc) · 2.05 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
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
/**
* Copyright 2026 The Horde Project (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*/
namespace Horde\Rpc\JsonRpc\Dispatch;
/**
* Generic provider backed by a callable map.
*
* Each method is a name→callable pair. Implements both ApiProviderInterface
* (method registry) and MethodInvokerInterface (method execution), making it
* a convenient all-in-one for simple APIs.
*
* Example usage:
*
* $provider = new CallableMapProvider([
* 'math.add' => fn(float $a, float $b): float => $a + $b,
* 'ping' => fn(): string => 'pong',
* ]);
*/
final class CallableMapProvider implements ApiProviderInterface, MethodInvokerInterface
{
/** @var array<string, callable> */
private readonly array $methods;
/** @var array<string, MethodDescriptor> */
private readonly array $descriptors;
/**
* @param array<string, callable> $methods Name→callable map
* @param array<string, MethodDescriptor> $descriptors Optional descriptors keyed by method name.
* Methods without an explicit descriptor get a minimal auto-generated one.
*/
public function __construct(array $methods, array $descriptors = [])
{
$this->methods = $methods;
$merged = [];
foreach ($methods as $name => $callable) {
$merged[$name] = $descriptors[$name] ?? new MethodDescriptor($name);
}
$this->descriptors = $merged;
}
public function hasMethod(string $method): bool
{
return isset($this->methods[$method]);
}
public function getMethodDescriptor(string $method): ?MethodDescriptor
{
return $this->descriptors[$method] ?? null;
}
public function listMethods(): array
{
return array_values($this->descriptors);
}
public function invoke(string $method, array $params): Result
{
return new Result(($this->methods[$method])(...$params));
}
}