Completed
Pull Request — master (#160)
by Lito
04:39
created

Dropbox::listFolderContinue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Kunnu\Dropbox;
4
5
use Kunnu\Dropbox\Exceptions\DropboxClientUnableToOpenTempFileException;
6
use Kunnu\Dropbox\Exceptions\DropboxClientUnableToWriteToTempException;
7
use Kunnu\Dropbox\Models\DeletedMetadata;
8
use Kunnu\Dropbox\Models\File;
9
use Kunnu\Dropbox\Models\Account;
10
use Kunnu\Dropbox\Models\Thumbnail;
11
use Kunnu\Dropbox\Models\AccountList;
12
use Kunnu\Dropbox\Models\ModelFactory;
13
use Kunnu\Dropbox\Models\FileMetadata;
14
use Kunnu\Dropbox\Models\CopyReference;
15
use Kunnu\Dropbox\Models\FolderMetadata;
16
use Kunnu\Dropbox\Models\ModelCollection;
17
use Kunnu\Dropbox\Authentication\OAuth2Client;
18
use Kunnu\Dropbox\Store\PersistentDataStoreFactory;
19
use Kunnu\Dropbox\Authentication\DropboxAuthHelper;
20
use Kunnu\Dropbox\Exceptions\DropboxClientException;
21
use Kunnu\Dropbox\Security\RandomStringGeneratorFactory;
22
use Kunnu\Dropbox\Http\Clients\DropboxHttpClientFactory;
23
24
/**
25
 * Dropbox
26
 */
27
class Dropbox
28
{
29
    /**
30
     * Uploading a file with the 'uploadFile' method, with the file's
31
     * size less than this value (~8 MB), the simple `upload` method will be
32
     * used, if the file size exceed this value (~8 MB), the `startUploadSession`,
33
     * `appendUploadSession` & `finishUploadSession` methods will be used
34
     * to upload the file in chunks.
35
     *
36
     * @const int
37
     */
38
    const AUTO_CHUNKED_UPLOAD_THRESHOLD = 8000000;
39
40
    /**
41
     * The Chunk Size the file will be
42
     * split into and uploaded (~4 MB)
43
     *
44
     * @const int
45
     */
46
    const DEFAULT_CHUNK_SIZE = 4000000;
47
48
    /**
49
     * Response header containing file metadata
50
     *
51
     * @const string
52
     */
53
    const METADATA_HEADER = 'dropbox-api-result';
54
55
    /**
56
     * Prefix for writable temporary file
57
     *
58
     * @const string
59
     */
60
    const TMP_PREFIX = 'dropbox-temp-file';
61
62
    /**
63
     * The Dropbox App
64
     *
65
     * @var \Kunnu\Dropbox\DropboxApp
66
     */
67
    protected $app;
68
69
    /**
70
     * OAuth2 Access Token
71
     *
72
     * @var string
73
     */
74
    protected $accessToken;
75
76
    /**
77
     * Dropbox Client
78
     *
79
     * @var \Kunnu\Dropbox\DropboxClient
80
     */
81
    protected $client;
82
83
    /**
84
     * OAuth2 Client
85
     *
86
     * @var \Kunnu\Dropbox\Authentication\OAuth2Client
87
     */
88
    protected $oAuth2Client;
89
90
    /**
91
     * Random String Generator
92
     *
93
     * @var \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
94
     */
95
    protected $randomStringGenerator;
96
97
    /**
98
     * Persistent Data Store
99
     *
100
     * @var \Kunnu\Dropbox\Store\PersistentDataStoreInterface
101
     */
102
    protected $persistentDataStore;
103
104
    /**
105
     * Create a new Dropbox instance
106
     *
107
     * @param \Kunnu\Dropbox\DropboxApp
108
     * @param array $config Configuration Array
109
     */
110
    public function __construct(DropboxApp $app, array $config = [])
111
    {
112
        //Configuration
113
        $config = array_merge([
114
            'http_client_handler' => null,
115
            'random_string_generator' => null,
116
            'persistent_data_store' => null
117
        ], $config);
118
119
        //Set the app
120
        $this->app = $app;
121
122
        //Set the access token
123
        $this->setAccessToken($app->getAccessToken());
124
125
        //Make the HTTP Client
126
        $httpClient = DropboxHttpClientFactory::make($config['http_client_handler']);
127
128
        //Make and Set the DropboxClient
129
        $this->client = new DropboxClient($httpClient);
130
131
        //Make and Set the Random String Generator
132
        $this->randomStringGenerator = RandomStringGeneratorFactory::makeRandomStringGenerator($config['random_string_generator']);
133
134
        //Make and Set the Persistent Data Store
135
        $this->persistentDataStore = PersistentDataStoreFactory::makePersistentDataStore($config['persistent_data_store']);
136
    }
137
138
    /**
139
     * Get Dropbox Auth Helper
140
     *
141
     * @return \Kunnu\Dropbox\Authentication\DropboxAuthHelper
142
     */
143
    public function getAuthHelper()
144
    {
145
        return new DropboxAuthHelper(
146
            $this->getOAuth2Client(),
147
            $this->getRandomStringGenerator(),
148
            $this->getPersistentDataStore()
149
        );
150
    }
151
152
    /**
153
     * Get OAuth2Client
154
     *
155
     * @return \Kunnu\Dropbox\Authentication\OAuth2Client
156
     */
157
    public function getOAuth2Client()
158
    {
159
        if (!$this->oAuth2Client instanceof OAuth2Client) {
160
            return new OAuth2Client(
161
                $this->getApp(),
162
                $this->getClient(),
163
                $this->getRandomStringGenerator()
164
            );
165
        }
166
167
        return $this->oAuth2Client;
168
    }
169
170
    /**
171
     * Get the Dropbox App.
172
     *
173
     * @return \Kunnu\Dropbox\DropboxApp Dropbox App
174
     */
175
    public function getApp()
176
    {
177
        return $this->app;
178
    }
179
180
    /**
181
     * Get the Client
182
     *
183
     * @return \Kunnu\Dropbox\DropboxClient
184
     */
185
    public function getClient()
186
    {
187
        return $this->client;
188
    }
189
190
    /**
191
     * Get the Random String Generator
192
     *
193
     * @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
194
     */
195
    public function getRandomStringGenerator()
196
    {
197
        return $this->randomStringGenerator;
198
    }
199
200
    /**
201
     * Get Persistent Data Store
202
     *
203
     * @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface
204
     */
205
    public function getPersistentDataStore()
206
    {
207
        return $this->persistentDataStore;
208
    }
209
210
    /**
211
     * Get the Metadata for a file or folder
212
     *
213
     * @param string $path Path of the file or folder
214
     * @param array $params Additional Params
215
     *
216
     * @return \Kunnu\Dropbox\Models\FileMetadata | \Kunnu\Dropbox\Models\FolderMetadata
217
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
218
     *
219
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
220
     *
221
     */
222
    public function getMetadata($path, array $params = [])
223
    {
224
        //Root folder is unsupported
225
        if ($path === '/') {
226
            throw new DropboxClientException("Metadata for the root folder is unsupported.");
227
        }
228
229
        //Set the path
230
        $params['path'] = $path;
231
232
        //Get File Metadata
233
        $response = $this->postToAPI('/files/get_metadata', $params);
234
235
        //Make and Return the Model
236
        return $this->makeModelFromResponse($response);
237
    }
238
239
    /**
240
     * Make a HTTP POST Request to the API endpoint type
241
     *
242
     * @param string $endpoint API Endpoint to send Request to
243
     * @param array $params Request Query Params
244
     * @param string $accessToken Access Token to send with the Request
245
     *
246
     * @return \Kunnu\Dropbox\DropboxResponse
247
     */
248
    public function postToAPI($endpoint, array $params = [], $accessToken = null)
249
    {
250
        return $this->sendRequest("POST", $endpoint, 'api', $params, $accessToken);
251
    }
252
253
    /**
254
     * Make Request to the API
255
     *
256
     * @param string $method HTTP Request Method
257
     * @param string $endpoint API Endpoint to send Request to
258
     * @param string $endpointType Endpoint type ['api'|'content']
259
     * @param array $params Request Query Params
260
     * @param string $accessToken Access Token to send with the Request
261
     * @param DropboxFile $responseFile Save response to the file
262
     *
263
     * @return \Kunnu\Dropbox\DropboxResponse
264
     *
265
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
266
     */
267
    public function sendRequest(
268
        $method,
269
        $endpoint,
270
        $endpointType = 'api',
271
        array $params = [],
272
        $accessToken = null,
273
        DropboxFile $responseFile = null
274
    ) {
275
        //Access Token
276
        $accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken;
277
278
        //Make a DropboxRequest object
279
        $request = new DropboxRequest($method, $endpoint, $accessToken, $endpointType, $params);
280
281
        //Make a DropboxResponse object if a response should be saved to the file
282
        $response = $responseFile ? new DropboxResponseToFile($request, $responseFile) : null;
283
284
        //Send Request through the DropboxClient
285
        //Fetch and return the Response
286
        return $this->getClient()->sendRequest($request, $response);
287
    }
288
289
    /**
290
     * Get the Access Token.
291
     *
292
     * @return string Access Token
293
     */
294
    public function getAccessToken()
295
    {
296
        return $this->accessToken;
297
    }
298
299
    /**
300
     * Set the Access Token.
301
     *
302
     * @param string $accessToken Access Token
303
     *
304
     * @return \Kunnu\Dropbox\Dropbox Dropbox Client
305
     */
306
    public function setAccessToken($accessToken)
307
    {
308
        $this->accessToken = $accessToken;
309
310
        return $this;
311
    }
312
313
    /**
314
     * Make Model from DropboxResponse
315
     *
316
     * @param DropboxResponse $response
317
     *
318
     * @return \Kunnu\Dropbox\Models\ModelInterface
319
     *
320
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
321
     */
322
    public function makeModelFromResponse(DropboxResponse $response)
323
    {
324
        //Get the Decoded Body
325
        $body = $response->getDecodedBody();
326
327
        if (is_null($body)) {
328
            $body = [];
329
        }
330
331
        //Make and Return the Model
332
        return ModelFactory::make($body);
333
    }
334
335
    /**
336
     * Get the contents of a Folder
337
     *
338
     * @param string $path Path to the folder. Defaults to root.
339
     * @param array $params Additional Params
340
     *
341
     * @return \Kunnu\Dropbox\Models\MetadataCollection
342
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
343
     *
344
     */
345 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...
346
    {
347
        //Specify the root folder as an
348
        //empty string rather than as "/"
349
        if ($path === '/') {
350
            $path = "";
351
        }
352
353
        //Set the path
354
        $params['path'] = $path;
355
356
        //Get File Metadata
357
        $response = $this->postToAPI('/files/list_folder', $params);
358
359
        //Make and Return the Model
360
        return $this->makeModelFromResponse($response);
361
    }
362
363
    /**
364
     * Paginate through all files and retrieve updates to the folder,
365
     * using the cursor retrieved from listFolder or listFolderContinue
366
     *
367
     * @param string $cursor The cursor returned by your
368
     *                        last call to listFolder or listFolderContinue
369
     *
370
     * @return \Kunnu\Dropbox\Models\MetadataCollection
371
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
372
     *
373
     */
374
    public function listFolderContinue($cursor)
375
    {
376
        $response = $this->postToAPI('/files/list_folder/continue', ['cursor' => $cursor]);
377
378
        //Make and Return the Model
379
        return $this->makeModelFromResponse($response);
380
    }
381
382
    /**
383
     * Get a cursor for the folder's state.
384
     *
385
     * @param string $path Path to the folder. Defaults to root.
386
     * @param array $params Additional Params
387
     *
388
     * @return string The Cursor for the folder's state
389
     *
390
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
391
     *
392
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor
393
     *
394
     */
395
    public function listFolderLatestCursor($path, array $params = [])
396
    {
397
        //Specify the root folder as an
398
        //empty string rather than as "/"
399
        if ($path === '/') {
400
            $path = "";
401
        }
402
403
        //Set the path
404
        $params['path'] = $path;
405
406
        //Fetch the cursor
407
        $response = $this->postToAPI('/files/list_folder/get_latest_cursor', $params);
408
409
        //Retrieve the cursor
410
        $body = $response->getDecodedBody();
411
        $cursor = isset($body['cursor']) ? $body['cursor'] : false;
412
413
        //No cursor returned
414
        if (!$cursor) {
415
            throw new DropboxClientException("Could not retrieve cursor. Something went wrong.");
416
        }
417
418
        //Return the cursor
419
        return $cursor;
420
    }
421
422
    /**
423
     * Get Revisions of a File
424
     *
425
     * @param string $path Path to the file
426
     * @param array $params Additional Params
427
     *
428
     * @return \Kunnu\Dropbox\Models\ModelCollection
429
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_revisions
430
     *
431
     */
432
    public function listRevisions($path, array $params = [])
433
    {
434
        //Set the Path
435
        $params['path'] = $path;
436
437
        //Fetch the Revisions
438
        $response = $this->postToAPI('/files/list_revisions', $params);
439
440
        //The file metadata of the entries, returned by this
441
        //endpoint doesn't include a '.tag' attribute, which
442
        //is used by the ModelFactory to resolve the correct
443
        //model. But since we know that revisions returned
444
        //are file metadata objects, we can explicitly cast
445
        //them as \Kunnu\Dropbox\Models\FileMetadata manually.
446
        $body = $response->getDecodedBody();
447
        $entries = isset($body['entries']) ? $body['entries'] : [];
448
        $processedEntries = [];
449
450
        foreach ($entries as $entry) {
451
            $processedEntries[] = new FileMetadata($entry);
452
        }
453
454
        return new ModelCollection($processedEntries);
455
    }
456
457
    /**
458
     * Search a folder for files/folders
459
     *
460
     * @param string $path Path to search
461
     * @param string $query Search Query
462
     * @param array $params Additional Params
463
     *
464
     * @return \Kunnu\Dropbox\Models\SearchResults
465
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-search
466
     *
467
     */
468 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...
469
    {
470
        //Specify the root folder as an
471
        //empty string rather than as "/"
472
        if ($path === '/') {
473
            $path = "";
474
        }
475
476
        //Set the path and query
477
        $params['path'] = $path;
478
        $params['query'] = $query;
479
480
        //Fetch Search Results
481
        $response = $this->postToAPI('/files/search', $params);
482
483
        //Make and Return the Model
484
        return $this->makeModelFromResponse($response);
485
    }
486
487
	/**
488
     * Search a folder for files/folders
489
     *
490
     * @param  string $path   Path to search
0 ignored issues
show
Bug introduced by
There is no parameter named $path. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
491
     * @param  string $query  Search Query
492
     * @param  array  $params Additional Params
493
     *
494
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-search
495
     *
496
     * @return \Kunnu\Dropbox\Models\SearchResults
497
     */
498 View Code Duplication
    public function searchV2($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...
499
    {
500
        //Specify the root folder as an
501
        //empty string rather than as "/"
502
        if ($path === '/') {
0 ignored issues
show
Bug introduced by
The variable $path seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
503
            $path = "";
0 ignored issues
show
Unused Code introduced by
$path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
504
        }
505
506
        //Set the path and query
507
        $params['query'] = $query;
508
509
		if( !array_key_exists( 'include_highlights', $params ) ){
510
			$params['include_highlights'] = false;
511
		}
512
513
        //Fetch Search Results
514
        $response = $this->postToAPI('/files/search_v2', $params);
515
516
        //Make and Return the Model
517
        return $this->makeModelFromResponse($response);
518
    }
519
520
    /**
521
     * Create a folder at the given path
522
     *
523
     * @param string $path Path to create
524
     * @param boolean $autorename Auto Rename File
525
     *
526
     * @return \Kunnu\Dropbox\Models\FolderMetadata
527
     *
528
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
529
     *
530
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
531
     *
532
     */
533 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...
534
    {
535
        //Path cannot be null
536
        if (is_null($path)) {
537
            throw new DropboxClientException("Path cannot be null.");
538
        }
539
540
        //Create Folder
541
        $response = $this->postToAPI('/files/create_folder', ['path' => $path, 'autorename' => $autorename]);
542
543
        //Fetch the Metadata
544
        $body = $response->getDecodedBody();
545
546
        //Make and Return the Model
547
        return new FolderMetadata($body);
548
    }
549
550
    /**
551
     * Delete a file or folder at the given path
552
     *
553
     * @param string $path Path to file/folder to delete
554
     *
555
     * @return \Kunnu\Dropbox\Models\DeletedMetadata
556
     *
557
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
558
     *
559
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
560
     *
561
     */
562 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...
563
    {
564
        //Path cannot be null
565
        if (is_null($path)) {
566
            throw new DropboxClientException("Path cannot be null.");
567
        }
568
569
        //Delete
570
        $response = $this->postToAPI('/files/delete_v2', ['path' => $path]);
571
        $body = $response->getDecodedBody();
572
573
        //Response doesn't have Metadata
574
        if (!isset($body['metadata']) || !is_array($body['metadata'])) {
575
            throw new DropboxClientException("Invalid Response.");
576
        }
577
578
        return new DeletedMetadata($body['metadata']);
579
    }
580
581
    /**
582
     * Move a file or folder to a different location
583
     *
584
     * @param string $fromPath Path to be moved
585
     * @param string $toPath Path to be moved to
586
     *
587
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
588
     *
589
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
590
     *
591
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
592
     *
593
     */
594 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...
595
    {
596
        //From and To paths cannot be null
597
        if (is_null($fromPath) || is_null($toPath)) {
598
            throw new DropboxClientException("From and To paths cannot be null.");
599
        }
600
601
        //Response
602
        $response = $this->postToAPI('/files/move', ['from_path' => $fromPath, 'to_path' => $toPath]);
603
604
        //Make and Return the Model
605
        return $this->makeModelFromResponse($response);
606
    }
607
608
    /**
609
     * Copy a file or folder to a different location
610
     *
611
     * @param string $fromPath Path to be copied
612
     * @param string $toPath Path to be copied to
613
     *
614
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
615
     *
616
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
617
     *
618
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
619
     *
620
     */
621 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...
622
    {
623
        //From and To paths cannot be null
624
        if (is_null($fromPath) || is_null($toPath)) {
625
            throw new DropboxClientException("From and To paths cannot be null.");
626
        }
627
628
        //Response
629
        $response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]);
630
631
        //Make and Return the Model
632
        return $this->makeModelFromResponse($response);
633
    }
634
635
    /**
636
     * Restore a file to the specific version
637
     *
638
     * @param string $path Path to the file to restore
639
     * @param string $rev Revision to store for the file
640
     *
641
     * @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
642
     *
643
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
644
     *
645
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-restore
646
     *
647
     */
648 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...
649
    {
650
        //Path and Revision cannot be null
651
        if (is_null($path) || is_null($rev)) {
652
            throw new DropboxClientException("Path and Revision cannot be null.");
653
        }
654
655
        //Response
656
        $response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]);
657
658
        //Fetch the Metadata
659
        $body = $response->getDecodedBody();
660
661
        //Make and Return the Model
662
        return new FileMetadata($body);
663
    }
664
665
    /**
666
     * Get Copy Reference
667
     *
668
     * @param string $path Path to the file or folder to get a copy reference to
669
     *
670
     * @return \Kunnu\Dropbox\Models\CopyReference
671
     *
672
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
673
     *
674
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get
675
     *
676
     */
677 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...
678
    {
679
        //Path cannot be null
680
        if (is_null($path)) {
681
            throw new DropboxClientException("Path cannot be null.");
682
        }
683
684
        //Get Copy Reference
685
        $response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]);
686
        $body = $response->getDecodedBody();
687
688
        //Make and Return the Model
689
        return new CopyReference($body);
690
    }
691
692
    /**
693
     * Save Copy Reference
694
     *
695
     * @param string $path Path to the file or folder to get a copy reference to
696
     * @param string $copyReference Copy reference returned by getCopyReference
697
     *
698
     * @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
699
     *
700
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
701
     *
702
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save
703
     *
704
     */
705
    public function saveCopyReference($path, $copyReference)
706
    {
707
        //Path and Copy Reference cannot be null
708
        if (is_null($path) || is_null($copyReference)) {
709
            throw new DropboxClientException("Path and Copy Reference cannot be null.");
710
        }
711
712
        //Save Copy Reference
713
        $response = $this->postToAPI('/files/copy_reference/save',
714
            ['path' => $path, 'copy_reference' => $copyReference]);
715
        $body = $response->getDecodedBody();
716
717
        //Response doesn't have Metadata
718
        if (!isset($body['metadata']) || !is_array($body['metadata'])) {
719
            throw new DropboxClientException("Invalid Response.");
720
        }
721
722
        //Make and return the Model
723
        return ModelFactory::make($body['metadata']);
724
    }
725
726
    /**
727
     * Get a temporary link to stream contents of a file
728
     *
729
     * @param string $path Path to the file you want a temporary link to
730
     *
731
     * https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
732
     *
733
     * @return \Kunnu\Dropbox\Models\TemporaryLink
734
     *
735
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
736
     */
737 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...
738
    {
739
        //Path cannot be null
740
        if (is_null($path)) {
741
            throw new DropboxClientException("Path cannot be null.");
742
        }
743
744
        //Get Temporary Link
745
        $response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]);
746
747
        //Make and Return the Model
748
        return $this->makeModelFromResponse($response);
749
    }
750
751
    /**
752
     * Save a specified URL into a file in user's Dropbox
753
     *
754
     * @param string $path Path where the URL will be saved
755
     * @param string $url URL to be saved
756
     *
757
     * @return string Async Job ID
758
     *
759
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
760
     *
761
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
762
     *
763
     */
764 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...
765
    {
766
        //Path and URL cannot be null
767
        if (is_null($path) || is_null($url)) {
768
            throw new DropboxClientException("Path and URL cannot be null.");
769
        }
770
771
        //Save URL
772
        $response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]);
773
        $body = $response->getDecodedBody();
774
775
        if (!isset($body['async_job_id'])) {
776
            throw new DropboxClientException("Could not retrieve Async Job ID.");
777
        }
778
779
        //Return the Async Job ID
780
        return $body['async_job_id'];
781
    }
782
783
    /**
784
     * Save a specified URL into a file in user's Dropbox
785
     *
786
     * @param $asyncJobId
787
     *
788
     * @return \Kunnu\Dropbox\Models\FileMetadata|string Status (failed|in_progress) or FileMetadata (if complete)
789
     *
790
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
791
     *
792
     * @link     https://www.dropbox.com/developers/documentation/http/documentation#files-save_url-check_job_status
793
     *
794
     */
795
    public function checkJobStatus($asyncJobId)
796
    {
797
        //Async Job ID cannot be null
798
        if (is_null($asyncJobId)) {
799
            throw new DropboxClientException("Async Job ID cannot be null.");
800
        }
801
802
        //Get Job Status
803
        $response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]);
804
        $body = $response->getDecodedBody();
805
806
        //Status
807
        $status = isset($body['.tag']) ? $body['.tag'] : '';
808
809
        //If status is complete
810
        if ($status === 'complete') {
811
            return new FileMetadata($body);
812
        }
813
814
        //Return the status
815
        return $status;
816
    }
817
818
    /**
819
     * Upload a File to Dropbox
820
     *
821
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
822
     * @param string $path Path to upload the file to
823
     * @param array $params Additional Params
824
     *
825
     * @return \Kunnu\Dropbox\Models\FileMetadata
826
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
827
     *
828
     */
829
    public function upload($dropboxFile, $path, array $params = [])
830
    {
831
        //Make Dropbox File
832
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
833
834
        //If the file is larger than the Chunked Upload Threshold
835
        if ($dropboxFile->getSize() > static::AUTO_CHUNKED_UPLOAD_THRESHOLD) {
836
            //Upload the file in sessions/chunks
837
            return $this->uploadChunked($dropboxFile, $path, null, null, $params);
838
        }
839
840
        //Simple file upload
841
        return $this->simpleUpload($dropboxFile, $path, $params);
842
    }
843
844
845
    /**
846
     * Make DropboxFile Object using the given $data string as the file contents.
847
     * @param $path
848
     * @param $data
849
     * @return DropboxFile
850
     * @throws DropboxClientException
851
     * @throws DropboxClientUnableToWriteToTempException
852
     */
853
    public function makeDropboxFileFromString($path, $data)
854
    {
855
        //create a temp file with a prefix
856
        $tmpfname = tempnam(sys_get_temp_dir(), static::TMP_PREFIX);
857
858
        if (!is_writable($tmpfname)) { // Test if the file is writable
859
            throw new DropboxClientUnableToWriteToTempException("Cannot write to {$tmpfname}");
860
        }
861
862
        $handle = fopen($tmpfname, DropboxFile::MODE_WRITE);
863
864
        if (!is_resource($handle)) { // Test if PHP could open the file
865
            throw new DropboxClientUnableToOpenTempFileException("Could not open {$tmpfname} on writing mode.");
866
        }
867
868
        fwrite($handle, $data);
869
870
        return DropboxFile::createByStream($path, $handle, DropboxFile::MODE_WRITE);
871
    }
872
873
    /**
874
     * Make DropboxFile Object
875
     *
876
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
877
     * @param int $maxLength Max Bytes to read from the file
878
     * @param int $offset Seek to specified offset before reading
879
     * @param string $mode The type of access
880
     *
881
     * @return \Kunnu\Dropbox\DropboxFile
882
     */
883
    public function makeDropboxFile($dropboxFile, $maxLength = null, $offset = null, $mode = DropboxFile::MODE_READ)
884
    {
885
        //Uploading file by file path
886
        if (!$dropboxFile instanceof DropboxFile) {
887
            //Create a DropboxFile Object
888
            $dropboxFile = new DropboxFile($dropboxFile, $mode);
889
        } elseif ($mode !== $dropboxFile->getMode()) {
890
            //Reopen the file with expected mode
891
            $dropboxFile->close();
892
            $dropboxFile = new DropboxFile($dropboxFile->getFilePath(), $mode);
893
        }
894
895
        if (!is_null($offset)) {
896
            $dropboxFile->setOffset($offset);
897
        }
898
899
        if (!is_null($maxLength)) {
900
            $dropboxFile->setMaxLength($maxLength);
901
        }
902
903
        //Return the DropboxFile Object
904
        return $dropboxFile;
905
    }
906
907
    /**
908
     * Upload file in sessions/chunks
909
     *
910
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
911
     * @param string $path Path to save the file to, on Dropbox
912
     * @param int $fileSize The size of the file
913
     * @param int $chunkSize The amount of data to upload in each chunk
914
     * @param array $params Additional Params
915
     *
916
     * @return \Kunnu\Dropbox\Models\FileMetadata
917
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
918
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
919
     *
920
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
921
     */
922
    public function uploadChunked($dropboxFile, $path, $fileSize = null, $chunkSize = null, array $params = array())
923
    {
924
        //Make Dropbox File
925
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
926
927
        //No file size specified explicitly
928
        if (is_null($fileSize)) {
929
            $fileSize = $dropboxFile->getSize();
930
        }
931
932
        //No chunk size specified, use default size
933
        if (is_null($chunkSize)) {
934
            $chunkSize = static::DEFAULT_CHUNK_SIZE;
935
        }
936
937
        //If the fileSize is smaller
938
        //than the chunk size, we'll
939
        //make the chunk size relatively
940
        //smaller than the file size
941
        if ($fileSize <= $chunkSize) {
942
            $chunkSize = intval($fileSize / 2);
943
        }
944
945
        //Start the Upload Session with the file path
946
        //since the DropboxFile object will be created
947
        //again using the new chunk size.
948
        $sessionId = $this->startUploadSession($dropboxFile->getFilePath(), $chunkSize);
949
950
        //Uploaded
951
        $uploaded = $chunkSize;
952
953
        //Remaining
954
        $remaining = $fileSize - $chunkSize;
955
956
        //While the remaining bytes are
957
        //more than the chunk size, append
958
        //the chunk to the upload session.
959
        while ($remaining > $chunkSize) {
960
            //Append the next chunk to the Upload session
961
            $sessionId = $this->appendUploadSession($dropboxFile, $sessionId, $uploaded, $chunkSize);
962
963
            //Update remaining and uploaded
964
            $uploaded = $uploaded + $chunkSize;
965
            $remaining = $remaining - $chunkSize;
966
        }
967
968
        //Finish the Upload Session and return the Uploaded File Metadata
969
        return $this->finishUploadSession($dropboxFile, $sessionId, $uploaded, $remaining, $path, $params);
970
    }
971
972
    /**
973
     * Start an Upload Session
974
     *
975
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
976
     * @param int $chunkSize Size of file chunk to upload
977
     * @param boolean $close Closes the session for "appendUploadSession"
978
     *
979
     * @return string Unique identifier for the upload session
980
     *
981
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
982
     *
983
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
984
     *
985
     */
986
    public function startUploadSession($dropboxFile, $chunkSize = -1, $close = false)
987
    {
988
        //Make Dropbox File with the given chunk size
989
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize);
990
991
        //Set the close param
992
        $params = [
993
            'close' => $close ? true : false,
994
            'file' => $dropboxFile
995
        ];
996
997
        //Upload File
998
        $file = $this->postToContent('/files/upload_session/start', $params);
999
        $body = $file->getDecodedBody();
1000
1001
        //Cannot retrieve Session ID
1002
        if (!isset($body['session_id'])) {
1003
            throw new DropboxClientException("Could not retrieve Session ID.");
1004
        }
1005
1006
        //Return the Session ID
1007
        return $body['session_id'];
1008
    }
1009
1010
    /**
1011
     * Make a HTTP POST Request to the Content endpoint type
1012
     *
1013
     * @param string $endpoint Content Endpoint to send Request to
1014
     * @param array $params Request Query Params
1015
     * @param string $accessToken Access Token to send with the Request
1016
     * @param DropboxFile $responseFile Save response to the file
1017
     *
1018
     * @return \Kunnu\Dropbox\DropboxResponse
1019
     */
1020
    public function postToContent($endpoint, array $params = [], $accessToken = null, DropboxFile $responseFile = null)
1021
    {
1022
        return $this->sendRequest("POST", $endpoint, 'content', $params, $accessToken, $responseFile);
1023
    }
1024
1025
    /**
1026
     * Append more data to an Upload Session
1027
     *
1028
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
1029
     * @param string $sessionId Session ID returned by `startUploadSession`
1030
     * @param int $offset The amount of data that has been uploaded so far
1031
     * @param int $chunkSize The amount of data to upload
1032
     * @param boolean $close Closes the session for futher "appendUploadSession" calls
1033
     *
1034
     * @return string Unique identifier for the upload session
1035
     *
1036
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1037
     *
1038
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
1039
     *
1040
     */
1041
    public function appendUploadSession($dropboxFile, $sessionId, $offset, $chunkSize, $close = false)
1042
    {
1043
        //Make Dropbox File
1044
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize, $offset);
1045
1046
        //Session ID, offset, chunkSize and path cannot be null
1047 View Code Duplication
        if (is_null($sessionId) || is_null($offset) || is_null($chunkSize)) {
1048
            throw new DropboxClientException("Session ID, offset and chunk size cannot be null");
1049
        }
1050
1051
        $params = [];
1052
1053
        //Set the File
1054
        $params['file'] = $dropboxFile;
1055
1056
        //Set the Cursor: Session ID and Offset
1057
        $params['cursor'] = ['session_id' => $sessionId, 'offset' => $offset];
1058
1059
        //Set the close param
1060
        $params['close'] = $close ? true : false;
1061
1062
        //Since this endpoint doesn't have
1063
        //any return values, we'll disable the
1064
        //response validation for this request.
1065
        $params['validateResponse'] = false;
1066
1067
        //Upload File
1068
        $this->postToContent('/files/upload_session/append_v2', $params);
1069
1070
        //Make and Return the Model
1071
        return $sessionId;
1072
    }
1073
1074
    /**
1075
     * Finish an upload session and save the uploaded data to the given file path
1076
     *
1077
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
1078
     * @param string $sessionId Session ID returned by `startUploadSession`
1079
     * @param int $offset The amount of data that has been uploaded so far
1080
     * @param int $remaining The amount of data that is remaining
1081
     * @param string $path Path to save the file to, on Dropbox
1082
     * @param array $params Additional Params
1083
     *
1084
     * @return \Kunnu\Dropbox\Models\FileMetadata
1085
     *
1086
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1087
     *
1088
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
1089
     *
1090
     */
1091
    public function finishUploadSession($dropboxFile, $sessionId, $offset, $remaining, $path, array $params = [])
1092
    {
1093
        //Make Dropbox File
1094
        $dropboxFile = $this->makeDropboxFile($dropboxFile, $remaining, $offset);
1095
1096
        //Session ID, offset, remaining and path cannot be null
1097 View Code Duplication
        if (is_null($sessionId) || is_null($path) || is_null($offset) || is_null($remaining)) {
1098
            throw new DropboxClientException("Session ID, offset, remaining and path cannot be null");
1099
        }
1100
1101
        $queryParams = [];
1102
1103
        //Set the File
1104
        $queryParams['file'] = $dropboxFile;
1105
1106
        //Set the Cursor: Session ID and Offset
1107
        $queryParams['cursor'] = ['session_id' => $sessionId, 'offset' => $offset];
1108
1109
        //Set the path
1110
        $params['path'] = $path;
1111
        //Set the Commit
1112
        $queryParams['commit'] = $params;
1113
1114
        //Upload File
1115
        $file = $this->postToContent('/files/upload_session/finish', $queryParams);
1116
        $body = $file->getDecodedBody();
1117
1118
        //Make and Return the Model
1119
        return new FileMetadata($body);
1120
    }
1121
1122
    /**
1123
     * Upload a File to Dropbox in a single request
1124
     *
1125
     * @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
1126
     * @param string $path Path to upload the file to
1127
     * @param array $params Additional Params
1128
     *
1129
     * @return \Kunnu\Dropbox\Models\FileMetadata
1130
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
1131
     *
1132
     */
1133
    public function simpleUpload($dropboxFile, $path, array $params = [])
1134
    {
1135
        //Make Dropbox File
1136
        $dropboxFile = $this->makeDropboxFile($dropboxFile);
1137
1138
        //Set the path and file
1139
        $params['path'] = $path;
1140
        $params['file'] = $dropboxFile;
1141
1142
        //Upload File
1143
        $file = $this->postToContent('/files/upload', $params);
1144
        $body = $file->getDecodedBody();
1145
1146
        //Make and Return the Model
1147
        return new FileMetadata($body);
1148
    }
1149
1150
    /**
1151
     * Get a thumbnail for an image
1152
     *
1153
     * @param string $path Path to the file you want a thumbnail to
1154
     * @param string $size Size for the thumbnail image ['thumb','small','medium','large','huge']
1155
     * @param string $format Format for the thumbnail image ['jpeg'|'png']
1156
     *
1157
     * @return \Kunnu\Dropbox\Models\Thumbnail
1158
     *
1159
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1160
     *
1161
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
1162
     *
1163
     */
1164
    public function getThumbnail($path, $size = 'small', $format = 'jpeg')
1165
    {
1166
        //Path cannot be null
1167
        if (is_null($path)) {
1168
            throw new DropboxClientException("Path cannot be null.");
1169
        }
1170
1171
        //Invalid Format
1172
        if (!in_array($format, ['jpeg', 'png'])) {
1173
            throw new DropboxClientException("Invalid format. Must either be 'jpeg' or 'png'.");
1174
        }
1175
1176
        //Thumbnail size
1177
        $size = $this->getThumbnailSize($size);
1178
1179
        //Get Thumbnail
1180
        $response = $this->postToContent('/files/get_thumbnail',
1181
            ['path' => $path, 'format' => $format, 'size' => $size]);
1182
1183
        //Get file metadata from response headers
1184
        $metadata = $this->getMetadataFromResponseHeaders($response);
1185
1186
        //File Contents
1187
        $contents = $response->getBody();
1188
1189
        //Make and return a Thumbnail model
1190
        return new Thumbnail($metadata, $contents);
1191
    }
1192
1193
    /**
1194
     * Get thumbnail size
1195
     *
1196
     * @param string $size Thumbnail Size
1197
     *
1198
     * @return string
1199
     */
1200
    protected function getThumbnailSize($size)
1201
    {
1202
        $thumbnailSizes = [
1203
            'thumb' => 'w32h32',
1204
            'small' => 'w64h64',
1205
            'medium' => 'w128h128',
1206
            'large' => 'w640h480',
1207
            'huge' => 'w1024h768'
1208
        ];
1209
1210
        return isset($thumbnailSizes[$size]) ? $thumbnailSizes[$size] : $thumbnailSizes['small'];
1211
    }
1212
1213
    /**
1214
     * Get metadata from response headers
1215
     *
1216
     * @param DropboxResponse $response
1217
     *
1218
     * @return array
1219
     */
1220
    protected function getMetadataFromResponseHeaders(DropboxResponse $response)
1221
    {
1222
        //Response Headers
1223
        $headers = $response->getHeaders();
1224
1225
        //Empty metadata for when
1226
        //metadata isn't returned
1227
        $metadata = [];
1228
1229
        //If metadata is available
1230
        if (isset($headers[static::METADATA_HEADER])) {
1231
            //File Metadata
1232
            $data = $headers[static::METADATA_HEADER];
1233
1234
            //The metadata is present in the first index
1235
            //of the metadata response header array
1236
            if (is_array($data) && isset($data[0])) {
1237
                $data = $data[0];
1238
            }
1239
1240
            //Since the metadata is returned as a json string
1241
            //it needs to be decoded into an associative array
1242
            $metadata = json_decode((string)$data, true);
1243
        }
1244
1245
        //Return the metadata
1246
        return $metadata;
1247
    }
1248
1249
    /**
1250
     * Download a File
1251
     *
1252
     * @param string $path Path to the file you want to download
1253
     * @param null|string|DropboxFile $dropboxFile DropboxFile object or Path to target file
1254
     *
1255
     * @return \Kunnu\Dropbox\Models\File
1256
     *
1257
     * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1258
     *
1259
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
1260
     *
1261
     */
1262 View Code Duplication
    public function download($path, $dropboxFile = null)
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...
1263
    {
1264
        //Path cannot be null
1265
        if (is_null($path)) {
1266
            throw new DropboxClientException("Path cannot be null.");
1267
        }
1268
1269
        //Make Dropbox File if target is specified
1270
        $dropboxFile = $dropboxFile ? $this->makeDropboxFile($dropboxFile, null, null, DropboxFile::MODE_WRITE) : null;
1271
1272
        //Download File
1273
        $response = $this->postToContent('/files/download', ['path' => $path], null, $dropboxFile);
1274
1275
        //Get file metadata from response headers
1276
        $metadata = $this->getMetadataFromResponseHeaders($response);
1277
1278
        //File Contents
1279
        $contents = $dropboxFile ? $this->makeDropboxFile($dropboxFile) : $response->getBody();
1280
1281
        //Make and return a File model
1282
        return new File($metadata, $contents);
1283
    }
1284
1285
	/**
1286
	 * Download a folder as a zip file
1287
	 *
1288
	 * @param  string                  $path        Path to the file you want to download
1289
	 * @param  null|string|DropboxFile $dropboxFile DropboxFile object or Path to target file
1290
	 *
1291
	 * @return \Kunnu\Dropbox\Models\File
1292
	 *
1293
	 * @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
1294
	 *
1295
	 * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download_zip
1296
	 *
1297
	 */
1298 View Code Duplication
	 public function downloadZip($path, $dropboxFile = null)
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...
1299
	 {
1300
		 //Path cannot be null
1301
		 if (is_null($path)) {
1302
			 throw new DropboxClientException("Path cannot be null.");
1303
		 }
1304
1305
		 //Make Dropbox File if target is specified
1306
		 $dropboxFile = $dropboxFile ? $this->makeDropboxFile($dropboxFile, null, null, DropboxFile::MODE_WRITE) : null;
1307
1308
		 //Download File
1309
		 $response = $this->postToContent('/files/download_zip', ['path' => $path], null, $dropboxFile);
1310
1311
		 //Get file metadata from response headers
1312
		 $metadata = $this->getMetadataFromResponseHeaders($response);
1313
1314
		 //File Contents
1315
		 $contents = $dropboxFile ? $this->makeDropboxFile($dropboxFile) : $response->getBody();
1316
1317
		 //Make and return a File model
1318
		 return new File($metadata, $contents);
1319
	}
1320
1321
    /**
1322
     * Get Current Account
1323
     *
1324
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account
1325
     *
1326
     * @return \Kunnu\Dropbox\Models\Account
1327
     */
1328
    public function getCurrentAccount()
1329
    {
1330
        //Get current account
1331
        $response = $this->postToAPI('/users/get_current_account', []);
1332
        $body = $response->getDecodedBody();
1333
1334
        //Make and return the model
1335
        return new Account($body);
1336
    }
1337
1338
    /**
1339
     * Get Account
1340
     *
1341
     * @param string $account_id Account ID of the account to get details for
1342
     *
1343
     * @return \Kunnu\Dropbox\Models\Account
1344
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account
1345
     *
1346
     */
1347
    public function getAccount($account_id)
1348
    {
1349
        //Get account
1350
        $response = $this->postToAPI('/users/get_account', ['account_id' => $account_id]);
1351
        $body = $response->getDecodedBody();
1352
1353
        //Make and return the model
1354
        return new Account($body);
1355
    }
1356
1357
    /**
1358
     * Get Multiple Accounts in one call
1359
     *
1360
     * @param array $account_ids IDs of the accounts to get details for
1361
     *
1362
     * @return \Kunnu\Dropbox\Models\AccountList
1363
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_account_batch
1364
     *
1365
     */
1366
    public function getAccounts(array $account_ids = [])
1367
    {
1368
        //Get account
1369
        $response = $this->postToAPI('/users/get_account_batch', ['account_ids' => $account_ids]);
1370
        $body = $response->getDecodedBody();
1371
1372
        //Make and return the model
1373
        return new AccountList($body);
1374
    }
1375
1376
    /**
1377
     * Get Space Usage for the current user's account
1378
     *
1379
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_space_usage
1380
     *
1381
     * @return array
1382
     */
1383
    public function getSpaceUsage()
1384
    {
1385
        //Get space usage
1386
        $response = $this->postToAPI('/users/get_space_usage', []);
1387
        $body = $response->getDecodedBody();
1388
1389
        //Return the decoded body
1390
        return $body;
1391
    }
1392
}
1393