1
|
|
|
<?php |
2
|
|
|
namespace Yoanm\JsonRpcServer\App\Manager; |
3
|
|
|
|
4
|
|
|
use Yoanm\JsonRpcServer\App\Creator\CustomExceptionCreator; |
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcMethodInterface; |
6
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\MethodResolverInterface; |
7
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface; |
8
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcInvalidParamsException; |
9
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcMethodNotFoundException; |
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
|
|
|
public function __construct(MethodResolverInterface $methodResolver, CustomExceptionCreator $customExceptionCreator) |
26
|
|
|
{ |
27
|
|
|
$this->methodResolver = $methodResolver; |
28
|
|
|
$this->customExceptionCreator = $customExceptionCreator; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $methodName |
33
|
|
|
* @param array $paramList |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
* |
37
|
|
|
* @throws JsonRpcInvalidParamsException |
38
|
|
|
* @throws JsonRpcMethodNotFoundException |
39
|
|
|
* @throws JsonRpcExceptionInterface |
40
|
|
|
*/ |
41
|
|
|
public function apply(string $methodName, array $paramList = null) |
42
|
|
|
{ |
43
|
|
|
$method = $this->methodResolver->resolve($methodName); |
44
|
|
|
|
45
|
|
|
$this->validateParamsIfNeeded($method, $methodName, $paramList); |
|
|
|
|
46
|
|
|
|
47
|
|
|
try { |
48
|
|
|
return $method->apply($paramList); |
49
|
|
|
} catch (\Exception $applyException) { |
50
|
|
|
throw $this->customExceptionCreator->createFor($applyException); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param JsonRpcMethodInterface $method |
56
|
|
|
* @param string $methodName |
57
|
|
|
* @param array $paramList |
58
|
|
|
* |
59
|
|
|
* @throws JsonRpcInvalidParamsException |
60
|
|
|
* |
61
|
|
|
* @return void |
62
|
|
|
*/ |
63
|
|
|
private function validateParamsIfNeeded(JsonRpcMethodInterface $method, string $methodName, array $paramList) |
64
|
|
|
{ |
65
|
|
|
if (is_array($paramList)) { |
|
|
|
|
66
|
|
|
try { |
67
|
|
|
$method->validateParams($paramList); |
68
|
|
|
} catch (\Exception $validationException) { |
69
|
|
|
throw new JsonRpcInvalidParamsException( |
70
|
|
|
$methodName, |
71
|
|
|
$validationException->getMessage() |
72
|
|
|
); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|