Completed
Push — master ( 3c4917...c12914 )
by Gabriel
03:23
created

RequestHandler::request()   B

Complexity

Conditions 4
Paths 7

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.0961

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 9
cts 11
cp 0.8182
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 14
nc 7
nop 4
crap 4.0961
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 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 18
    public function __construct(string $clientId, string $clientSecret, string $accessToken = null, string $apiUrl = null)
24
    {
25 18
        $this->clientId = $clientId;
26 18
        $this->clientSecret = $clientSecret;
27 18
        $this->accessToken = $accessToken;
28 18
        $this->apiUrl = $apiUrl;
29 18
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
30 18
    }
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 14
    public function getAccessToken(): string
58
    {
59 14
        if (null !== $this->accessToken) {
60 13
            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 18
    public function setAccessToken(string $accessToken = null)
76
    {
77 18
        $this->accessToken = $accessToken;
78 18
    }
79
80
    public function getApiUrl(): string
81
    {
82
        return $this->apiUrl;
83
    }
84
85 18
    public function setApiUrl(string $apiUrl)
86
    {
87 18
        $this->apiUrl = $apiUrl;
88 18
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
89 18
    }
90
91 18
    public function setMockHandler(HandlerStack $mockHandler = null)
92
    {
93 18
        $this->mockHandler = $mockHandler;
94 18
        $this->client = new Client(['base_uri' => $this->apiUrl, 'handler' => $this->mockHandler]);
95 18
    }
96
97 2
    private function handleBadResponse(ResponseInterface $response = null)
98
    {
99 2
        if ($response) {
100 2
            $body = (string)$response->getBody();
101 2
            $json = \GuzzleHttp\json_decode($body, true);
102 2
            (new ErrorHandler())($json);
103
            return;
104
        }
105
        throw new UnknownException();
106
    }
107
108 2
    private function handleException(BadResponseException $exception)
109
    {
110 2
        $this->handleBadResponse($exception->getResponse());
111
    }
112
113 13
    private function enhanceHeaders(array $headers = []): array
114
    {
115 13
        $headers['Content-Type'] = 'application/json';
116 13
        if (!$this->disabledAuthentication) {
117 12
            $accessToken = $this->getAccessToken();
118 12
            if ($accessToken !== null) {
119 12
                $headers['Authorization'] = 'Bearer '.$accessToken;
120
            }
121
        }
122 13
        $this->disabledAuthentication = false;
123 13
        return $headers;
124
    }
125
126 13
    private function encodeParams($params = null): ?string
127
    {
128 13
        $body = null;
129 13
        if ($params) {
130 9
            $body = \GuzzleHttp\json_encode($params);
131
        }
132 13
        return $body;
133
    }
134
135 13
    private function request(string $method, string $endpoint, array $headers = [], $params = null)
136
    {
137
        try {
138 13
            $request = new GuzzleRequest(
139
                $method,
140
                $endpoint,
141 13
                $this->enhanceHeaders($headers),
142 13
                $this->encodeParams($params)
143
            );
144 13
            $response = $this->client->send($request);
145 12
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() <= 399) {
146
                /*if ($endpoint !== '/v1/authorize' && $method !== 'GET') {
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
147
                    echo $method.PHP_EOL;
148
                    echo $endpoint.PHP_EOL;
149
                    $body = (string)$response->getBody();
150
                    //$obj = \GuzzleHttp\json_decode($body);
151
                    echo $body;
152
                    die();
153
                }*/
154 12
                return \GuzzleHttp\json_decode((string)$response->getBody(), true);
155
            }
156
            $this->handleBadResponse($response);
157 2
        } catch (BadResponseException $e) {
158
            /*$body = (string)$e->getResponse()->getBody();
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
159
            echo $body;
160
            die();*/
161 2
            $this->handleException($e);
162
        }
163
        throw new UnknownException();
164
    }
165
166 10
    public function get(string $endpoint, $params = null, array $headers = []): array
167
    {
168 10
        return $this->request('GET', $endpoint, $headers, $params);
169
    }
170
171 7
    public function post(string $endpoint, $params = null, array $headers = []): array
172
    {
173 7
        return $this->request('POST', $endpoint, $headers, $params);
174
    }
175
176 1
    public function update(string $endpoint, $params = null, array $headers = []): array
177
    {
178 1
        return $this->request('PUT', $endpoint, $headers, $params);
179
    }
180
181 1
    public function delete(string $endpoint, $params = null, array $headers = []): bool
182
    {
183 1
        return $this->request('DELETE', $endpoint, $headers, $params);
184
    }
185
}
186