|
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) : array |
|
|
|
|
|
|
34
|
|
|
{ |
|
35
|
|
|
$response = $this->client->get($url, ['query' => $parameters]); |
|
36
|
|
|
if (!$response instanceof ResponseInterface) { |
|
37
|
|
|
throw new ResponseIsNotValidInstance(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
return json_decode($response->getBody()->getContents(), true); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function post(string $url, array $parameters) : array |
|
44
|
|
|
{ |
|
45
|
|
|
return $this->internalPost($url, $parameters); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function put(string $url, array $parameters) : array |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->internalPost($url, $parameters); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function delete(string $url, array $parameters) : array |
|
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 ResponseIsNotValidInstance(); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return json_decode($response->getBody()->getContents(), true); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.