Completed
Pull Request — master (#126)
by
unknown
04:08
created

Dropbox::simpleUpload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 3
crap 2
1
<?php
2
3
namespace Kunnu\Dropbox;
4
5
use Kunnu\Dropbox\Models\DeletedList;
6
use Kunnu\Dropbox\Models\DeletedMetadata;
7
use Kunnu\Dropbox\Models\File;
8
use Kunnu\Dropbox\Models\Account;
9
use Kunnu\Dropbox\Models\Thumbnail;
10
use Kunnu\Dropbox\Models\AccountList;
11
use Kunnu\Dropbox\Models\ModelFactory;
12
use Kunnu\Dropbox\Models\FileMetadata;
13
use Kunnu\Dropbox\Models\CopyReference;
14
use Kunnu\Dropbox\Models\FolderMetadata;
15
use Kunnu\Dropbox\Models\ModelCollection;
16
use Kunnu\Dropbox\Authentication\OAuth2Client;
17
use Kunnu\Dropbox\Store\PersistentDataStoreFactory;
18
use Kunnu\Dropbox\Authentication\DropboxAuthHelper;
19
use Kunnu\Dropbox\Exceptions\DropboxClientException;
20
use Kunnu\Dropbox\Security\RandomStringGeneratorFactory;
21
use Kunnu\Dropbox\Http\Clients\DropboxHttpClientFactory;
22
23
/**
24
 * Dropbox
25
 */
26
class Dropbox
27
{
28
    /**
29
     * Uploading a file with the 'uploadFile' method, with the file's
30
     * size less than this value (~8 MB), the simple `upload` method will be
31
     * used, if the file size exceed this value (~8 MB), the `startUploadSession`,
32
     * `appendUploadSession` & `finishUploadSession` methods will be used
33
     * to upload the file in chunks.
34
     *
35
     * @const int
36
     */
37
    const AUTO_CHUNKED_UPLOAD_THRESHOLD = 8000000;
38
39
    /**
40
     * The Chunk Size the file will be
41
     * split into and uploaded (~4 MB)
42
     *
43
     * @const int
44
     */
45
    const DEFAULT_CHUNK_SIZE = 4000000;
46
47
    /**
48
     * Response header containing file metadata
49
     *
50
     * @const string
51
     */
52
    const METADATA_HEADER = 'dropbox-api-result';
53
54
    /**
55
     * The Dropbox App
56
     *
57
     * @var \Kunnu\Dropbox\DropboxApp
58
     */
59
    protected $app;
60
61
    /**
62
     * OAuth2 Access Token
63
     *
64
     * @var string
65
     */
66
    protected $accessToken;
67
68
    /**
69
     * Dropbox Client
70
     *
71
     * @var \Kunnu\Dropbox\DropboxClient
72
     */
73
    protected $client;
74
75
    /**
76
     * OAuth2 Client
77
     *
78
     * @var \Kunnu\Dropbox\Authentication\OAuth2Client
79
     */
80
    protected $oAuth2Client;
81
82
    /**
83
     * Random String Generator
84
     *
85
     * @var \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
86
     */
87
    protected $randomStringGenerator;
88
89
    /**
90
     * Persistent Data Store
91
     *
92
     * @var \Kunnu\Dropbox\Store\PersistentDataStoreInterface
93
     */
94
    protected $persistentDataStore;
95
96
    /**
97
     * Create a new Dropbox instance
98
     *
99
     * @param \Kunnu\Dropbox\DropboxApp
100
     * @param array $config Configuration Array
101
     */
102
    public function __construct(DropboxApp $app, array $config = [])
103
    {
104
        //Configuration
105
        $config = array_merge([
106
            'http_client_handler' => null,
107
            'random_string_generator' => null,
108
            'persistent_data_store' => null
109
        ], $config);
110
111
        //Set the app
112
        $this->app = $app;
113
114
        //Set the access token
115
        $this->setAccessToken($app->getAccessToken());
116
117
        //Make the HTTP Client
118
        $httpClient = DropboxHttpClientFactory::make($config['http_client_handler']);
119
120
        //Make and Set the DropboxClient
121
        $this->client = new DropboxClient($httpClient);
122
123
        //Make and Set the Random String Generator
124
        $this->randomStringGenerator = RandomStringGeneratorFactory::makeRandomStringGenerator($config['random_string_generator']);
125
126
        //Make and Set the Persistent Data Store
127
        $this->persistentDataStore = PersistentDataStoreFactory::makePersistentDataStore($config['persistent_data_store']);
128
    }
129
130
    /**
131
     * Get Dropbox Auth Helper
132
     *
133
     * @return \Kunnu\Dropbox\Authentication\DropboxAuthHelper
134
     */
135
    public function getAuthHelper()
136
    {
137
        return new DropboxAuthHelper(
138
            $this->getOAuth2Client(),
139
            $this->getRandomStringGenerator(),
140
            $this->getPersistentDataStore()
141
        );
142
    }
143
144
    /**
145
     * Get OAuth2Client
146
     *
147
     * @return \Kunnu\Dropbox\Authentication\OAuth2Client
148
     */
149
    public function getOAuth2Client()
150
    {
151
        if (!$this->oAuth2Client instanceof OAuth2Client) {
152
            return new OAuth2Client(
153
                $this->getApp(),
154
                $this->getClient(),
155
                $this->getRandomStringGenerator()
156
            );
157
        }
158
159
        return $this->oAuth2Client;
160
    }
161
162
    /**
163
     * Get the Dropbox App.
164
     *
165
     * @return \Kunnu\Dropbox\DropboxApp Dropbox App
166
     */
167
    public function getApp()
168
    {
169
        return $this->app;
170
    }
171
172
    /**
173
     * Get the Client
174
     *
175
     * @return \Kunnu\Dropbox\DropboxClient
176
     */
177
    public function getClient()
178
    {
179
        return $this->client;
180
    }
181
182
    /**
183
     * Get the Random String Generator
184
     *
185
     * @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
186
     */
187
    public function getRandomStringGenerator()
188
    {
189
        return $this->randomStringGenerator;
190
    }
191
192
    /**
193
     * Get Persistent Data Store
194
     *
195
     * @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface
196
     */
197
    public function getPersistentDataStore()
198
    {
199
        return $this->persistentDataStore;
200
    }
201
202
    /**
203
     * Get the Metadata for a file or folder
204
     *
205
     * @param  string $path   Path of the file or folder
206
     * @param  array  $params Additional Params
207
     *
208
     * @return \Kunnu\Dropbox\Models\FileMetadata | \Kunnu\Dropbox\Models\FolderMetadata
209
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
210
     *
211
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
212
     *
213
     */
214
    public function getMetadata($path, array $params = [])
215
    {
216
        //Root folder is unsupported
217
        if ($path === '/') {
218
            throw new DropboxClientException("Metadata for the root folder is unsupported.");
219
        }
220
221
        //Set the path
222
        $params['path'] = $path;
223
224
        //Get File Metadata
225
        $response = $this->postToAPI('/files/get_metadata', $params);
226
227
        //Make and Return the Model
228
        return $this->makeModelFromResponse($response);
229
    }
230
231
    /**
232
     * Make a HTTP POST Request to the API endpoint type
233
     *
234
     * @param  string $endpoint    API Endpoint to send Request to
235
     * @param  array  $params      Request Query Params
236
     * @param  string $accessToken Access Token to send with the Request
237
     *
238
     * @return \Kunnu\Dropbox\DropboxResponse
239
     */
240
    public function postToAPI($endpoint, array $params = [], $accessToken = null)
241
    {
242
        return $this->sendRequest("POST", $endpoint, 'api', $params, $accessToken);
243
    }
244
245
    /**
246
     * Make Request to the API
247
     *
248
     * @param  string      $method       HTTP Request Method
249
     * @param  string      $endpoint     API Endpoint to send Request to
250
     * @param  string      $endpointType Endpoint type ['api'|'content']
251
     * @param  array       $params       Request Query Params
252
     * @param  string      $accessToken  Access Token to send with the Request
253
     * @param  DropboxFile $responseFile Save response to the file
254
     *
255
     * @return \Kunnu\Dropbox\DropboxResponse
256
     *
257
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
258
     */
259
    public function sendRequest($method, $endpoint, $endpointType = 'api', array $params = [], $accessToken = null, DropboxFile $responseFile = null)
260
    {
261
        //Access Token
262
        $accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken;
263
264
        //Make a DropboxRequest object
265
        $request = new DropboxRequest($method, $endpoint, $accessToken, $endpointType, $params);
266
267
        //Make a DropboxResponse object if a response should be saved to the file
268
        $response = $responseFile ? new DropboxResponseToFile($request, $responseFile) : null;
269
270
        //Send Request through the DropboxClient
271
        //Fetch and return the Response
272
        return $this->getClient()->sendRequest($request, $response);
273
    }
274
275
    /**
276
     * Get the Access Token.
277
     *
278
     * @return string Access Token
279
     */
280
    public function getAccessToken()
281
    {
282
        return $this->accessToken;
283
    }
284
285
    /**
286
     * Set the Access Token.
287
     *
288
     * @param string $accessToken Access Token
289
     *
290
     * @return \Kunnu\Dropbox\Dropbox Dropbox Client
291
     */
292
    public function setAccessToken($accessToken)
293
    {
294
        $this->accessToken = $accessToken;
295
296
        return $this;
297
    }
298
299
    /**
300
     * Make Model from DropboxResponse
301
     *
302
     * @param  DropboxResponse $response
303
     *
304
     * @return \Kunnu\Dropbox\Models\ModelInterface
305
     *
306
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
307
     */
308
    public function makeModelFromResponse(DropboxResponse $response)
309
    {
310
        //Get the Decoded Body
311
        $body = $response->getDecodedBody();
312
313
        if (is_null($body)) {
314
            $body = [];
315
        }
316
317
        //Make and Return the Model
318
        return ModelFactory::make($body);
319
    }
320
321
    /**
322
     * Get the contents of a Folder
323
     *
324
     * @param  string $path   Path to the folder. Defaults to root.
325
     * @param  array  $params Additional Params
326
     *
327
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
328
     *
329
     * @return \Kunnu\Dropbox\Models\MetadataCollection
330
     */
331 View Code Duplication
    public function listFolder($path = null, array $params = [])
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...
332
    {
333
        //Specify the root folder as an
334
        //empty string rather than as "/"
335
        if ($path === '/') {
336
            $path = "";
337
        }
338
339
        //Set the path
340
        $params['path'] = $path;
341
342
        //Get File Metadata
343
        $response = $this->postToAPI('/files/list_folder', $params);
344
345
        //Make and Return the Model
346
        return $this->makeModelFromResponse($response);
347
    }
348
349
    /**
350
     * Paginate through all files and retrieve updates to the folder,
351
     * using the cursor retrieved from listFolder or listFolderContinue
352
     *
353
     * @param  string $cursor The cursor returned by your
354
     *                        last call to listFolder or listFolderContinue
355
     *
356
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
357
     *
358
     * @return \Kunnu\Dropbox\Models\MetadataCollection
359
     */
360
    public function listFolderContinue($cursor)
361
    {
362
        $response = $this->postToAPI('/files/list_folder/continue', ['cursor' => $cursor]);
363
364
        //Make and Return the Model
365
        return $this->makeModelFromResponse($response);
366
    }
367
368
    /**
369
     * Get a cursor for the folder's state.
370
     *
371
     * @param  string $path   Path to the folder. Defaults to root.
372
     * @param  array  $params Additional Params
373
     *
374
     * @return string The Cursor for the folder's state
375
     *
376
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
377
     *
378
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor
379
     *
380
     */
381
    public function listFolderLatestCursor($path, array $params = [])
382
    {
383
        //Specify the root folder as an
384
        //empty string rather than as "/"
385
        if ($path === '/') {
386
            $path = "";
387
        }
388
389
        //Set the path
390
        $params['path'] = $path;
391
392
        //Fetch the cursor
393
        $response = $this->postToAPI('/files/list_folder/get_latest_cursor', $params);
394
395
        //Retrieve the cursor
396
        $body = $response->getDecodedBody();
397
        $cursor = isset($body['cursor']) ? $body['cursor'] : false;
398
399
        //No cursor returned
400
        if (!$cursor) {
401
            throw new DropboxClientException("Could not retrieve cursor. Something went wrong.");
402
        }
403
404
        //Return the cursor
405
        return $cursor;
406
    }
407
408
    /**
409
     * Get Revisions of a File
410
     *
411
     * @param  string $path   Path to the file
412
     * @param  array  $params Additional Params
413
     *
414
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_revisions
415
     *
416
     * @return \Kunnu\Dropbox\Models\ModelCollection
417
     */
418
    public function listRevisions($path, array $params = [])
419
    {
420
        //Set the Path
421
        $params['path'] = $path;
422
423
        //Fetch the Revisions
424
        $response = $this->postToAPI('/files/list_revisions', $params);
425
426
        //The file metadata of the entries, returned by this
427
        //endpoint doesn't include a '.tag' attribute, which
428
        //is used by the ModelFactory to resolve the correct
429
        //model. But since we know that revisions returned
430
        //are file metadata objects, we can explicitly cast
431
        //them as \Kunnu\Dropbox\Models\FileMetadata manually.
432
        $body = $response->getDecodedBody();
433
        $entries = isset($body['entries']) ? $body['entries'] : [];
434
        $processedEntries = [];
435
436
        foreach ($entries as $entry) {
437
            $processedEntries[] = new FileMetadata($entry);
438
        }
439
440
        return new ModelCollection($processedEntries);
441
    }
442
443
    /**
444
     * Search a folder for files/folders
445
     *
446
     * @param  string $path   Path to search
447
     * @param  string $query  Search Query
448
     * @param  array  $params Additional Params
449
     *
450
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-search
451
     *
452
     * @return \Kunnu\Dropbox\Models\SearchResults
453
     */
454 View Code Duplication
    public function search($path, $query, array $params = [])
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...
455
    {
456
        //Specify the root folder as an
457
        //empty string rather than as "/"
458
        if ($path === '/') {
459
            $path = "";
460
        }
461
462
        //Set the path and query
463
        $params['path'] = $path;
464
        $params['query'] = $query;
465
466
        //Fetch Search Results
467
        $response = $this->postToAPI('/files/search', $params);
468
469
        //Make and Return the Model
470
        return $this->makeModelFromResponse($response);
471
    }
472
473
    /**
474
     * Create a folder at the given path
475
     *
476
     * @param  string  $path       Path to create
477
     * @param  boolean $autorename Auto Rename File
478
     *
479
     * @return \Kunnu\Dropbox\Models\FolderMetadata
480
     *
481
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
482
     *
483
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
484
     *
485
     */
486 View Code Duplication
    public function createFolder($path, $autorename = false)
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...
487
    {
488
        //Path cannot be null
489
        if (is_null($path)) {
490
            throw new DropboxClientException("Path cannot be null.");
491
        }
492
493
        //Create Folder
494
        $response = $this->postToAPI('/files/create_folder', ['path' => $path, 'autorename' => $autorename]);
495
496
        //Fetch the Metadata
497
        $body = $response->getDecodedBody();
498
499
        //Make and Return the Model
500
        return new FolderMetadata($body);
501
    }
502
503
    /**
504
     * Delete a file or folder at the given path
505
     *
506
     * @param  string $path Path to file/folder to delete
507
     *
508
     * @return \Kunnu\Dropbox\Models\DeletedMetadata
509
     *
510
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
511
     *
512
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
513
     *
514
     */
515 View Code Duplication
    public function delete($path)
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...
516
    {
517
        //Path cannot be null
518
        if (is_null($path)) {
519
            throw new DropboxClientException("Path cannot be null.");
520
        }
521
522
        //Delete
523
        $response = $this->postToAPI('/files/delete_v2', ['path' => $path]);
524
        $body = $response->getDecodedBody();
525
526
        //Response doesn't have Metadata
527
        if (!isset($body['metadata']) || !is_array($body['metadata'])) {
528
            throw new DropboxClientException("Invalid Response.");
529
        }
530
531
        return new DeletedMetadata($body['metadata']);
532
    }
533
534
    /**
535
     * Move a file or folder to a different location
536
     *
537
     * @param  string $fromPath Path to be moved
538
     * @param  string $toPath   Path to be moved to
539
     *
540
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
541
     *
542
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
543
     *
544
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
545
     *
546
     */
547 View Code Duplication
    public function move($fromPath, $toPath)
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...
548
    {
549
        //From and To paths cannot be null
550
        if (is_null($fromPath) || is_null($toPath)) {
551
            throw new DropboxClientException("From and To paths cannot be null.");
552
        }
553
554
        //Response
555
        $response = $this->postToAPI('/files/move', ['from_path' => $fromPath, 'to_path' => $toPath]);
556
557
        //Make and Return the Model
558
        return $this->makeModelFromResponse($response);
559
    }
560
561
    /**
562
     * Copy a file or folder to a different location
563
     *
564
     * @param  string $fromPath Path to be copied
565
     * @param  string $toPath   Path to be copied to
566
     *
567
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
568
     *
569
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
570
     *
571
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
572
     *
573
     */
574 View Code Duplication
    public function copy($fromPath, $toPath)
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...
575
    {
576
        //From and To paths cannot be null
577
        if (is_null($fromPath) || is_null($toPath)) {
578
            throw new DropboxClientException("From and To paths cannot be null.");
579
        }
580
581
        //Response
582
        $response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]);
583
584
        //Make and Return the Model
585
        return $this->makeModelFromResponse($response);
586
    }
587
588
    /**
589
     * Restore a file to the specific version
590
     *
591
     * @param  string $path Path to the file to restore
592
     * @param  string $rev  Revision to store for the file
593
     *
594
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
595
     *
596
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
597
     *
598
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-restore
599
     *
600
     */
601 View Code Duplication
    public function restore($path, $rev)
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...
602
    {
603
        //Path and Revision cannot be null
604
        if (is_null($path) || is_null($rev)) {
605
            throw new DropboxClientException("Path and Revision cannot be null.");
606
        }
607
608
        //Response
609
        $response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]);
610
611
        //Fetch the Metadata
612
        $body = $response->getDecodedBody();
613
614
        //Make and Return the Model
615
        return new FileMetadata($body);
616
    }
617
618
    /**
619
     * Get Copy Reference
620
     *
621
     * @param  string $path Path to the file or folder to get a copy reference to
622
     *
623
     * @return \Kunnu\Dropbox\Models\CopyReference
624
     *
625
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
626
     *
627
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get
628
     *
629
     */
630 View Code Duplication
    public function getCopyReference($path)
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...
631
    {
632
        //Path cannot be null
633
        if (is_null($path)) {
634
            throw new DropboxClientException("Path cannot be null.");
635
        }
636
637
        //Get Copy Reference
638
        $response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]);
639
        $body = $response->getDecodedBody();
640
641
        //Make and Return the Model
642
        return new CopyReference($body);
643
    }
644
645
    /**
646
     * Save Copy Reference
647
     *
648
     * @param  string $path          Path to the file or folder to get a copy reference to
649
     * @param  string $copyReference Copy reference returned by getCopyReference
650
     *
651
     * @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
652
     *
653
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
654
     *
655
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save
656
     *
657
     */
658
    public function saveCopyReference($path, $copyReference)
659
    {
660
        //Path and Copy Reference cannot be null
661
        if (is_null($path) || is_null($copyReference)) {
662
            throw new DropboxClientException("Path and Copy Reference cannot be null.");
663
        }
664
665
        //Save Copy Reference
666
        $response = $this->postToAPI('/files/copy_reference/save', ['path' => $path, 'copy_reference' => $copyReference]);
667
        $body = $response->getDecodedBody();
668
669
        //Response doesn't have Metadata
670
        if (!isset($body['metadata']) || !is_array($body['metadata'])) {
671
            throw new DropboxClientException("Invalid Response.");
672
        }
673
674
        //Make and return the Model
675
        return ModelFactory::make($body['metadata']);
676
    }
677
678
    /**
679
     * Get a temporary link to stream contents of a file
680
     *
681
     * @param  string $path Path to the file you want a temporary link to
682
     *
683
     * https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
684
     *
685
     * @return \Kunnu\Dropbox\Models\TemporaryLink
686
     *
687
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
688
     */
689 View Code Duplication
    public function getTemporaryLink($path)
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...
690
    {
691
        //Path cannot be null
692
        if (is_null($path)) {
693
            throw new DropboxClientException("Path cannot be null.");
694
        }
695
696
        //Get Temporary Link
697
        $response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]);
698
699
        //Make and Return the Model
700
        return $this->makeModelFromResponse($response);
701
    }
702
703
    /**
704
     * Save a specified URL into a file in user's Dropbox
705
     *
706
     * @param  string $path Path where the URL will be saved
707
     * @param  string $url  URL to be saved
708
     *
709
     * @return string Async Job ID
710
     *
711
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
712
     *
713
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
714
     *
715
     */
716 View Code Duplication
    public function saveUrl($path, $url)
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...
717
    {
718
        //Path and URL cannot be null
719
        if (is_null($path) || is_null($url)) {
720
            throw new DropboxClientException("Path and URL cannot be null.");
721
        }
722
723
        //Save URL
724
        $response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]);
725
        $body = $response->getDecodedBody();
726
727
        if (!isset($body['async_job_id'])) {
728
            throw new DropboxClientException("Could not retrieve Async Job ID.");
729
        }
730
731
        //Return the Async Job ID
732
        return $body['async_job_id'];
733
    }
734
735
    /**
736
     * Save a specified URL into a file in user's Dropbox
737
     *
738
     * @param $asyncJobId
739
     *
740
     * @return \Kunnu\Dropbox\Models\FileMetadata|string Status (failed|in_progress) or FileMetadata (if complete)
741
     *
742
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
743
     *
744
     * @link     https://www.dropbox.com/developers/documentation/http/documentation#files-save_url-check_job_status
745
     *
746
     */
747
    public function checkJobStatus($asyncJobId)
748
    {
749
        //Async Job ID cannot be null
750
        if (is_null($asyncJobId)) {
751
            throw new DropboxClientException("Async Job ID cannot be null.");
752
        }
753
754
        //Get Job Status
755
        $response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]);
756
        $body = $response->getDecodedBody();
757
758
        //Status
759
        $status = isset($body['.tag']) ? $body['.tag'] : '';
760
761
        //If status is complete
762
        if ($status === 'complete') {
763
            return new FileMetadata($body);
764
        }
765
766
        //Return the status
767
        return $status;
768
    }
769
770
    /**
771
     * Upload a File to Dropbox
772
     *
773
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
774
     * @param  string             $path        Path to upload the file to
775
     * @param  array              $params      Additional Params
776
     *
777
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
778
     *
779
     * @return \Kunnu\Dropbox\Models\FileMetadata
780
     */
781
    public function upload($dropboxFile, $path, array $params = [])
782
    {
783
        //Make Dropbox File
784
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
785
786
        //If the file is larger than the Chunked Upload Threshold
787
        if ($dropboxFile->getSize() > static::AUTO_CHUNKED_UPLOAD_THRESHOLD) {
788
            //Upload the file in sessions/chunks
789
            return $this->uploadChunked($dropboxFile, $path, null, null, $params);
790
        }
791
792
        //Simple file upload
793
        return $this->simpleUpload($dropboxFile, $path, $params);
794
    }
795
796
    /**
797
     * Make DropboxFile Object
798
     *
799
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
800
     * @param  int                $maxLength   Max Bytes to read from the file
801
     * @param  int                $offset      Seek to specified offset before reading
802
     * @param  string             $mode        The type of access
803
     *
804
     * @return \Kunnu\Dropbox\DropboxFile
805
     */
806
    public function makeDropboxFile($dropboxFile, $maxLength = null, $offset = null, $mode = DropboxFile::MODE_READ)
807
    {
808
        //Uploading file by file path
809
        if (!$dropboxFile instanceof DropboxFile) {
810
            //Create a DropboxFile Object
811
            $dropboxFile = new DropboxFile($dropboxFile, $mode);
812
        } elseif ($mode !== $dropboxFile->getMode()) {
813
            //Reopen the file with expected mode
814
            $dropboxFile->close();
815
            $dropboxFile = new DropboxFile($dropboxFile->getFilePath(), $mode);
816
        }
817
818
        if (!is_null($offset)) {
819
            $dropboxFile->setOffset($offset);
820
        }
821
822
        if (!is_null($maxLength)) {
823
            $dropboxFile->setMaxLength($maxLength);
824
        }
825
826
        //Return the DropboxFile Object
827
        return $dropboxFile;
828
    }
829
830
    /**
831
     * Upload file in sessions/chunks
832
     *
833
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
834
     * @param  string             $path        Path to save the file to, on Dropbox
835
     * @param  int                $fileSize    The size of the file
836
     * @param  int                $chunkSize   The amount of data to upload in each chunk
837
     * @param  array              $params      Additional Params
838
     *
839
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
840
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
841
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
842
     *
843
     * @return \Kunnu\Dropbox\Models\FileMetadata
844
     */
845
    public function uploadChunked($dropboxFile, $path, $fileSize = null, $chunkSize = null, array $params = array())
846
    {
847
        //Make Dropbox File
848
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
849
850
        //No file size specified explicitly
851
        if (is_null($fileSize)) {
852
            $fileSize = $dropboxFile->getSize();
853
        }
854
855
        //No chunk size specified, use default size
856
        if (is_null($chunkSize)) {
857
            $chunkSize = static::DEFAULT_CHUNK_SIZE;
858
        }
859
860
        //If the fileSize is smaller
861
        //than the chunk size, we'll
862
        //make the chunk size relatively
863
        //smaller than the file size
864
        if ($fileSize <= $chunkSize) {
865
            $chunkSize = intval($fileSize / 2);
866
        }
867
868
        //Start the Upload Session with the file path
869
        //since the DropboxFile object will be created
870
        //again using the new chunk size.
871
        $sessionId = $this->startUploadSession($dropboxFile->getFilePath(), $chunkSize);
872
873
        //Uploaded
874
        $uploaded = $chunkSize;
875
876
        //Remaining
877
        $remaining = $fileSize - $chunkSize;
878
879
        //While the remaining bytes are
880
        //more than the chunk size, append
881
        //the chunk to the upload session.
882
        while ($remaining > $chunkSize) {
883
            //Append the next chunk to the Upload session
884
            $sessionId = $this->appendUploadSession($dropboxFile, $sessionId, $uploaded, $chunkSize);
885
886
            //Update remaining and uploaded
887
            $uploaded = $uploaded + $chunkSize;
888
            $remaining = $remaining - $chunkSize;
889
        }
890
891
        //Finish the Upload Session and return the Uploaded File Metadata
892
        return $this->finishUploadSession($dropboxFile, $sessionId, $uploaded, $remaining, $path, $params);
893
    }
894
895
    /**
896
     * Start an Upload Session
897
     *
898
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
899
     * @param  int                $chunkSize   Size of file chunk to upload
900
     * @param  boolean            $close       Closes the session for "appendUploadSession"
901
     *
902
     * @return string Unique identifier for the upload session
903
     *
904
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
905
     *
906
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
907
     *
908
     */
909
    public function startUploadSession($dropboxFile, $chunkSize = -1, $close = false)
910
    {
911
        //Make Dropbox File with the given chunk size
912
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize);
913
914
        //Set the close param
915
        $params = [
916
            'close' => $close ? true : false,
917
            'file' => $dropboxFile
918
        ];
919
920
        //Upload File
921
        $file = $this->postToContent('/files/upload_session/start', $params);
922
        $body = $file->getDecodedBody();
923
924
        //Cannot retrieve Session ID
925
        if (!isset($body['session_id'])) {
926
            throw new DropboxClientException("Could not retrieve Session ID.");
927
        }
928
929
        //Return the Session ID
930
        return $body['session_id'];
931
    }
932
933
    /**
934
     * Make a HTTP POST Request to the Content endpoint type
935
     *
936
     * @param  string      $endpoint     Content Endpoint to send Request to
937
     * @param  array       $params       Request Query Params
938
     * @param  string      $accessToken  Access Token to send with the Request
939
     * @param  DropboxFile $responseFile Save response to the file
940
     *
941
     * @return \Kunnu\Dropbox\DropboxResponse
942
     */
943
    public function postToContent($endpoint, array $params = [], $accessToken = null, DropboxFile $responseFile = null)
944
    {
945
        return $this->sendRequest("POST", $endpoint, 'content', $params, $accessToken, $responseFile);
946
    }
947
948
    /**
949
     * Append more data to an Upload Session
950
     *
951
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
952
     * @param  string             $sessionId   Session ID returned by `startUploadSession`
953
     * @param  int                $offset      The amount of data that has been uploaded so far
954
     * @param  int                $chunkSize   The amount of data to upload
955
     * @param  boolean            $close       Closes the session for futher "appendUploadSession" calls
956
     *
957
     * @return string Unique identifier for the upload session
958
     *
959
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
960
     *
961
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
962
     *
963
     */
964
    public function appendUploadSession($dropboxFile, $sessionId, $offset, $chunkSize, $close = false)
965
    {
966
        //Make Dropbox File
967
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize, $offset);
968
969
        //Session ID, offset, chunkSize and path cannot be null
970 View Code Duplication
        if (is_null($sessionId) || is_null($offset) || is_null($chunkSize)) {
971
            throw new DropboxClientException("Session ID, offset and chunk size cannot be null");
972
        }
973
974
        $params = [];
975
976
        //Set the File
977
        $params['file'] = $dropboxFile;
978
979
        //Set the Cursor: Session ID and Offset
980
        $params['cursor'] = ['session_id' => $sessionId, 'offset' => $offset];
981
982
        //Set the close param
983
        $params['close'] = $close ? true : false;
984
985
        //Since this endpoint doesn't have
986
        //any return values, we'll disable the
987
        //response validation for this request.
988
        $params['validateResponse'] = false;
989
990
        //Upload File
991
        $this->postToContent('/files/upload_session/append_v2', $params);
992
993
        //Make and Return the Model
994
        return $sessionId;
995
    }
996
997
    /**
998
     * Finish an upload session and save the uploaded data to the given file path
999
     *
1000
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
1001
     * @param  string             $sessionId   Session ID returned by `startUploadSession`
1002
     * @param  int                $offset      The amount of data that has been uploaded so far
1003
     * @param  int                $remaining   The amount of data that is remaining
1004
     * @param  string             $path        Path to save the file to, on Dropbox
1005
     * @param  array              $params      Additional Params
1006
     *
1007
     * @return \Kunnu\Dropbox\Models\FileMetadata
1008
     *
1009
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1010
     *
1011
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
1012
     *
1013
     */
1014
    public function finishUploadSession($dropboxFile, $sessionId, $offset, $remaining, $path, array $params = [])
1015
    {
1016
        //Make Dropbox File
1017
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $remaining, $offset);
1018
1019
        //Session ID, offset, remaining and path cannot be null
1020 View Code Duplication
        if (is_null($sessionId) || is_null($path) || is_null($offset) || is_null($remaining)) {
1021
            throw new DropboxClientException("Session ID, offset, remaining and path cannot be null");
1022
        }
1023
1024
        $queryParams = [];
1025
1026
        //Set the File
1027
        $queryParams['file'] = $dropboxFile;
1028
1029
        //Set the Cursor: Session ID and Offset
1030
        $queryParams['cursor'] = ['session_id' => $sessionId, 'offset' => $offset];
1031
1032
        //Set the path
1033
        $params['path'] = $path;
1034
        //Set the Commit
1035
        $queryParams['commit'] = $params;
1036
1037
        //Upload File
1038
        $file = $this->postToContent('/files/upload_session/finish', $queryParams);
1039
        $body = $file->getDecodedBody();
1040
1041
        //Make and Return the Model
1042
        return new FileMetadata($body);
1043
    }
1044
1045
    /**
1046
     * Upload a File to Dropbox in a single request
1047
     *
1048
     * @param  string|DropboxFile $dropboxFile DropboxFile object or Path to file
1049
     * @param  string             $path        Path to upload the file to
1050
     * @param  array              $params      Additional Params
1051
     *
1052
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
1053
     *
1054
     * @return \Kunnu\Dropbox\Models\FileMetadata
1055
     */
1056
    public function simpleUpload($dropboxFile, $path, array $params = [])
1057
    {
1058
        //Make Dropbox File
1059
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
1060
1061
        //Set the path and file
1062
        $params['path'] = $path;
1063
        $params['file'] = $dropboxFile;
1064
1065
        //Upload File
1066
        $file = $this->postToContent('/files/upload', $params);
1067
        $body = $file->getDecodedBody();
1068
1069
        //Make and Return the Model
1070
        return new FileMetadata($body);
1071
    }
1072
1073
    /**
1074
     * Get a thumbnail for an image
1075
     *
1076
     * @param  string $path   Path to the file you want a thumbnail to
1077
     * @param  string $size   Size for the thumbnail image ['thumb','small','medium','large','huge']
1078
     * @param  string $format Format for the thumbnail image ['jpeg'|'png']
1079
     *
1080
     * @return \Kunnu\Dropbox\Models\Thumbnail
1081
     *
1082
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1083
     *
1084
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
1085
     *
1086
     */
1087
    public function getThumbnail($path, $size = 'small', $format = 'jpeg')
1088
    {
1089
        //Path cannot be null
1090
        if (is_null($path)) {
1091
            throw new DropboxClientException("Path cannot be null.");
1092
        }
1093
1094
        //Invalid Format
1095
        if (!in_array($format, ['jpeg', 'png'])) {
1096
            throw new DropboxClientException("Invalid format. Must either be 'jpeg' or 'png'.");
1097
        }
1098
1099
        //Thumbnail size
1100
        $size = $this->getThumbnailSize($size);
1101
1102
        //Get Thumbnail
1103
        $response = $this->postToContent('/files/get_thumbnail', ['path' => $path, 'format' => $format, 'size' => $size]);
1104
1105
        //Get file metadata from response headers
1106
        $metadata = $this->getMetadataFromResponseHeaders($response);
1107
1108
        //File Contents
1109
        $contents = $response->getBody();
1110
1111
        //Make and return a Thumbnail model
1112
        return new Thumbnail($metadata, $contents);
1113
    }
1114
1115
    /**
1116
     * Get thumbnail size
1117
     *
1118
     * @param  string $size Thumbnail Size
1119
     *
1120
     * @return string
1121
     */
1122
    protected function getThumbnailSize($size)
1123
    {
1124
        $thumbnailSizes = [
1125
            'thumb' => 'w32h32',
1126
            'small' => 'w64h64',
1127
            'medium' => 'w128h128',
1128
            'large' => 'w640h480',
1129
            'huge' => 'w1024h768'
1130
        ];
1131
1132
        return isset($thumbnailSizes[$size]) ? $thumbnailSizes[$size] : $thumbnailSizes['small'];
1133
    }
1134
1135
    /**
1136
     * Get metadata from response headers
1137
     *
1138
     * @param  DropboxResponse $response
1139
     *
1140
     * @return array
1141
     */
1142
    protected function getMetadataFromResponseHeaders(DropboxResponse $response)
1143
    {
1144
        //Response Headers
1145
        $headers = $response->getHeaders();
1146
1147
        //Empty metadata for when
1148
        //metadata isn't returned
1149
        $metadata = [];
1150
1151
        //If metadata is available
1152
        if (isset($headers[static::METADATA_HEADER])) {
1153
            //File Metadata
1154
            $data = $headers[static::METADATA_HEADER];
1155
1156
            //The metadata is present in the first index
1157
            //of the metadata response header array
1158
            if (is_array($data) && isset($data[0])) {
1159
                $data = $data[0];
1160
            }
1161
1162
            //Since the metadata is returned as a json string
1163
            //it needs to be decoded into an associative array
1164
            $metadata = json_decode((string)$data, true);
1165
        }
1166
1167
        //Return the metadata
1168
        return $metadata;
1169
    }
1170
1171
    /**
1172
     * Download a File
1173
     *
1174
     * @param  string                  $path        Path to the file you want to download
1175
     * @param  null|string|DropboxFile $dropboxFile DropboxFile object or Path to target file
1176
     *
1177
     * @return \Kunnu\Dropbox\Models\File
1178
     *
1179
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1180
     *
1181
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
1182
     *
1183
     */
1184
    public function download($path, $dropboxFile = null)
1185
    {
1186
        //Path cannot be null
1187
        if (is_null($path)) {
1188
            throw new DropboxClientException("Path cannot be null.");
1189
        }
1190
1191
        //Make Dropbox File if target is specified
1192
        $dropboxFile = $dropboxFile ? $this->makeDropboxFile($dropboxFile, null, null, DropboxFile::MODE_WRITE) : null;
1193
1194
        //Download File
1195
        $response = $this->postToContent('/files/download', ['path' => $path], null, $dropboxFile);
1196
1197
        //Get file metadata from response headers
1198
        $metadata = $this->getMetadataFromResponseHeaders($response);
1199
1200
        //File Contents
1201
        $contents = $dropboxFile ? $this->makeDropboxFile($dropboxFile) : $response->getBody();
1202
1203
        //Make and return a File model
1204
        return new File($metadata, $contents);
1205
    }
1206
1207
    /**
1208
     * Get Current Account
1209
     *
1210
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account
1211
     *
1212
     * @return \Kunnu\Dropbox\Models\Account
1213
     */
1214
    public function getCurrentAccount()
1215
    {
1216
        //Get current account
1217
        $response = $this->postToAPI('/users/get_current_account', []);
1218
        $body = $response->getDecodedBody();
1219
1220
        //Make and return the model
1221
        return new Account($body);
1222
    }
1223
1224
    /**
1225
     * Get Account
1226
     *
1227
     * @param string $account_id Account ID of the account to get details for
1228
     *
1229
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account
1230
     *
1231
     * @return \Kunnu\Dropbox\Models\Account
1232
     */
1233
    public function getAccount($account_id)
1234
    {
1235
        //Get account
1236
        $response = $this->postToAPI('/users/get_account', ['account_id' => $account_id]);
1237
        $body = $response->getDecodedBody();
1238
1239
        //Make and return the model
1240
        return new Account($body);
1241
    }
1242
1243
    /**
1244
     * Get Multiple Accounts in one call
1245
     *
1246
     * @param array $account_ids IDs of the accounts to get details for
1247
     *
1248
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account_batch
1249
     *
1250
     * @return \Kunnu\Dropbox\Models\AccountList
1251
     */
1252
    public function getAccounts(array $account_ids = [])
1253
    {
1254
        //Get account
1255
        $response = $this->postToAPI('/users/get_account_batch', ['account_ids' => $account_ids]);
1256
        $body = $response->getDecodedBody();
1257
1258
        //Make and return the model
1259
        return new AccountList($body);
1260
    }
1261
1262
    /**
1263
     * Get Space Usage for the current user's account
1264
     *
1265
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_space_usage
1266
     *
1267
     * @return array
1268
     */
1269
    public function getSpaceUsage()
1270
    {
1271
        //Get space usage
1272
        $response = $this->postToAPI('/users/get_space_usage', []);
1273
        $body = $response->getDecodedBody();
1274
1275
        //Return the decoded body
1276
        return $body;
1277
    }
1278
1279
    /**
1280
     * Delete multiple files/folders at once.
1281
     * This route is asynchronous, which returns a job ID immediately and runs the delete batch asynchronously.
1282
     * Use checkDeleteBatch to check the job status
1283
     *
1284
     * @param array|\Kunnu\Dropbox\Models\FolderMetadata[]|\Kunnu\Dropbox\Models\FileMetadata[] $files
1285
     * @return DeletedList|string List of deleted items or job ID
1286
     * @throws DropboxClientException
1287
     * @throws \Dropbox_BadRequestException
1288
     */
1289
    public function deleteBatch(array $files)
1290
    {
1291
        // prepare list of files
1292
        $entries = [];
1293
        foreach ($files as $file) {
1294
            if (is_string($file)) {
1295
                $path = $file;
1296
            } elseif (
1297
                $file instanceof \Kunnu\Dropbox\Models\FolderMetadata ||
1298
                $file instanceof \Kunnu\Dropbox\Models\FileMetadata
1299
            ) {
1300
                $path = $file->getPathLower();
1301
            } else {
1302
                throw new \Dropbox_BadRequestException("Invalid argument type");
1303
            }
1304
1305
            $entries[] = ['path' => $path];
1306
        }
1307
1308
        $response = $this->postToAPI('/files/delete_batch', ['entries' => $entries]);
1309
        $body = $response->getDecodedBody();
1310
1311
        //Response doesn't have .tag
1312
        if (!isset($body['.tag'])) {
1313
            throw new DropboxClientException("Invalid Response.");
1314
        }
1315
1316 View Code Duplication
        if ($body['.tag'] == 'complete') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1317
            $entries = isset($body['entries']) ? $body['entries'] : [];
1318
1319
            return new DeletedList($entries);
1320
        }
1321
1322
        if (!isset($body['async_job_id'])) {
1323
            throw new DropboxClientException("Could not retrieve Async Job ID.");
1324
        }
1325
1326
        return $body['async_job_id'];
1327
    }
1328
1329
    /**
1330
     * Returns the status of an asynchronous job for deleteBatch. If success, it returns list of result for each entry.
1331
     *
1332
     * @param string $asyncJobId
1333
     * @return DeletedList|string
1334
     * @throws DropboxClientException
1335
     */
1336
    public function checkDeleteBatch($asyncJobId)
1337
    {
1338
        //Async Job ID cannot be null
1339
        if (empty($asyncJobId)) {
1340
            throw new DropboxClientException("Async Job ID cannot be empty.");
1341
        }
1342
1343
        //Get Job Status
1344
        $response = $this->postToAPI('/files/delete_batch/check', ['async_job_id' => $asyncJobId]);
1345
        $body = $response->getDecodedBody();
1346
1347
        //Status
1348
        $status = isset($body['.tag']) ? $body['.tag'] : '';
1349
1350
        //If status is complete
1351 View Code Duplication
        if ($status === 'complete') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
1352
            $entries = isset($body['entries']) ? $body['entries'] : [];
1353
1354
            return new DeletedList($entries);
1355
        }
1356
1357
        //Return the status
1358
        return $status;
1359
    }
1360
}
1361