Completed
Push — master ( cb44f9...1fdaf4 )
by Gabriel
07:02
created

RequestHandler::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 3
crap 2
1
<?php
2
3
namespace Waredesk;
4
5
use GuzzleHttp\Exception\ClientException;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Psr7\Request as GuzzleRequest;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Psr7\Request;
10
use Psr\Http\Message\ResponseInterface;
11
use Waredesk\Exceptions\UnknownException;
12
13
class RequestHandler
14
{
15
    private $mockHandler;
16
    private $accessToken;
17
    private $apiUrl;
18
    private $client;
19
    private $clientId;
20
    private $clientSecret;
21
    private $disabledAuthentication = false;
22
23 12
    public function __construct(string $clientId, string $clientSecret, string $accessToken = null, string $apiUrl = null)
24
    {
25 12
        $this->clientId = $clientId;
26 12
        $this->clientSecret = $clientSecret;
27 12
        $this->accessToken = $accessToken;
28 12
        $this->apiUrl = $apiUrl;
29 12
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
30 12
    }
31
32 1
    public function disabledAuthentication()
33
    {
34 1
        $this->disabledAuthentication = true;
35 1
    }
36
37
    public function getClientId(): string
38
    {
39
        return $this->clientId;
40
    }
41
42 1
    public function setClientId(string $clientId = null)
43
    {
44 1
        $this->clientId = $clientId;
45 1
    }
46
47
    public function getClientSecret(): string
48
    {
49
        return $this->clientSecret;
50
    }
51
52
    public function setClientSecret(string $clientSecret = null)
53
    {
54
        $this->clientSecret = $clientSecret;
55
    }
56
57 7
    public function getAccessToken(): string
58
    {
59 7
        if (null !== $this->accessToken) {
60 6
            return $this->accessToken;
61
        }
62 1
        $this->disabledAuthentication();
63 1
        $response = $this->post(
64 1
            '/v1/authorize',
65
            [
66 1
                'client_id' => $this->clientId,
67 1
                'client_secret' => $this->clientSecret,
68 1
                'grant_type' => 'client_credentials'
69
            ]
70
        );
71
        $this->accessToken = $response['access_token'];
72
        return $this->accessToken;
73
    }
74
75 12
    public function setAccessToken(string $accessToken = null)
76
    {
77 12
        $this->accessToken = $accessToken;
78 12
    }
79
80
    public function getApiUrl(): string
81
    {
82
        return $this->apiUrl;
83
    }
84
85 12
    public function setApiUrl(string $apiUrl)
86
    {
87 12
        $this->apiUrl = $apiUrl;
88 12
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
89 12
    }
90
91 12
    public function setMockHandler(HandlerStack $mockHandler = null)
92
    {
93 12
        $this->mockHandler = $mockHandler;
94 12
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
95 12
    }
96
97 1
    private function handleBadResponse(ResponseInterface $response = null)
98
    {
99 1
        if ($response) {
100 1
            $body = (string)$response->getBody();
101 1
            $json = \GuzzleHttp\json_decode($body, true);
102 1
            (new ErrorHandler())($json);
103
            return;
104
        }
105
        throw new UnknownException();
106
    }
107
108 1
    private function handleException(ClientException $exception)
109
    {
110 1
        $this->handleBadResponse($exception->getResponse());
111
    }
112
113 6
    private function enhanceHeaders(array $headers = []): array
114
    {
115 6
        $headers['Content-Type'] = 'application/json';
116 6
        if (!$this->disabledAuthentication) {
117 5
            $accessToken = $this->getAccessToken();
118 5
            if ($accessToken !== null) {
119 5
                $headers['Authorization'] = 'Bearer '.$accessToken;
120
            }
121
        }
122 6
        $this->disabledAuthentication = false;
123 6
        return $headers;
124
    }
125
126 6
    private function encodeParams($params = null): ?string
127
    {
128 6
        $body = null;
129 6
        if ($params) {
130 4
            $body = \GuzzleHttp\json_encode($params);
131
        }
132 6
        return $body;
133
    }
134
135 6
    private function request(string $method, string $endpoint, array $headers = [], $params = null): array
136
    {
137
        try {
138 6
            $request = new GuzzleRequest(
139
                $method,
140
                $endpoint,
141 6
                $this->enhanceHeaders($headers),
142 6
                $this->encodeParams($params)
143
            );
144 6
            $response = $this->client->send($request);
145 5
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 399) {
146 5
                return \GuzzleHttp\json_decode((string)$response->getBody(), true);
147
            }
148
            $this->handleBadResponse($response);
149 1
        } catch (ClientException $e) {
150 1
            $this->handleException($e);
151
        }
152
        throw new UnknownException();
153
    }
154
155 2
    public function get(string $endpoint, array $headers = [], array $params = null): array
156
    {
157 2
        return $this->request('GET', $endpoint, $headers, $params);
158
    }
159
160 4
    public function post(string $endpoint, $params = null, array $headers = []): array
161
    {
162 4
        return $this->request('POST', $endpoint, $headers, $params);
163
    }
164
165
    public function update(string $endpoint, $params = null, array $headers = []): array
166
    {
167
        return $this->request('PUT', $endpoint, $headers, $params);
168
    }
169
170
    public function delete(string $endpoint, $params = null, array $headers = []): array
171
    {
172
        return $this->request('DELETE', $endpoint, $headers, $params);
173
    }
174
}
175