1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Waredesk; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Exception\ClientException; |
6
|
|
|
use GuzzleHttp\Psr7\Request as GuzzleRequest; |
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Waredesk\Exceptions\UnknownException; |
10
|
|
|
|
11
|
|
|
class RequestHandler |
12
|
|
|
{ |
13
|
|
|
private $accessToken; |
14
|
|
|
private $apiUrl; |
15
|
|
|
private $client; |
16
|
|
|
|
17
|
|
|
public function __construct(string $accessToken = null, string $apiUrl = null) |
18
|
|
|
{ |
19
|
|
|
$this->accessToken = $accessToken; |
20
|
|
|
$this->apiUrl = $apiUrl; |
21
|
|
|
$this->client = new Client(['base_uri' => $this->apiUrl . '/']); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function getAccessToken(): string |
25
|
|
|
{ |
26
|
|
|
return $this->accessToken; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function setAccessToken(string $accessToken) |
30
|
|
|
{ |
31
|
|
|
$this->accessToken = $accessToken; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getApiUrl(): string |
35
|
|
|
{ |
36
|
|
|
return $this->apiUrl; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function setApiUrl(string $apiUrl) |
40
|
|
|
{ |
41
|
|
|
$this->apiUrl = $apiUrl; |
42
|
|
|
$this->client = new Client(['base_uri' => $apiUrl . '/']); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function handleBadResponse(ResponseInterface $response) |
46
|
|
|
{ |
47
|
|
|
$body = (string) $response->getBody(); |
48
|
|
|
$json = \GuzzleHttp\json_decode($body, true); |
49
|
|
|
ErrorHandler::error($json); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function handleException(ClientException $exception) |
53
|
|
|
{ |
54
|
|
|
$this->handleBadResponse($exception->getResponse()); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function get(string $endpoint, array $headers = [], array $params = null) |
|
|
|
|
58
|
|
|
{ |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function post(string $endpoint, array $params = null, array $headers = []): array |
62
|
|
|
{ |
63
|
|
|
$headers['Content-Type'] = 'application/json'; |
64
|
|
|
$body = null; |
65
|
|
|
if ($params) $body = \GuzzleHttp\json_encode($params); |
66
|
|
|
$request = new GuzzleRequest('POST', $endpoint, $headers, $body); |
67
|
|
|
|
68
|
|
|
try { |
69
|
|
|
$response = $this->client->send($request); |
70
|
|
|
if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 399) { |
71
|
|
|
return \GuzzleHttp\json_decode((string)$response->getBody(), true); |
72
|
|
|
} else { |
73
|
|
|
$this->handleBadResponse($response); |
74
|
|
|
} |
75
|
|
|
} catch (ClientException $e) { |
76
|
|
|
$this->handleException($e); |
77
|
|
|
} |
78
|
|
|
throw new UnknownException(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: