-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Invoker.php
101 lines (82 loc) · 2.83 KB
/
Invoker.php
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
declare(strict_types=1);
namespace Spiral\RoadRunner\GRPC;
use Google\Protobuf\Internal\Message;
use Spiral\RoadRunner\GRPC\Exception\InvokeException;
final class Invoker implements InvokerInterface
{
private const ERROR_METHOD_RETURN =
'Method %s must return an object that instance of %s, ' .
'but the result provides type of %s';
private const ERROR_METHOD_IN_TYPE =
'Method %s input type must be an instance of %s, ' .
'but the input is type of %s';
public function invoke(
ServiceInterface $service,
Method $method,
ContextInterface $ctx,
string|Message|null $input,
): string {
/** @var callable $callable */
$callable = [$service, $method->name];
$input = $input instanceof Message ? $input : $this->makeInput($method, $input);
/** @var Message $message */
$message = $callable($ctx, $input);
\assert($this->assertResultType($method, $message));
try {
return $message->serializeToString();
} catch (\Throwable $e) {
throw InvokeException::create($e->getMessage(), StatusCode::INTERNAL, $e);
}
}
/**
* Checks that the result from the GRPC service method returns the Message object.
*
* @throws \BadFunctionCallException
*/
private function assertResultType(Method $method, mixed $result): bool
{
if (!$result instanceof Message) {
$type = \get_debug_type($result);
throw new \BadFunctionCallException(
\sprintf(self::ERROR_METHOD_RETURN, $method->name, Message::class, $type),
);
}
return true;
}
/**
* Converts the input from the GRPC service method to the Message object.
* @throws InvokeException
*/
private function makeInput(Method $method, ?string $body): Message
{
try {
$class = $method->inputType;
\assert($this->assertInputType($method, $class));
/** @psalm-suppress UnsafeInstantiation */
$in = new $class();
if ($body !== null) {
$in->mergeFromString($body);
}
return $in;
} catch (\Throwable $e) {
throw InvokeException::create($e->getMessage(), StatusCode::INTERNAL, $e);
}
}
/**
* Checks that the input of the GRPC service method contains the
* Message object.
*
* @param class-string $class
* @throws \InvalidArgumentException
*/
private function assertInputType(Method $method, string $class): bool
{
if (!\is_subclass_of($class, Message::class)) {
throw new \InvalidArgumentException(
\sprintf(self::ERROR_METHOD_IN_TYPE, $method->name, Message::class, $class),
);
}
return true;
}
}