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.
Completed
Push — master ( 0ca652...2cfe71 )
by Freek
07:21 queued 03:16
created

Client::normalizePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Spatie\Dropbox;
4
5
use Exception;
6
use GuzzleHttp\Client as GuzzleClient;
7
use GuzzleHttp\Exception\ClientException;
8
use GuzzleHttp\Psr7\StreamWrapper;
9
use Psr\Http\Message\ResponseInterface;
10
use Spatie\Dropbox\Exceptions\BadRequest;
11
12
class Client
13
{
14
    const THUMBNAIL_FORMAT_JPEG = 'jpeg';
15
    const THUMBNAIL_FORMAT_PNG = 'png';
16
17
    const THUMBNAIL_SIZE_XS = 'w32h32';
18
    const THUMBNAIL_SIZE_S = 'w64h64';
19
    const THUMBNAIL_SIZE_M = 'w128h128';
20
    const THUMBNAIL_SIZE_L = 'w640h480';
21
    const THUMBNAIL_SIZE_XL = 'w1024h768';
22
23
    protected $accessToken;
24
25
    protected $client;
26
27
    public function __construct(string $accessToken)
28
    {
29
        $this->accessToken = $accessToken;
30
31
        $this->client = new GuzzleClient([
32
            'headers' => [
33
                'Authorization' => "Bearer {$this->accessToken}",
34
            ],
35
        ]);
36
    }
37
38
    /**
39
     * Copy a file or folder to a different location in the user's Dropbox.
40
     *
41
     * If the source path is a folder all its contents will be copied.
42
     *
43
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
44
     */
45 View Code Duplication
    public function copy(string $path, string $newPath): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
46
    {
47
        $parameters = [
48
            'from_path' => $this->normalizePath($path),
49
            'to_path' => $this->normalizePath($newPath),
50
        ];
51
52
        return $this->rpcEndpointRequest('files/copy', $parameters);
53
    }
54
55
    /**
56
     * Create a folder at a given path.Create a folder at a given path.
57
     *
58
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
59
     */
60
    public function createFolder(string $path): array
61
    {
62
        $parameters = [
63
            'path' => $this->normalizePath($path),
64
        ];
65
66
        $object = $this->rpcEndpointRequest('files/create_folder', $parameters);
67
68
        $object['.tag'] = 'folder';
69
70
        return $object;
71
    }
72
73
    /**
74
     * Delete the file or folder at a given path.
75
     *
76
     * If the path is a folder, all its contents will be deleted too.
77
     * A successful response indicates that the file or folder was deleted.
78
     *
79
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
80
     */
81
    public function delete(string $path): array
82
    {
83
        $parameters = [
84
            'path' => $this->normalizePath($path),
85
        ];
86
87
        return $this->rpcEndpointRequest('files/delete', $parameters);
88
    }
89
90
    /**
91
     * Download a file from a user's Dropbox.
92
     *
93
     * @param string $path
94
     *
95
     * @return resource
96
     *
97
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
98
     */
99
    public function download(string $path)
100
    {
101
        $arguments = [
102
            'path' => $this->normalizePath($path),
103
        ];
104
105
        $response = $this->contentEndpointRequest('files/download', $arguments);
106
107
        return StreamWrapper::getResource($response->getBody());
108
    }
109
110
    /**
111
     * Returns the metadata for a file or folder.
112
     *
113
     * Note: Metadata for the root folder is unsupported.
114
     *
115
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
116
     */
117
    public function getMetadata(string $path): array
118
    {
119
        $parameters = [
120
            'path' => $this->normalizePath($path),
121
        ];
122
123
        return $this->rpcEndpointRequest('files/get_metadata', $parameters);
124
    }
125
126
    /**
127
     * Get a temporary link to stream content of a file.
128
     *
129
     * This link will expire in four hours and afterwards you will get 410 Gone.
130
     * Content-Type of the link is determined automatically by the file's mime type.
131
     *
132
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
133
     */
134 View Code Duplication
    public function getTemporaryLink(string $path): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
    {
136
        $parameters = [
137
            'path' => $this->normalizePath($path),
138
        ];
139
140
        $body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
141
142
        return $body['link'];
143
    }
144
145
    /**
146
     * Get a thumbnail for an image.
147
     *
148
     * This method currently supports files with the following file extensions:jpg, jpeg,
149
     * png, tiff, tif, gif and bmp.
150
     * Photos that are larger than 20MB in size won't be converted to a thumbnail.
151
     *
152
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
153
     */
154
    public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
155
    {
156
        $arguments = [
157
            'path' => $this->normalizePath($path),
158
            'format' => $format,
159
            'size' => $size
160
        ];
161
162
        $response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
163
164
        return (string)$response->getBody();
165
    }
166
167
    /**
168
     * Starts returning the contents of a folder.
169
     *
170
     * If the result's ListFolderResult.has_more field is true, call
171
     * list_folder/continue with the returned ListFolderResult.cursor to retrieve more entries.
172
     *
173
     * Note: auth.RateLimitError may be returned if multiple list_folder or list_folder/continue calls
174
     * with same parameters are made simultaneously by same API app for same user. If your app implements
175
     * retry logic, please hold off the retry until the previous request finishes.
176
     *
177
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
178
     */
179 View Code Duplication
    public function listFolder(string $path = '', bool $recursive = false): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
    {
181
        $parameters = [
182
            'path' => $this->normalizePath($path),
183
            'recursive' => $recursive,
184
        ];
185
186
        return $this->rpcEndpointRequest('files/list_folder', $parameters);
187
    }
188
189
    /**
190
     * Move a file or folder to a different location in the user's Dropbox.
191
     *
192
     * If the source path is a folder all its contents will be moved.
193
     *
194
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
195
     */
196 View Code Duplication
    public function move(string $path, string $newPath): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197
    {
198
        $parameters = [
199
            'from_path' => $this->normalizePath($path),
200
            'to_path' => $this->normalizePath($newPath),
201
        ];
202
203
        return $this->rpcEndpointRequest('files/move', $parameters);
204
    }
205
206
    /**
207
     * Create a new file with the contents provided in the request.
208
     *
209
     * Do not use this to upload a file larger than 150 MB. Instead, create an upload session with upload_session/start.
210
     *
211
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
212
     *
213
     * @param string $path
214
     * @param string $mode
215
     * @param string|resource $contents
216
     *
217
     * @return array
218
     */
219
    public function upload(string $path, string $mode, $contents): array
220
    {
221
        $arguments = [
222
            'path' => $this->normalizePath($path),
223
            'mode' => $mode,
224
        ];
225
226
        $response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
227
228
        $metadata = json_decode($response->getBody(), true);
229
230
        $metadata['.tag'] = 'file';
231
232
        return $metadata;
233
    }
234
235
    protected function normalizePath(string $path): string
236
    {
237
        $path = trim($path, '/');
238
239
        if ($path === '') {
240
            return '';
241
        }
242
243
        return '/' . $path;
244
    }
245
246
    /**
247
     * @param string $endpoint
248
     * @param array $arguments
249
     * @param string|resource $body
250
     *
251
     * @return \Psr\Http\Message\ResponseInterface
252
     *
253
     * @throws \Spatie\Dropbox\Exceptions\BadRequest
254
     */
255
    protected function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
256
    {
257
        $headers['Dropbox-API-Arg'] = json_encode($arguments);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$headers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $headers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
258
259
        if ($body !== '') {
260
            $headers['Content-Type'] = 'application/octet-stream';
261
        }
262
263
        try {
264
            $response = $this->client->post("https://content.dropboxapi.com/2/{$endpoint}", [
265
                'headers' => $headers,
266
                'body' => $body,
267
            ]);
268
269
        } catch (ClientException $exception) {
270
            throw $this->determineException($exception);
271
        }
272
273
        return $response;
274
    }
275
276
    protected function rpcEndpointRequest(string $endpoint, array $parameters): array
277
    {
278
        try {
279
            $response = $this->client->post("https://api.dropboxapi.com/2/{$endpoint}", [
280
                'json' => $parameters
281
            ]);
282
        } catch (ClientException $exception) {
283
            throw $this->determineException($exception);
284
        }
285
286
        return json_decode($response->getBody(), true);
287
    }
288
289
     protected function determineException(ClientException $exception): Exception
290
     {
291
         if (in_array($exception->getResponse()->getStatusCode(), [400, 409])) {
292
             return new BadRequest($exception->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $exception->getResponse() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
293
         }
294
295
         return $exception;
296
     }
297
}
298