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 (#11)
by
unknown
01:49
created

Client::listSharedLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
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, GuzzleClient $client = null)
30
    {
31
        $this->accessToken = $accessToken;
32
33
        $this->client = $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
     * Create a shared link with custom settings.
77
     *
78
     * If no settings are given then the default visibility is RequestedVisibility.public.
79
     * The resolved visibility, though, may depend on other aspects such as team and
80
     * shared folder settings).
81
     *
82
     * @link https://www.dropbox.com/developers/documentation/http/documentation#sharing-create_shared_link_with_settings
83
     */
84
    public function createSharedLinkWithSettings(string $path, array $settings = [])
0 ignored issues
show
Unused Code introduced by
The parameter $settings is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
85
    {
86
        $parameters = [
87
            'path' => $this->normalizePath($path),
88
        ];
89
90
        return $this->rpcEndpointRequest('sharing/create_shared_link_with_settings', $parameters);
91
    }
92
93
    /**
94
     * List shared links.
95
     *
96
     * For empty path returns a list of all shared links. For non-empty path 
97
     * returns a list of all shared links with access to the given path.
98
     *
99
     * @link https://www.dropbox.com/developers/documentation/http/documentation#sharing-list_shared_links
100
     */
101 View Code Duplication
    public function listSharedLinks(string $path): 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...
102
    {
103
        $parameters = [
104
            'path' => $this->normalizePath($path),
105
        ];
106
107
        $body = $this->rpcEndpointRequest('sharing/list_shared_links', $parameters);
108
109
        return $body['links'];
110
    }
111
112
    /**
113
     * Delete the file or folder at a given path.
114
     *
115
     * If the path is a folder, all its contents will be deleted too.
116
     * A successful response indicates that the file or folder was deleted.
117
     *
118
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
119
     */
120
    public function delete(string $path): array
121
    {
122
        $parameters = [
123
            'path' => $this->normalizePath($path),
124
        ];
125
126
        return $this->rpcEndpointRequest('files/delete', $parameters);
127
    }
128
129
    /**
130
     * Download a file from a user's Dropbox.
131
     *
132
     * @param string $path
133
     *
134
     * @return resource
135
     *
136
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
137
     */
138
    public function download(string $path)
139
    {
140
        $arguments = [
141
            'path' => $this->normalizePath($path),
142
        ];
143
144
        $response = $this->contentEndpointRequest('files/download', $arguments);
145
146
        return StreamWrapper::getResource($response->getBody());
147
    }
148
149
    /**
150
     * Returns the metadata for a file or folder.
151
     *
152
     * Note: Metadata for the root folder is unsupported.
153
     *
154
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
155
     */
156
    public function getMetadata(string $path): array
157
    {
158
        $parameters = [
159
            'path' => $this->normalizePath($path),
160
        ];
161
162
        return $this->rpcEndpointRequest('files/get_metadata', $parameters);
163
    }
164
165
    /**
166
     * Get a temporary link to stream content of a file.
167
     *
168
     * This link will expire in four hours and afterwards you will get 410 Gone.
169
     * Content-Type of the link is determined automatically by the file's mime type.
170
     *
171
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
172
     */
173 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...
174
    {
175
        $parameters = [
176
            'path' => $this->normalizePath($path),
177
        ];
178
179
        $body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
180
181
        return $body['link'];
182
    }
183
184
    /**
185
     * Get a thumbnail for an image.
186
     *
187
     * This method currently supports files with the following file extensions:
188
     * jpg, jpeg, png, tiff, tif, gif and bmp.
189
     *
190
     * Photos that are larger than 20MB in size won't be converted to a thumbnail.
191
     *
192
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
193
     */
194
    public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
195
    {
196
        $arguments = [
197
            'path' => $this->normalizePath($path),
198
            'format' => $format,
199
            'size' => $size,
200
        ];
201
202
        $response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
203
204
        return (string) $response->getBody();
205
    }
206
207
    /**
208
     * Starts returning the contents of a folder.
209
     *
210
     * If the result's ListFolderResult.has_more field is true, call
211
     * list_folder/continue with the returned ListFolderResult.cursor to retrieve more entries.
212
     *
213
     * Note: auth.RateLimitError may be returned if multiple list_folder or list_folder/continue calls
214
     * with same parameters are made simultaneously by same API app for same user. If your app implements
215
     * retry logic, please hold off the retry until the previous request finishes.
216
     *
217
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
218
     */
219 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...
220
    {
221
        $parameters = [
222
            'path' => $this->normalizePath($path),
223
            'recursive' => $recursive,
224
        ];
225
226
        return $this->rpcEndpointRequest('files/list_folder', $parameters);
227
    }
228
229
    /**
230
     * Once a cursor has been retrieved from list_folder, use this to paginate through all files and
231
     * retrieve updates to the folder, following the same rules as documented for list_folder.
232
     *
233
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
234
     */
235
    public function listFolderContinue(string $cursor = ''): array
236
    {
237
        return $this->rpcEndpointRequest('files/list_folder/continue', compact('cursor'));
238
    }
239
240
    /**
241
     * Move a file or folder to a different location in the user's Dropbox.
242
     *
243
     * If the source path is a folder all its contents will be moved.
244
     *
245
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
246
     */
247 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...
248
    {
249
        $parameters = [
250
            'from_path' => $this->normalizePath($fromPath),
251
            'to_path' => $this->normalizePath($toPath),
252
        ];
253
254
        return $this->rpcEndpointRequest('files/move', $parameters);
255
    }
256
257
    /**
258
     * Create a new file with the contents provided in the request.
259
     *
260
     * Do not use this to upload a file larger than 150 MB. Instead, create an upload session with upload_session/start.
261
     *
262
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
263
     *
264
     * @param string $path
265
     * @param string|resource $contents
266
     * @param string|array $mode
267
     *
268
     * @return array
269
     */
270
    public function upload(string $path, $contents, $mode = 'add'): array
271
    {
272
        $arguments = [
273
            'path' => $this->normalizePath($path),
274
            'mode' => $mode,
275
        ];
276
277
        $response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
278
279
        $metadata = json_decode($response->getBody(), true);
280
281
        $metadata['.tag'] = 'file';
282
283
        return $metadata;
284
    }
285
286
    protected function normalizePath(string $path): string
287
    {
288
        $path = trim($path, '/');
289
290
        return ($path === '') ? '' : '/'.$path;
291
    }
292
293
    /**
294
     * @param string $endpoint
295
     * @param array $arguments
296
     * @param string|resource $body
297
     *
298
     * @return \Psr\Http\Message\ResponseInterface
299
     *
300
     * @throws \Exception
301
     */
302
    public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
303
    {
304
        $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...
305
306
        if ($body !== '') {
307
            $headers['Content-Type'] = 'application/octet-stream';
308
        }
309
310
        try {
311
            $response = $this->client->post("https://content.dropboxapi.com/2/{$endpoint}", [
312
                'headers' => $headers,
313
                'body' => $body,
314
            ]);
315
        } catch (ClientException $exception) {
316
            throw $this->determineException($exception);
317
        }
318
319
        return $response;
320
    }
321
322
    public function rpcEndpointRequest(string $endpoint, array $parameters): array
323
    {
324
        try {
325
            $response = $this->client->post("https://api.dropboxapi.com/2/{$endpoint}", [
326
                'json' => $parameters,
327
            ]);
328
        } catch (ClientException $exception) {
329
            throw $this->determineException($exception);
330
        }
331
332
        return json_decode($response->getBody(), true);
333
    }
334
335
    protected function determineException(ClientException $exception): Exception
336
    {
337
        if (in_array($exception->getResponse()->getStatusCode(), [400, 409])) {
338
            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...
339
        }
340
341
        return $exception;
342
    }
343
344
}
345