1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace TheHorhe\ApiClient; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use GuzzleHttp\Psr7\Request; |
7
|
|
|
use function GuzzleHttp\Psr7\try_fopen; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* TODO: ApiClientInterface |
13
|
|
|
* |
14
|
|
|
* Class ApiClient |
15
|
|
|
* @package TheHorhe\ApiClient |
16
|
|
|
*/ |
17
|
|
|
class ApiClient |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @param MethodInterface $method |
21
|
|
|
* @return mixed |
22
|
|
|
*/ |
23
|
|
|
public function executeMethod(MethodInterface $method) |
24
|
|
|
{ |
25
|
|
|
$this->preprocessMethod($method); |
26
|
|
|
|
27
|
|
|
$client = $this->createClient(); |
28
|
|
|
$request = $this->buildRequest($method); |
29
|
|
|
|
30
|
|
|
try { |
31
|
|
|
$response = $client->send($request, [ |
32
|
|
|
'timeout' => $method->getTimeout() |
33
|
|
|
]); |
34
|
|
|
|
35
|
|
|
$this->preprocessResponse($response); |
36
|
|
|
|
37
|
|
|
$result = $method->processResponse($response); |
38
|
|
|
return $result; |
39
|
|
|
} catch (\Throwable $exception) { |
40
|
|
|
$method->handleException($exception); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* TODO: Method body |
46
|
|
|
* Parameters: Get -> query / Post -> body |
47
|
|
|
* |
48
|
|
|
* @param MethodInterface $method |
49
|
|
|
* @return RequestInterface |
50
|
|
|
*/ |
51
|
|
|
protected function buildRequest(MethodInterface $method) |
52
|
|
|
{ |
53
|
|
|
$parameters = http_build_query($method->getQueryParameters()); |
54
|
|
|
|
55
|
|
|
$request = new Request( |
56
|
|
|
$method->getHttpMethod(), |
57
|
|
|
sprintf('%s://%s%s?%s', $method->getScheme(), $method->getHost(), $method->getMethodUrl(), $parameters), |
58
|
|
|
$method->getHeaders(), |
59
|
|
|
$method->getRawBody() |
60
|
|
|
); |
61
|
|
|
|
62
|
|
|
return $request; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @return Client |
67
|
|
|
*/ |
68
|
|
|
protected function createClient() |
69
|
|
|
{ |
70
|
|
|
return new Client(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Methods allows add some common operations, e.g. add body parameter to the body of all methods executed by this client. |
75
|
|
|
* |
76
|
|
|
* @param MethodInterface $method |
77
|
|
|
*/ |
78
|
|
|
protected function preprocessMethod(MethodInterface $method) |
|
|
|
|
79
|
|
|
{ |
80
|
|
|
return; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Use this to modify response before processing |
85
|
|
|
* |
86
|
|
|
* @param ResponseInterface $response |
87
|
|
|
*/ |
88
|
|
|
protected function preprocessResponse(ResponseInterface $response) |
|
|
|
|
89
|
|
|
{ |
90
|
|
|
return; |
91
|
|
|
} |
92
|
|
|
} |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.