Passed
Push — master ( 664b37...040394 )
by Gabriel
02:14
created

RequestHandler::getLogger()   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 0
crap 2
1
<?php
2
3
namespace Waredesk;
4
5
use GuzzleHttp\Exception\BadResponseException;
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 Psr\Log\LoggerInterface;
12
use Waredesk\Exceptions\UnknownException;
13
14
class RequestHandler
15
{
16
    private $mockHandler;
17
    private $accessToken;
18
    private $apiUrl;
19
    private $client;
20
    private $clientId;
21
    private $clientSecret;
22
    private $disabledAuthentication = false;
23
    private $logger;
24
25 20
    public function __construct(string $clientId, string $clientSecret, string $accessToken = null, string $apiUrl = null, LoggerInterface $logger = null)
26
    {
27 20
        $this->logger = $logger;
28 20
        $this->clientId = $clientId;
29 20
        $this->clientSecret = $clientSecret;
30 20
        $this->accessToken = $accessToken;
31 20
        $this->apiUrl = $apiUrl;
32 20
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
33 20
    }
34
35
    public function getLogger(): ? LoggerInterface
36
    {
37
        return $this->logger;
38
    }
39
40 1
    public function setLogger(LoggerInterface $logger = null)
41
    {
42 1
        $this->logger = $logger;
43 1
    }
44
45 1
    public function disabledAuthentication()
46
    {
47 1
        $this->disabledAuthentication = true;
48 1
    }
49
50
    public function getClientId(): string
51
    {
52
        return $this->clientId;
53
    }
54
55 1
    public function setClientId(string $clientId = null)
56
    {
57 1
        $this->clientId = $clientId;
58 1
    }
59
60
    public function getClientSecret(): string
61
    {
62
        return $this->clientSecret;
63
    }
64
65
    public function setClientSecret(string $clientSecret = null)
66
    {
67
        $this->clientSecret = $clientSecret;
68
    }
69
70 16
    public function getAccessToken(): string
71
    {
72 16
        if (null !== $this->accessToken) {
73 15
            return $this->accessToken;
74
        }
75 1
        $this->disabledAuthentication();
76 1
        $response = $this->post(
77 1
            '/v1-alpha/authorize',
78
            [
79 1
                'client_id' => $this->clientId,
80 1
                'client_secret' => $this->clientSecret,
81 1
                'grant_type' => 'client_credentials'
82
            ]
83
        );
84
        $this->accessToken = $response['access_token'];
85
        return $this->accessToken;
86
    }
87
88 20
    public function setAccessToken(string $accessToken = null)
89
    {
90 20
        $this->accessToken = $accessToken;
91 20
    }
92
93
    public function getApiUrl(): string
94
    {
95
        return $this->apiUrl;
96
    }
97
98 20
    public function setApiUrl(string $apiUrl)
99
    {
100 20
        $this->apiUrl = $apiUrl;
101 20
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
102 20
    }
103
104 20
    public function setMockHandler(HandlerStack $mockHandler = null)
105
    {
106 20
        $this->mockHandler = $mockHandler;
107 20
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
108 20
    }
109
110 2
    private function handleBadResponse(ResponseInterface $response = null)
111
    {
112 2
        if ($response) {
113 2
            $body = (string)$response->getBody();
114 2
            $json = \GuzzleHttp\json_decode($body, true);
115 2
            (new ErrorHandler())($json);
116
            return;
117
        }
118
        throw new UnknownException();
119
    }
120
121 2
    private function handleException(BadResponseException $exception)
122
    {
123 2
        $this->handleBadResponse($exception->getResponse());
124
    }
125
126 15
    private function enhanceHeaders(array $headers = []): array
127
    {
128 15
        $headers['Content-Type'] = 'application/json';
129 15
        if (!$this->disabledAuthentication) {
130 14
            $accessToken = $this->getAccessToken();
131 14
            if ($accessToken !== null) {
132 14
                $headers['Authorization'] = 'Bearer '.$accessToken;
133
            }
134
        }
135 15
        $this->disabledAuthentication = false;
136 15
        return $headers;
137
    }
138
139 15
    private function encodeParams($params = null): ?string
140
    {
141 15
        $body = null;
142 15
        if ($params) {
143 15
            $body = \GuzzleHttp\json_encode($params);
144
        }
145 15
        return $body;
146
    }
147
148 15
    private function request(string $method, string $endpoint, array $headers = [], $params = null)
149
    {
150
        try {
151 15
            $enhancedHeaders = $this->enhanceHeaders($headers);
152 15
            $params = $this->encodeParams($params);
153 15
            if ($this->logger) {
154 1
                $this->logger->debug('REQUEST', [
155 1
                    'method' => $method,
156 1
                    'endpoint' => $endpoint,
157 1
                    'header' => $enhancedHeaders,
158 1
                    'body' => \GuzzleHttp\json_decode($params, true)
159
                ]);
160
            }
161 15
            $request = new GuzzleRequest(
162
                $method,
163
                $endpoint,
164
                $enhancedHeaders,
165
                $params
166
            );
167 15
            $response = $this->client->send($request);
168 14
            if ($this->logger) {
169 1
                $this->logger->debug('RESPONSE', [
170 1
                    'method' => $method,
171 1
                    'status' => $response->getStatusCode(),
172 1
                    'endpoint' => $endpoint,
173 1
                    'body' => \GuzzleHttp\json_decode((string)$response->getBody(), true)
174
                ]);
175
            }
176 14
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 399) {
177 14
                return \GuzzleHttp\json_decode((string)$response->getBody(), true);
178
            }
179
            $this->handleBadResponse($response);
180 2
        } catch (BadResponseException $e) {
181 2
            if ($this->logger) {
182
                $this->logger->debug('RESPONSE', [
183
                    'method' => $method,
184
                    'status' => $e->getResponse()->getStatusCode(),
185
                    'endpoint' => $endpoint,
186
                    'body' => \GuzzleHttp\json_decode((string)$e->getResponse()->getBody(), true)
187
                ]);
188
            }
189 2
            $this->handleException($e);
190
        }
191
        if ($this->logger) {
192
            $this->logger->debug('RESPONSE', [
193
                'method' => $method,
194
                'status' => null,
195
                'endpoint' => $endpoint,
196
                'body' => null
197
            ]);
198
        }
199
        throw new UnknownException();
200
    }
201
202 12
    public function get(string $endpoint, $params = null, array $headers = []): array
203
    {
204 12
        return $this->request('GET', $endpoint, $headers, $params);
205
    }
206
207 8
    public function post(string $endpoint, $params = null, array $headers = []): array
208
    {
209 8
        return $this->request('POST', $endpoint, $headers, $params);
210
    }
211
212 1
    public function update(string $endpoint, $params = null, array $headers = []): array
213
    {
214 1
        return $this->request('PUT', $endpoint, $headers, $params);
215
    }
216
217 3
    public function delete(string $endpoint, $params = null, array $headers = []): bool
218
    {
219 3
        return $this->request('DELETE', $endpoint, $headers, $params);
220
    }
221
}
222