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 ( aa8877...d0400e )
by Freek
01:12
created

Client::listSharedLinks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
317
        }
318
319
        $arguments = [
320
            'path' => $this->normalizePath($path),
321
            'mode' => $mode,
322
        ];
323
324
        $response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
325
326
        $metadata = json_decode($response->getBody(), true);
327
328
        $metadata['.tag'] = 'file';
329
330
        return $metadata;
331
    }
332
333
    /**
334
     * Upload file split in chunks. This allows uploading large files, since
335
     * Dropbox API v2 limits the content size to 150MB.
336
     *
337
     * The chunk size will affect directly the memory usage, so be careful.
338
     * Large chunks tends to speed up the upload, while smaller optimizes memory usage.
339
     *
340
     * @param string          $path
341
     * @param string|resource $contents
342
     * @param string          $mode
343
     * @param int             $chunkSize
344
     *
345
     * @return array
346
     */
347
    public function uploadChunked(string $path, $contents, $mode = 'add', $chunkSize = null): array
348
    {
349
        $chunkSize = $chunkSize ?? static::MAX_CHUNK_SIZE;
350
        $stream = $contents;
351
352
        // This method relies on resources, so we need to convert strings to resource
353
        if (is_string($contents)) {
354
            $stream = fopen('php://memory', 'r+');
355
            fwrite($stream, $contents);
356
            rewind($stream);
357
        }
358
359
        $data = self::readChunk($stream, $chunkSize);
0 ignored issues
show
Bug introduced by
It seems like $stream defined by $contents on line 350 can also be of type string; however, Spatie\Dropbox\Client::readChunk() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
360
        $cursor = null;
361
362
        while (! ((strlen($data) < $chunkSize) || feof($stream))) {
363
            // Start upload session on first iteration, then just append on subsequent iterations
364
            $cursor = isset($cursor) ? $this->uploadSessionAppend($data, $cursor) : $this->uploadSessionStart($data);
365
            $data = self::readChunk($stream, $chunkSize);
0 ignored issues
show
Bug introduced by
It seems like $stream defined by $contents on line 350 can also be of type string; however, Spatie\Dropbox\Client::readChunk() does only seem to accept resource, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
366
        }
367
368
        // If there's no cursor here, our stream is small enough to a single request
369
        if (! isset($cursor)) {
370
            $cursor = $this->uploadSessionStart($data);
371
            $data = '';
372
        }
373
374
        return $this->uploadSessionFinish($data, $cursor, $path, $mode);
375
    }
376
377
    /**
378
     * Upload sessions allow you to upload a single file in one or more requests,
379
     * for example where the size of the file is greater than 150 MB.
380
     * This call starts a new upload session with the given data.
381
     *
382
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
383
     *
384
     * @param string $contents
385
     * @param bool   $close
386
     *
387
     * @return UploadSessionCursor
388
     */
389
    public function uploadSessionStart($contents, bool $close = false): UploadSessionCursor
390
    {
391
        $arguments = compact('close');
392
393
        $response = json_decode(
394
            $this->contentEndpointRequest('files/upload_session/start', $arguments, $contents)->getBody(),
395
            true
396
        );
397
398
        return new UploadSessionCursor($response['session_id'], strlen($contents));
399
    }
400
401
    /**
402
     * Append more data to an upload session.
403
     * When the parameter close is set, this call will close the session.
404
     * A single request should not upload more than 150 MB.
405
     *
406
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
407
     *
408
     * @param string              $contents
409
     * @param UploadSessionCursor $cursor
410
     * @param bool                $close
411
     *
412
     * @return \Spatie\Dropbox\UploadSessionCursor
413
     */
414
    public function uploadSessionAppend($contents, UploadSessionCursor $cursor, bool $close = false): UploadSessionCursor
415
    {
416
        $arguments = compact('cursor', 'close');
417
418
        $this->contentEndpointRequest('files/upload_session/append_v2', $arguments, $contents);
419
420
        $cursor->offset += strlen($contents);
421
422
        return $cursor;
423
    }
424
425
    /**
426
     * Finish an upload session and save the uploaded data to the given file path.
427
     * A single request should not upload more than 150 MB.
428
     *
429
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
430
     *
431
     * @param string                              $contents
432
     * @param \Spatie\Dropbox\UploadSessionCursor $cursor
433
     * @param string                              $path
434
     * @param string|array                        $mode
435
     * @param bool                                $autorename
436
     * @param bool                                $mute
437
     *
438
     * @return array
439
     */
440
    public function uploadSessionFinish($contents, UploadSessionCursor $cursor, string $path, $mode = 'add', $autorename = false, $mute = false): array
441
    {
442
        $arguments = compact('cursor');
443
        $arguments['commit'] = compact('path', 'mode', 'autorename', 'mute');
444
445
        $response = $this->contentEndpointRequest(
446
            'files/upload_session/finish',
447
            $arguments,
448
            ($contents == '') ? null : $contents
449
        );
450
451
        return json_decode($response->getBody(), true);
452
    }
453
454
    /**
455
     * Sometimes fread() returns less than the request number of bytes (for example, when reading
456
     * from network streams).  This function repeatedly calls fread until the requested number of
457
     * bytes have been read or we've reached EOF.
458
     *
459
     * @param resource $stream
460
     * @param int      $chunkSize
461
     *
462
     * @throws Exception
463
     * @return string
464
     */
465
    protected static function readChunk($stream, int $chunkSize)
466
    {
467
        $chunk = '';
468
        while (! feof($stream) && $chunkSize > 0) {
469
            $part = fread($stream, $chunkSize);
470
            if ($part === false) {
471
                throw new Exception('Error reading from $stream.');
472
            }
473
            $chunk .= $part;
474
            $chunkSize -= strlen($part);
475
        }
476
477
        return $chunk;
478
    }
479
480
    /**
481
     * Get Account Info for current authenticated user.
482
     *
483
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account
484
     *
485
     * @return array
486
     */
487
    public function getAccountInfo(): array
488
    {
489
        return $this->rpcEndpointRequest('users/get_current_account');
490
    }
491
492
    /**
493
     * Revoke current access token.
494
     *
495
     * @link https://www.dropbox.com/developers/documentation/http/documentation#auth-token-revoke
496
     */
497
    public function revokeToken()
498
    {
499
        $this->rpcEndpointRequest('auth/token/revoke');
500
    }
501
502
    protected function normalizePath(string $path): string
503
    {
504
        $path = trim($path, '/');
505
506
        return ($path === '') ? '' : '/'.$path;
507
    }
508
509
    /**
510
     * @param string $endpoint
511
     * @param array $arguments
512
     * @param string|resource $body
513
     *
514
     * @return \Psr\Http\Message\ResponseInterface
515
     *
516
     * @throws \Exception
517
     */
518
    public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
519
    {
520
        $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...
521
522
        if ($body !== '') {
523
            $headers['Content-Type'] = 'application/octet-stream';
524
        }
525
526
        try {
527
            $response = $this->client->post("https://content.dropboxapi.com/2/{$endpoint}", [
528
                'headers' => $headers,
529
                'body' => $body,
530
            ]);
531
        } catch (ClientException $exception) {
532
            throw $this->determineException($exception);
533
        }
534
535
        return $response;
536
    }
537
538
    public function rpcEndpointRequest(string $endpoint, array $parameters = null): array
539
    {
540
        try {
541
            $options = [];
542
543
            if ($parameters) {
544
                $options['json'] = $parameters;
545
            }
546
547
            $response = $this->client->post("https://api.dropboxapi.com/2/{$endpoint}", $options);
548
        } catch (ClientException $exception) {
549
            throw $this->determineException($exception);
550
        }
551
552
        $response = json_decode($response->getBody(), true);
553
554
        return $response ?? [];
555
    }
556
557
    protected function determineException(ClientException $exception): Exception
558
    {
559
        if (in_array($exception->getResponse()->getStatusCode(), [400, 409])) {
560
            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...
561
        }
562
563
        return $exception;
564
    }
565
}
566