Completed
Pull Request — master (#101)
by Ankit
21:06
created

Client::setChecksumAlgorithm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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