GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#2)
by Harald
02:47
created

Client::addAuthenticationHeaders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Bokbasen\ApiClient;
4
5
use Http\Client\HttpClient;
6
use Psr\Http\Message\ResponseInterface;
7
use Bokbasen\Auth\Login;
8
use Psr\Http\Message\StreamInterface;
9
use Psr\Log\LoggerInterface;
10
use Bokbasen\ApiClient\Exceptions\BokbasenApiClientException;
11
12
/**
13
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
14
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
15
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
16
 * A PARTICULAR PURPOSE ARE DISCLAIMED.
17
 * IN NO EVENT SHALL THE COPYRIGHT
18
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
 */
26
27
/**
28
 * Generic HTTP client for use against Bokbasen APIs.
29
 *
30
 * @license https://opensource.org/licenses/MIT
31
 */
32
class Client
33
{
34
    /**
35
     * @var LoggerInterface
36
     */
37
    protected $logger;
38
39
    /**
40
     * @var Login
41
     */
42
    protected $login;
43
44
    /**
45
     * @var Caller
46
     */
47
    protected $caller;
48
49
    /**
50
     * @var string
51
     */
52
    protected $baseUrl;
53
54
    /**
55
     * @param Login  $login
56
     * @param string $baseUrl
57
     */
58 14
    public function __construct(Login $login, string $baseUrl)
59
    {
60 14
        $this->login = $login;
61 14
        $this->baseUrl = $baseUrl;
62 14
    }
63
64 14
    protected function getCaller(): Caller
65
    {
66 14
        if (!$this->caller) {
67 14
            $this->caller = new Caller();
68
        }
69
70 14
        return $this->caller;
71
    }
72
73 14
    public function setHttpClient(HttpClient $httpClient): void
74
    {
75 14
        $this->getCaller()->setHttpClient($httpClient);
76 14
    }
77
78
    /**
79
     * @throws BokbasenApiClientException
80
     */
81 14
    protected function call(string $method, string $path, array $headers = [], $body = null, bool $authenticate = true): ResponseInterface
82
    {
83 14
        $headers = $authenticate ? $this->addAuthenticationHeaders($headers) : $headers;
84 14
        $url = $this->prependBaseUrl($path);
85
86 14
        $this->logRequest($method, $url, $body);
87
88 14
        $response = $this->getCaller()->request($method, $url, $headers, $body);
89
90 12
        $this->logResponse($response);
91
92 12
        return $response;
93
    }
94
95
    /**
96
     * Execute POST request
97
     *
98
     * @param string                               $path
99
     * @param resource|string|StreamInterface|null $body
100
     * @param array                                $headers
101
     * @param bool                                 $authenticate
102
     *
103
     * @return ResponseInterface
104
     *
105
     * @throws BokbasenApiClientException
106
     */
107 6
    public function post(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
108
    {
109 6
        return $this->call(
110 6
            HttpRequestOptions::HTTP_METHOD_POST,
111 6
            $path,
112 6
            $headers,
113 6
            $body,
114 6
            $authenticate
115
        );
116
    }
117
118
    /**
119
     * Execute PUT request
120
     *
121
     * @param string                               $path
122
     * @param resource|string|StreamInterface|null $body
123
     * @param array                                $headers
124
     * @param bool                                 $authenticate
125
     *
126
     * @return ResponseInterface
127
     *
128
     * @throws BokbasenApiClientException
129
     */
130 2
    public function put(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
131
    {
132 2
        return $this->call(
133 2
            HttpRequestOptions::HTTP_METHOD_PUT,
134 2
            $path,
135 2
            $headers,
136 2
            $body,
137 2
            $authenticate
138
        );
139
    }
140
141
    /**
142
     * Execute GET request
143
     *
144
     * @param string                               $path
145
     * @param resource|string|StreamInterface|null $body
146
     * @param array                                $headers
147
     * @param bool                                 $authenticate
148
     *
149
     * @return ResponseInterface
150
     *
151
     * @throws BokbasenApiClientException
152
     */
153 4
    public function get(string $path, array $headers = [], $authenticate = true): ResponseInterface
154
    {
155 4
        return $this->call(
156 4
            HttpRequestOptions::HTTP_METHOD_GET,
157 4
            $path,
158 4
            $headers,
159 4
            null,
160 4
            $authenticate
161
        );
162
    }
163
164
    /**
165
     * Execute PATCH request
166
     *
167
     * @param string                               $path
168
     * @param resource|string|StreamInterface|null $body
169
     * @param array                                $headers
170
     * @param bool                                 $authenticate
171
     *
172
     * @return ResponseInterface
173
     *
174
     * @throws BokbasenApiClientException
175
     */
176 2
    public function patch(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
177
    {
178 2
        return $this->call(
179 2
            HttpRequestOptions::HTTP_METHOD_PATCH,
180 2
            $path,
181 2
            $headers,
182 2
            $body,
183 2
            $authenticate
184
        );
185
    }
186
187
    /**
188
     * Special endpoint for posting json, sets correct content type header and encodes data as json
189
     *
190
     * @param string $path
191
     * @param array  $body
192
     *
193
     * @return ResponseInterface
194
     *
195
     * @throws BokbasenApiClientException
196
     */
197 2
    public function postJson(string $path, array $body): ResponseInterface
198
    {
199 2
        $body = json_encode($body);
200
201 2
        if ($body === false) {
202
            throw new BokbasenApiClientException('Unable to convert data to json');
203
        }
204
205 2
        return $this->post(
206 2
            $path,
207 2
            $body,
208
            [
209 2
                'Content-Type' => HttpRequestOptions::CONTENT_TYPE_JSON,
210
            ]
211
        );
212
    }
213
214
    /**
215
     * @param LoggerInterface $logger
216
     */
217 2
    public function setLogger(LoggerInterface $logger = null): void
218
    {
219 2
        $this->logger = $logger;
220 2
    }
221
222 14
    protected function prependBaseUrl(string $path): string
223
    {
224 14
        return sprintf('%s%s', $this->baseUrl, $path);
225
    }
226
227 14
    protected function addAuthenticationHeaders(array $existingHeaders = []): array
228
    {
229 14
        return array_merge($this->login->getAuthHeadersAsArray(), $existingHeaders);
230
    }
231
232 14
    protected function logRequest(string $method, string $url, $body = null): void
233
    {
234 14
        if ($this->logger) {
235 2
            $message = sprintf('Executing HTTP %s request to %s', $method, $url);
236 2
            if (!empty($body)) {
237 2
                $message .= sprintf(' with data %s', $body);
238
            }
239 2
            $this->logger->info($message);
240
        }
241 14
    }
242
243 12
    protected function logResponse(ResponseInterface $response): void
244
    {
245 12
        if ($this->logger) {
246
            $logItem = [
247 2
                'code' => $response->getStatusCode(),
248 2
                'headers' => $response->getHeaders(),
249
            ];
250
251 2
            if (!empty($body)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $body seems to never exist and therefore empty should always be true.
Loading history...
252
                $logItem['body'] = $response->getBody()->getContents();
253
            }
254
255 2
            $this->logger->info(json_encode($logItem));
256
257 2
            $response->getBody()->rewind();
258
        }
259 12
    }
260
}
261