Passed
Pull Request — master (#101)
by Ankit
02:19
created

Client::upload()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 12
nop 1
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace TusPhp\Tus;
4
5
use TusPhp\File;
6
use Carbon\Carbon;
7
use TusPhp\Config;
8
use TusPhp\Exception\Exception;
9
use TusPhp\Exception\FileException;
10
use GuzzleHttp\Client as GuzzleClient;
11
use GuzzleHttp\Exception\ClientException;
12
use TusPhp\Exception\ConnectionException;
13
use GuzzleHttp\Exception\ConnectException;
14
use Symfony\Component\HttpFoundation\Response as HttpResponse;
15
16
class Client extends AbstractTus
17
{
18
    /** @var GuzzleClient */
19
    protected $client;
20
21
    /** @var string */
22
    protected $filePath;
23
24
    /** @var int */
25
    protected $fileSize = 0;
26
27
    /** @var string */
28
    protected $fileName;
29
30
    /** @var string */
31
    protected $key;
32
33
    /** @var string */
34
    protected $url;
35
36
    /** @var string */
37
    protected $checksum;
38
39
    /** @var int */
40
    protected $partialOffset = -1;
41
42
    /** @var bool */
43
    protected $partial = false;
44
45
    /** @var string */
46
    protected $checksumAlgorithm = 'sha256';
47
48
    /**
49
     * Client constructor.
50
     *
51
     * @param string $baseUri
52
     * @param array  $options
53
     *
54
     * @throws \ReflectionException
55
     */
56 2
    public function __construct(string $baseUri, array $options = [])
57
    {
58 2
        $options['headers'] = [
59 2
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
60 2
        ] + ($options['headers'] ?? []);
61
62 2
        $this->client = new GuzzleClient(
63 2
            ['base_uri' => $baseUri] + $options
64
        );
65
66 2
        Config::set(__DIR__ . '/../Config/client.php');
67
68 2
        $this->setCache('file');
69 2
    }
70
71
    /**
72
     * Set file properties.
73
     *
74
     * @param string $file File path.
75
     * @param string $name File name.
76
     *
77
     * @return Client
78
     */
79 3
    public function file(string $file, string $name = null) : self
80
    {
81 3
        $this->filePath = $file;
82
83 3
        if ( ! file_exists($file) || ! is_readable($file)) {
84 2
            throw new FileException('Cannot read file: ' . $file);
85
        }
86
87 1
        $this->fileName = $name ?? basename($this->filePath);
88 1
        $this->fileSize = filesize($file);
89
90 1
        return $this;
91
    }
92
93
    /**
94
     * Get file path.
95
     *
96
     * @return string|null
97
     */
98 1
    public function getFilePath() : ?string
99
    {
100 1
        return $this->filePath;
101
    }
102
103
    /**
104
     * Set file name.
105
     *
106
     * @param string $name
107
     *
108
     * @return Client
109
     */
110 1
    public function setFileName(string $name) : self
111
    {
112 1
        $this->fileName = $name;
113
114 1
        return $this;
115
    }
116
117
    /**
118
     * Get file name.
119
     *
120
     * @return string|null
121
     */
122 2
    public function getFileName() : ?string
123
    {
124 2
        return $this->fileName;
125
    }
126
127
    /**
128
     * Get file size.
129
     *
130
     * @return int
131
     */
132 1
    public function getFileSize() : int
133
    {
134 1
        return $this->fileSize;
135
    }
136
137
    /**
138
     * Get guzzle client.
139
     *
140
     * @return GuzzleClient
141
     */
142 2
    public function getClient() : GuzzleClient
143
    {
144 2
        return $this->client;
145
    }
146
147
    /**
148
     * Get checksum.
149
     *
150
     * @return string
151
     */
152 1
    public function getChecksum() : string
153
    {
154 1
        if (empty($this->checksum)) {
155 1
            $this->checksum = hash_file($this->getChecksumAlgorithm(), $this->getFilePath());
156
        }
157
158 1
        return $this->checksum;
159
    }
160
161
    /**
162
     * Set key.
163
     *
164
     * @param string $key
165
     *
166
     * @return Client
167
     */
168 1
    public function setKey(string $key) : self
169
    {
170 1
        $this->key = $key;
171
172 1
        return $this;
173
    }
174
175
    /**
176
     * Get key.
177
     *
178
     * @return string
179
     */
180 1
    public function getKey() : string
181
    {
182 1
        return $this->key;
183
    }
184
185
    /**
186
     * Get url.
187
     *
188
     * @return string|null
189
     */
190 2
    public function getUrl() : ?string
191
    {
192 2
        $this->url = $this->getCache()->get($this->getKey())['location'] ?? null;
193
194 2
        if ( ! $this->url) {
195 1
            throw new FileException('File not found.');
196
        }
197
198 1
        return $this->url;
199
    }
200
201
    /**
202
     * Set checksum algorithm.
203
     *
204
     * @param string $algorithm
205
     *
206
     * @return Client
207
     */
208 1
    public function setChecksumAlgorithm(string $algorithm) : self
209
    {
210 1
        $this->checksumAlgorithm = $algorithm;
211
212 1
        return $this;
213
    }
214
215
    /**
216
     * Get checksum algorithm.
217
     *
218
     * @return string
219
     */
220 1
    public function getChecksumAlgorithm() : string
221
    {
222 1
        return $this->checksumAlgorithm;
223
    }
224
225
    /**
226
     * Check if this is a partial upload request.
227
     *
228
     * @return bool
229
     */
230 2
    public function isPartial() : bool
231
    {
232 2
        return $this->partial;
233
    }
234
235
    /**
236
     * Get partial offset.
237
     *
238
     * @return int
239
     */
240 1
    public function getPartialOffset() : int
241
    {
242 1
        return $this->partialOffset;
243
    }
244
245
    /**
246
     * Set offset and force this to be a partial upload request.
247
     *
248
     * @param int $offset
249
     *
250
     * @return self
251
     */
252 1
    public function seek(int $offset) : self
253
    {
254 1
        $this->partialOffset = $offset;
255
256 1
        $this->partial();
257
258 1
        return $this;
259
    }
260
261
    /**
262
     * Upload file.
263
     *
264
     * @param int $bytes Bytes to upload
265
     *
266
     * @throws Exception
267
     * @throws ConnectionException
268
     *
269
     * @return int
270
     */
271 5
    public function upload(int $bytes = -1) : int
272
    {
273 5
        $bytes  = $bytes < 0 ? $this->getFileSize() : $bytes;
274 5
        $offset = $this->partialOffset < 0 ? 0 : $this->partialOffset;
0 ignored issues
show
Unused Code introduced by
The assignment to $offset is dead and can be removed.
Loading history...
275
276
        try {
277 5
            $offset = $this->sendHeadRequest();
278 3
        } catch (FileException | ClientException $e) {
279 2
            $this->url = $this->create($this->getKey());
280 1
        } catch (ConnectException $e) {
281 1
            throw new ConnectionException("Couldn't connect to server.");
282
        }
283
284
        // Now, resume upload with PATCH request.
285 4
        return $this->sendPatchRequest($bytes, $offset);
286
    }
287
288
    /**
289
     * Returns offset if file is partially uploaded.
290
     *
291
     * @return bool|int
292
     */
293 3
    public function getOffset()
294
    {
295
        try {
296 3
            $offset = $this->sendHeadRequest();
297 2
        } catch (FileException | ClientException $e) {
298 2
            return false;
299
        }
300
301 1
        return $offset;
302
    }
303
304
    /**
305
     * Create resource with POST request.
306
     *
307
     * @param string $key
308
     *
309
     * @throws FileException
310
     *
311
     * @return string
312
     */
313 3
    public function create(string $key) : string
314
    {
315
        $headers = [
316 3
            'Upload-Length' => $this->fileSize,
317 3
            'Upload-Key' => $key,
318 3
            'Upload-Checksum' => $this->getUploadChecksumHeader(),
319 3
            'Upload-Metadata' => 'filename ' . base64_encode($this->fileName),
320
        ];
321
322 3
        if ($this->isPartial()) {
323 1
            $headers += ['Upload-Concat' => 'partial'];
324
        }
325
326 3
        $response = $this->getClient()->post($this->apiPath, [
327 3
            'headers' => $headers,
328
        ]);
329
330 3
        $statusCode = $response->getStatusCode();
331
332 3
        if (HttpResponse::HTTP_CREATED !== $statusCode) {
333 1
            throw new FileException('Unable to create resource.');
334
        }
335
336 2
        $uploadLocation = current($response->getHeader('location'));
337
338 2
        $this->getCache()->set($this->getKey(), [
339 2
            'location' => $uploadLocation,
340 2
            'expires_at' => Carbon::now()->addSeconds($this->getCache()->getTtl())->format($this->getCache()::RFC_7231),
341
        ]);
342
343 2
        return $uploadLocation;
344
    }
345
346
    /**
347
     * Concatenate 2 or more partial uploads.
348
     *
349
     * @param string $key
350
     * @param mixed  $partials
351
     *
352
     * @return string
353
     */
354 3
    public function concat(string $key, ...$partials) : string
355
    {
356 3
        $response = $this->getClient()->post($this->apiPath, [
357
            'headers' => [
358 3
                'Upload-Length' => $this->fileSize,
359 3
                'Upload-Key' => $key,
360 3
                'Upload-Checksum' => $this->getUploadChecksumHeader(),
361 3
                'Upload-Metadata' => 'filename ' . base64_encode($this->fileName),
362 3
                'Upload-Concat' => self::UPLOAD_TYPE_FINAL . ';' . implode(' ', $partials),
363
            ],
364
        ]);
365
366 3
        $data       = json_decode($response->getBody(), true);
367 3
        $checksum   = $data['data']['checksum'] ?? null;
368 3
        $statusCode = $response->getStatusCode();
369
370 3
        if (HttpResponse::HTTP_CREATED !== $statusCode || ! $checksum) {
371 2
            throw new FileException('Unable to create resource.');
372
        }
373
374 1
        return $checksum;
375
    }
376
377
    /**
378
     * Send DELETE request.
379
     *
380
     * @throws FileException
381
     *
382
     * @return void
383
     */
384 3
    public function delete()
385
    {
386
        try {
387 3
            $this->getClient()->delete($this->getUrl());
388 2
        } catch (ClientException $e) {
389 2
            $statusCode = $e->getResponse()->getStatusCode();
390
391 2
            if (HttpResponse::HTTP_NOT_FOUND === $statusCode || HttpResponse::HTTP_GONE === $statusCode) {
392 2
                throw new FileException('File not found.');
393
            }
394
        }
395 1
    }
396
397
    /**
398
     * Set as partial request.
399
     *
400
     * @param bool $state
401
     *
402
     * @return void
403
     */
404 3
    protected function partial(bool $state = true)
405
    {
406 3
        $this->partial = $state;
407
408 3
        if ( ! $this->partial) {
409 1
            return;
410
        }
411
412 2
        $key = $this->getKey();
413
414 2
        if (false !== strpos($key, self::PARTIAL_UPLOAD_NAME_SEPARATOR)) {
415 1
            list($key, /* $partialKey */) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
416
        }
417
418 2
        $this->key = $key . uniqid(self::PARTIAL_UPLOAD_NAME_SEPARATOR);
419 2
    }
420
421
    /**
422
     * Send HEAD request.
423
     *
424
     * @throws FileException
425
     *
426
     * @return int
427
     */
428 2
    protected function sendHeadRequest() : int
429
    {
430 2
        $response   = $this->getClient()->head($this->getUrl());
431 2
        $statusCode = $response->getStatusCode();
432
433 2
        if (HttpResponse::HTTP_OK !== $statusCode) {
434 1
            throw new FileException('File not found.');
435
        }
436
437 1
        return (int) current($response->getHeader('upload-offset'));
438
    }
439
440
    /**
441
     * Send PATCH request.
442
     *
443
     * @param int $bytes
444
     * @param int $offset
445
     *
446
     * @throws Exception
447
     * @throws ConnectionException
448
     *
449
     * @return int
450
     */
451 7
    protected function sendPatchRequest(int $bytes, int $offset) : int
452
    {
453 7
        $data    = $this->getData($offset, $bytes);
454
        $headers = [
455 7
            'Content-Type' => self::HEADER_CONTENT_TYPE,
456 7
            'Content-Length' => strlen($data),
457 7
            'Upload-Checksum' => $this->getUploadChecksumHeader(),
458
        ];
459
460 7
        if ($this->isPartial()) {
461 1
            $headers += ['Upload-Concat' => self::UPLOAD_TYPE_PARTIAL];
462
        } else {
463 6
            $headers += ['Upload-Offset' => $offset];
464
        }
465
466
        try {
467 7
            $response = $this->getClient()->patch($this->getUrl(), [
468 7
                'body' => $data,
469 7
                'headers' => $headers,
470
            ]);
471
472 2
            return (int) current($response->getHeader('upload-offset'));
473 5
        } catch (ClientException $e) {
474 4
            throw $this->handleClientException($e);
475 1
        } catch (ConnectException $e) {
476 1
            throw new ConnectionException("Couldn't connect to server.");
477
        }
478
    }
479
480
    /**
481
     * Handle client exception during patch request.
482
     *
483
     * @param ClientException $e
484
     *
485
     * @return mixed
486
     */
487 4
    protected function handleClientException(ClientException $e)
488
    {
489 4
        $statusCode = $e->getResponse()->getStatusCode();
490
491 4
        if (HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE === $statusCode) {
492 1
            return new FileException('The uploaded file is corrupt.');
493
        }
494
495 3
        if (HttpResponse::HTTP_CONTINUE === $statusCode) {
496 1
            return new ConnectionException('Connection aborted by user.');
497
        }
498
499 2
        if (HttpResponse::HTTP_UNSUPPORTED_MEDIA_TYPE === $statusCode) {
500 1
            return new Exception('Unsupported media types.');
501
        }
502
503 1
        return new Exception($e->getResponse()->getBody(), $statusCode);
504
    }
505
506
    /**
507
     * Get X bytes of data from file.
508
     *
509
     * @param int $offset
510
     * @param int $bytes
511
     *
512
     * @return string
513
     */
514 2
    protected function getData(int $offset, int $bytes) : string
515
    {
516 2
        $file   = new File;
517 2
        $handle = $file->open($this->getFilePath(), $file::READ_BINARY);
518
519 2
        $file->seek($handle, $offset);
520
521 2
        $data = $file->read($handle, $bytes);
522
523 2
        $file->close($handle);
524
525 2
        return (string) $data;
526
    }
527
528
    /**
529
     * Get upload checksum header.
530
     *
531
     * @return string
532
     */
533 1
    protected function getUploadChecksumHeader() : string
534
    {
535 1
        return $this->getChecksumAlgorithm() . ' ' . base64_encode($this->getChecksum());
536
    }
537
}
538