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
Pull Request — master (#4)
by
unknown
27:06 queued 10:57
created

Client::listFolderContinue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Spatie\Dropbox;
4
5
use Exception;
6
use GuzzleHttp\Psr7\StreamWrapper;
7
use GuzzleHttp\Client as GuzzleClient;
8
use Psr\Http\Message\ResponseInterface;
9
use GuzzleHttp\Exception\ClientException;
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
    /** @var string */
24
    protected $accessToken;
25
26
    /** @var \GuzzleHttp\Client */
27
    protected $client;
28
29
    public function __construct(string $accessToken)
30
    {
31
        $this->accessToken = $accessToken;
32
33
        $this->client = new GuzzleClient([
34
            'headers' => [
35
                'Authorization' => "Bearer {$this->accessToken}",
36
            ],
37
        ]);
38
    }
39
40
    /**
41
     * Copy a file or folder to a different location in the user's Dropbox.
42
     *
43
     * If the source path is a folder all its contents will be copied.
44
     *
45
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
46
     */
47 View Code Duplication
    public function copy(string $fromPath, string $toPath): 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...
48
    {
49
        $parameters = [
50
            'from_path' => $this->normalizePath($fromPath),
51
            'to_path' => $this->normalizePath($toPath),
52
        ];
53
54
        return $this->rpcEndpointRequest('files/copy', $parameters);
55
    }
56
57
    /**
58
     * Create a folder at a given path.
59
     *
60
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
61
     */
62
    public function createFolder(string $path): array
63
    {
64
        $parameters = [
65
            'path' => $this->normalizePath($path),
66
        ];
67
68
        $object = $this->rpcEndpointRequest('files/create_folder', $parameters);
69
70
        $object['.tag'] = 'folder';
71
72
        return $object;
73
    }
74
75
    /**
76
     * Delete the file or folder at a given path.
77
     *
78
     * If the path is a folder, all its contents will be deleted too.
79
     * A successful response indicates that the file or folder was deleted.
80
     *
81
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
82
     */
83
    public function delete(string $path): array
84
    {
85
        $parameters = [
86
            'path' => $this->normalizePath($path),
87
        ];
88
89
        return $this->rpcEndpointRequest('files/delete', $parameters);
90
    }
91
92
    /**
93
     * Download a file from a user's Dropbox.
94
     *
95
     * @param string $path
96
     *
97
     * @return resource
98
     *
99
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
100
     */
101
    public function download(string $path)
102
    {
103
        $arguments = [
104
            'path' => $this->normalizePath($path),
105
        ];
106
107
        $response = $this->contentEndpointRequest('files/download', $arguments);
108
109
        return StreamWrapper::getResource($response->getBody());
110
    }
111
112
    /**
113
     * Returns the metadata for a file or folder.
114
     *
115
     * Note: Metadata for the root folder is unsupported.
116
     *
117
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
118
     */
119
    public function getMetadata(string $path): array
120
    {
121
        $parameters = [
122
            'path' => $this->normalizePath($path),
123
        ];
124
125
        return $this->rpcEndpointRequest('files/get_metadata', $parameters);
126
    }
127
128
    /**
129
     * Get a temporary link to stream content of a file.
130
     *
131
     * This link will expire in four hours and afterwards you will get 410 Gone.
132
     * Content-Type of the link is determined automatically by the file's mime type.
133
     *
134
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
135
     */
136 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...
137
    {
138
        $parameters = [
139
            'path' => $this->normalizePath($path),
140
        ];
141
142
        $body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
143
144
        return $body['link'];
145
    }
146
147
    /**
148
     * Get a thumbnail for an image.
149
     *
150
     * This method currently supports files with the following file extensions:
151
     * jpg, jpeg, png, tiff, tif, gif and bmp.
152
     *
153
     * Photos that are larger than 20MB in size won't be converted to a thumbnail.
154
     *
155
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
156
     */
157
    public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
158
    {
159
        $arguments = [
160
            'path' => $this->normalizePath($path),
161
            'format' => $format,
162
            'size' => $size,
163
        ];
164
165
        $response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
166
167
        return (string) $response->getBody();
168
    }
169
170
    /**
171
     * Starts returning the contents of a folder.
172
     *
173
     * If the result's ListFolderResult.has_more field is true, call
174
     * list_folder/continue with the returned ListFolderResult.cursor to retrieve more entries.
175
     *
176
     * Note: auth.RateLimitError may be returned if multiple list_folder or list_folder/continue calls
177
     * with same parameters are made simultaneously by same API app for same user. If your app implements
178
     * retry logic, please hold off the retry until the previous request finishes.
179
     *
180
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
181
     */
182 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...
183
    {
184
        $parameters = [
185
            'path' => $this->normalizePath($path),
186
            'recursive' => $recursive,
187
        ];
188
189
        return $this->rpcEndpointRequest('files/list_folder', $parameters);
190
    }
191
192
    /**
193
     * Once a cursor has been retrieved from list_folder, use this to paginate through all files and
194
     * retrieve updates to the folder, following the same rules as documented for list_folder.
195
     *
196
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
197
     */
198
    public function listFolderContinue(string $cursor = ''): array
199
    {
200
        $parameters = [
201
            'cursor' => $cursor,
202
        ];
203
204
        return $this->rpcEndpointRequest('files/list_folder/continue', $parameters);
205
    }
206
207
    /**
208
     * Move a file or folder to a different location in the user's Dropbox.
209
     *
210
     * If the source path is a folder all its contents will be moved.
211
     *
212
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
213
     */
214 View Code Duplication
    public function move(string $fromPath, string $toPath): 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...
215
    {
216
        $parameters = [
217
            'from_path' => $this->normalizePath($fromPath),
218
            'to_path' => $this->normalizePath($toPath),
219
        ];
220
221
        return $this->rpcEndpointRequest('files/move', $parameters);
222
    }
223
224
    /**
225
     * Create a new file with the contents provided in the request.
226
     *
227
     * Do not use this to upload a file larger than 150 MB. Instead, create an upload session with upload_session/start.
228
     *
229
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
230
     *
231
     * @param string $path
232
     * @param string|resource $contents
233
     * @param string|array $mode
234
     *
235
     * @return array
236
     */
237
    public function upload(string $path, $contents, $mode = 'add'): array
238
    {
239
        $arguments = [
240
            'path' => $this->normalizePath($path),
241
            'mode' => $mode,
242
        ];
243
244
        $response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
245
246
        $metadata = json_decode($response->getBody(), true);
247
248
        $metadata['.tag'] = 'file';
249
250
        return $metadata;
251
    }
252
253
    protected function normalizePath(string $path): string
254
    {
255
        $path = trim($path, '/');
256
257
        if ($path === '') {
258
            return '';
259
        }
260
261
        return '/'.$path;
262
    }
263
264
    /**
265
     * @param string $endpoint
266
     * @param array $arguments
267
     * @param string|resource $body
268
     *
269
     * @return \Psr\Http\Message\ResponseInterface
270
     *
271
     * @throws \Exception
272
     */
273
    public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
274
    {
275
        $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...
276
277
        if ($body !== '') {
278
            $headers['Content-Type'] = 'application/octet-stream';
279
        }
280
281
        try {
282
            $response = $this->client->post("https://content.dropboxapi.com/2/{$endpoint}", [
283
                'headers' => $headers,
284
                'body' => $body,
285
            ]);
286
        } catch (ClientException $exception) {
287
            throw $this->determineException($exception);
288
        }
289
290
        return $response;
291
    }
292
293
    public function rpcEndpointRequest(string $endpoint, array $parameters): array
294
    {
295
        try {
296
            $response = $this->client->post("https://api.dropboxapi.com/2/{$endpoint}", [
297
                'json' => $parameters,
298
            ]);
299
        } catch (ClientException $exception) {
300
            throw $this->determineException($exception);
301
        }
302
303
        return json_decode($response->getBody(), true);
304
    }
305
306
    protected function determineException(ClientException $exception): Exception
307
    {
308
        if (in_array($exception->getResponse()->getStatusCode(), [400, 409])) {
309
            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...
310
        }
311
312
        return $exception;
313
    }
314
}
315