1
|
|
|
<?php |
2
|
|
|
namespace Yoanm\JsonRpcServer\App\Manager; |
3
|
|
|
|
4
|
|
|
use Yoanm\JsonRpcServer\App\Creator\CustomExceptionCreator; |
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface; |
6
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcInvalidParamsException; |
7
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcMethodNotFoundException; |
8
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcMethodInterface; |
9
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\MethodResolverInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class MethodManager |
13
|
|
|
*/ |
14
|
|
|
class MethodManager |
15
|
|
|
{ |
16
|
|
|
/** @var MethodResolverInterface */ |
17
|
|
|
private $methodResolver; |
18
|
|
|
/** @var CustomExceptionCreator */ |
19
|
|
|
private $customExceptionCreator; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param MethodResolverInterface $methodResolver |
23
|
|
|
* @param CustomExceptionCreator $customExceptionCreator |
24
|
|
|
*/ |
25
|
4 |
|
public function __construct(MethodResolverInterface $methodResolver, CustomExceptionCreator $customExceptionCreator) |
26
|
|
|
{ |
27
|
4 |
|
$this->methodResolver = $methodResolver; |
28
|
4 |
|
$this->customExceptionCreator = $customExceptionCreator; |
29
|
4 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $methodName |
33
|
|
|
* @param array|null $paramList |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
* |
37
|
|
|
* @throws JsonRpcInvalidParamsException |
38
|
|
|
* @throws JsonRpcMethodNotFoundException |
39
|
|
|
* @throws JsonRpcExceptionInterface |
40
|
|
|
*/ |
41
|
4 |
|
public function apply(string $methodName, array $paramList = null) |
42
|
|
|
{ |
43
|
4 |
|
$method = $this->methodResolver->resolve($methodName); |
44
|
|
|
|
45
|
4 |
|
if (!$method instanceof JsonRpcMethodInterface) { |
46
|
1 |
|
throw new JsonRpcMethodNotFoundException($methodName); |
47
|
|
|
} |
48
|
|
|
|
49
|
3 |
|
$this->validateParams($method, $paramList); |
50
|
|
|
|
51
|
|
|
try { |
52
|
2 |
|
return $method->apply($paramList); |
53
|
1 |
|
} catch (\Exception $applyException) { |
54
|
1 |
|
throw $this->customExceptionCreator->createFor($applyException); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param JsonRpcMethodInterface $method |
60
|
|
|
* @param array|null $paramList |
61
|
|
|
* |
62
|
|
|
* @throws JsonRpcInvalidParamsException |
63
|
|
|
* |
64
|
|
|
* @return void |
65
|
|
|
*/ |
66
|
3 |
|
private function validateParams(JsonRpcMethodInterface $method, $paramList) |
67
|
|
|
{ |
68
|
3 |
|
$violationList = $method->validateParams($paramList ?? []); |
69
|
|
|
|
70
|
3 |
|
if (count($violationList)) { |
71
|
1 |
|
throw new JsonRpcInvalidParamsException($violationList); |
72
|
|
|
} |
73
|
2 |
|
} |
74
|
|
|
} |
75
|
|
|
|