1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Tools\Services\XmlRpc; |
4
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Transport\Service\RequestService; |
6
|
|
|
use ApiClients\Middleware\Xml\XmlStream; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use RingCentral\Psr7\Request; |
9
|
|
|
use function React\Promise\reject; |
10
|
|
|
use function React\Promise\resolve; |
11
|
|
|
|
12
|
|
|
class XmlRpcService |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var RequestService |
16
|
|
|
*/ |
17
|
|
|
private $requestService; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param RequestService $requestService |
21
|
|
|
*/ |
22
|
|
|
public function __construct(RequestService $requestService) |
23
|
|
|
{ |
24
|
|
|
$this->requestService = $requestService; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function call(string $method, array $arguments = []) |
28
|
|
|
{ |
29
|
|
|
$params = []; |
30
|
|
|
foreach ($arguments as $argument) { |
31
|
|
|
$params[] = [ |
32
|
|
|
'param' => [ |
33
|
|
|
'value' => [ |
34
|
|
|
gettype($argument) => $argument, |
35
|
|
|
], |
36
|
|
|
], |
37
|
|
|
]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $this->callRaw($method, $params)->then(function (array $xml) { |
41
|
|
|
return XmlRpcPayloadParser::parse($xml); |
42
|
|
|
}); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function callRaw(string $method, array $arguments = []) |
46
|
|
|
{ |
47
|
|
|
$xml = [ |
48
|
|
|
'methodCall' => [ |
49
|
|
|
'methodName' => $method, |
50
|
|
|
], |
51
|
|
|
]; |
52
|
|
|
|
53
|
|
|
if (count($arguments) > 0) { |
54
|
|
|
$xml['methodCall']['params'] = $arguments; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $this->requestService->request(new Request( |
58
|
|
|
'POST', |
59
|
|
|
'', |
60
|
|
|
[], |
61
|
|
|
new XmlStream($xml) |
62
|
|
|
))->then(function (ResponseInterface $response) { |
63
|
|
|
$xml = $response->getBody()->getParsedContents(); |
|
|
|
|
64
|
|
|
|
65
|
|
|
if (isset($xml['methodResponse']['fault'])) { |
66
|
|
|
return reject( |
67
|
|
|
new XmlRpcError( |
68
|
|
|
$xml['methodResponse']['fault']['value']['struct']['member'][1]['value']['string'], |
69
|
|
|
(int)$xml['methodResponse']['fault']['value']['struct']['member'][0]['value']['int'] |
70
|
|
|
) |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return resolve($xml['methodResponse']['params']['param']['value']); |
75
|
|
|
}); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: