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.
Test Failed
Pull Request — master (#2)
by Harald
07:26 queued 04:37
created

Client::patch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 10
cc 1
nc 1
nop 4
crap 2
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 2
    public function __construct(Login $login, string $baseUrl)
59
    {
60 2
        $this->login = $login;
61 2
        $this->baseUrl = $baseUrl;
62 2
    }
63
64 2
    protected function getCaller(): Caller
65
    {
66 2
        if (!$this->caller) {
67 2
            $this->caller = new Caller();
68
        }
69
70
        return $this->caller;
71
    }
72
73 2
    public function setHttpClient(HttpClient $httpClient): void
74
    {
75 2
        $this->getCaller()->setHttpClient($httpClient);
76
    }
77
78
    /**
79
     * @throws BokbasenApiClientException
80
     */
81
    protected function call(string $method, string $path, array $headers = [], $body = null, bool $authenticate = true): ResponseInterface
82
    {
83
        $headers = $authenticate ? $this->addAuthenticationHeaders($headers) : $headers;
84
        $url = $this->prependBaseUrl($path);
85
86
        $this->logRequest($method, $url, $body);
87
88
        $response = $this->getCaller()->request($method, $url, $headers, $body);
89
90
        $this->logResponse($response);
91
92
        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
    public function post(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
108
    {
109
        return $this->call(
110
            HttpRequestOptions::HTTP_METHOD_POST,
111
            $path,
112
            $headers,
113
            $body,
114
            $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
    public function put(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
131
    {
132
        return $this->call(
133
            HttpRequestOptions::HTTP_METHOD_PUT,
134
            $path,
135
            $headers,
136
            $body,
137
            $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
    public function get(string $path, array $headers = [], $authenticate = true): ResponseInterface
154
    {
155
        return $this->call(
156
            HttpRequestOptions::HTTP_METHOD_GET,
157
            $path,
158
            $headers,
159
            null,
160
            $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
    public function patch(string $path, $body, array $headers = [], bool $authenticate = true): ResponseInterface
177
    {
178
        return $this->call(
179
            HttpRequestOptions::HTTP_METHOD_PATCH,
180
            $path,
181
            $headers,
182
            $body,
183
            $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
    public function postJson(string $path, array $body): ResponseInterface
198
    {
199
        $body = json_encode($body);
200
201
        if ($body === false) {
202
            throw new BokbasenApiClientException('Unable to convert data to json');
203
        }
204
205
        return $this->post(
206
            $path,
207
            $body,
208
            [
209
                'Content-Type' => HttpRequestOptions::CONTENT_TYPE_JSON,
210
            ]
211
        );
212
    }
213
214
    /**
215
     * @param LoggerInterface $logger
216
     */
217
    public function setLogger(LoggerInterface $logger = null): void
218
    {
219
        $this->logger = $logger;
220
    }
221
222
    protected function prependBaseUrl(string $path): string
223
    {
224
        return sprintf('%s%s', $this->baseUrl, $path);
225
    }
226
227
    protected function addAuthenticationHeaders(array $existingHeaders = []): array
228
    {
229
        return array_merge($this->login->getAuthHeadersAsArray(), $existingHeaders);
230
    }
231
232
    protected function logRequest(string $method, string $url, $body = null): void
233
    {
234
        if ($this->logger) {
235
            $message = sprintf('Executing HTTP %s request to %s', $method, $url);
236
            if (!empty($body)) {
237
                $message .= sprintf(' with data %s', $body);
238
            }
239
            $this->logger->info($message);
240
        }
241
    }
242
243
    protected function logResponse(ResponseInterface $response): void
244
    {
245
        if ($this->logger) {
246
            $logItem = [
247
                'code' => $response->getStatusCode(),
248
                'headers' => $response->getHeaders(),
249
            ];
250
251
            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
            $this->logger->info(json_encode($logItem));
256
257
            $response->getBody()->rewind();
258
        }
259
    }
260
}
261