Passed
Push — master ( 18010c...ab4210 )
by Gabriel
02:26
created

RequestHandler::handleBadResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0932

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 7
cp 0.7143
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2.0932
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 7
    public function __construct(string $clientId, string $clientSecret, string $accessToken = null, string $apiUrl = null)
24
    {
25 7
        $this->clientId = $clientId;
26 7
        $this->clientSecret = $clientSecret;
27 7
        $this->accessToken = $accessToken;
28 7
        $this->apiUrl = $apiUrl;
29 7
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
30 7
    }
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 5
    public function getAccessToken(): string
58
    {
59 5
        if (null !== $this->accessToken) {
60 4
            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 7
    public function setAccessToken(string $accessToken = null)
76
    {
77 7
        $this->accessToken = $accessToken;
78 7
    }
79
80
    public function getApiUrl(): string
81
    {
82
        return $this->apiUrl;
83
    }
84
85 7
    public function setApiUrl(string $apiUrl)
86
    {
87 7
        $this->apiUrl = $apiUrl;
88 7
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
89 7
    }
90
91 7
    public function setMockHandler(HandlerStack $mockHandler = null)
92
    {
93 7
        $this->mockHandler = $mockHandler;
94 7
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
95 7
    }
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 4
    private function enhanceHeaders(array $headers = []): array
114
    {
115 4
        $headers['Content-Type'] = 'application/json';
116 4
        if (!$this->disabledAuthentication) {
117 3
            $accessToken = $this->getAccessToken();
118 3
            if ($accessToken !== null) {
119 3
                $headers['Authorization'] = 'Bearer '.$accessToken;
120
            }
121
        }
122 4
        $this->disabledAuthentication = false;
123 4
        return $headers;
124
    }
125
126 4
    private function encodeParams($params = null): ?string
127
    {
128 4
        $body = null;
129 4
        if ($params) {
130 3
            $body = \GuzzleHttp\json_encode($params);
131
        }
132 4
        return $body;
133
    }
134
135 4
    private function request(Request $request): array
136
    {
137
        try {
138 4
            $response = $this->client->send($request);
139 3
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 399) {
140 3
                return \GuzzleHttp\json_decode((string)$response->getBody(), true);
141
            }
142
            $this->handleBadResponse($response);
143 1
        } catch (ClientException $e) {
144 1
            $this->handleException($e);
145
        }
146
        throw new UnknownException();
147
    }
148
149 1
    public function get(string $endpoint, array $headers = [], array $params = null): array
150
    {
151 1
        return $this->request(
152 1
            new GuzzleRequest(
153 1
                'GET',
154
                $endpoint,
155 1
                $this->enhanceHeaders($headers),
156 1
                $this->encodeParams($params)
157
            )
158
        );
159
    }
160
161 3
    public function post(string $endpoint, $params = null, array $headers = []): array
162
    {
163 3
        return $this->request(
164 3
            new GuzzleRequest(
165 3
                'POST',
166
                $endpoint,
167 3
                $this->enhanceHeaders($headers),
168 3
                $this->encodeParams($params)
169
            )
170
        );
171
    }
172
}
173