1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Stack Exchange Api Client library. |
5
|
|
|
* |
6
|
|
|
* (c) Beñat Espiña <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace BenatEspina\StackExchangeApiClient\Http; |
15
|
|
|
|
16
|
|
|
use GuzzleHttp\Client; |
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @author Beñat Espiña <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
final class GuzzleHttpClient implements HttpClient |
23
|
|
|
{ |
24
|
|
|
private $client; |
25
|
|
|
|
26
|
|
|
public function __construct() |
27
|
|
|
{ |
28
|
|
|
$this->client = new Client([ |
29
|
|
|
'base_uri' => HttpClient::BASE_URL, |
30
|
|
|
]); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
View Code Duplication |
public function get(string $url, array $parameters) |
|
|
|
|
34
|
|
|
{ |
35
|
|
|
$response = $this->client->get($url, ['query' => $parameters]); |
36
|
|
|
if (!$response instanceof ResponseInterface) { |
37
|
|
|
throw new \Exception('The response must be implements the ResponseInterface'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return json_decode($response->getBody()->getContents(), true); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function post(string $url, array $parameters) |
|
|
|
|
44
|
|
|
{ |
45
|
|
|
return $this->internalPost($url, $parameters); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function put(string $url, array $parameters) |
|
|
|
|
49
|
|
|
{ |
50
|
|
|
return $this->internalPost($url, $parameters); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function delete(string $url, array $parameters) |
|
|
|
|
54
|
|
|
{ |
55
|
|
|
return $this->internalPost($url, $parameters); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
View Code Duplication |
private function internalPost(string $url, array $parameters) |
|
|
|
|
59
|
|
|
{ |
60
|
|
|
$response = $this->client->post($url, ['form_params' => $parameters]); |
61
|
|
|
if (!$response instanceof ResponseInterface) { |
62
|
|
|
throw new \Exception('The response must be implements the ResponseInterface'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return json_decode($response->getBody()->getContents(), true); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.