Passed
Push — master ( ff76b0...84f20a )
by Ankit
02:41
created

Server::setMiddleware()   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\Request;
8
use TusPhp\Response;
9
use Ramsey\Uuid\Uuid;
10
use TusPhp\Cache\Cacheable;
11
use TusPhp\Events\UploadMerged;
12
use TusPhp\Events\UploadCreated;
13
use TusPhp\Events\UploadComplete;
14
use TusPhp\Events\UploadProgress;
15
use TusPhp\Middleware\Middleware;
16
use TusPhp\Exception\FileException;
17
use TusPhp\Exception\ConnectionException;
18
use TusPhp\Exception\OutOfRangeException;
19
use Symfony\Component\HttpFoundation\BinaryFileResponse;
20
use Symfony\Component\HttpFoundation\Response as HttpResponse;
21
22
class Server extends AbstractTus
23
{
24
    /** @const string Tus Creation Extension */
25
    public const TUS_EXTENSION_CREATION = 'creation';
26
27
    /** @const string Tus Termination Extension */
28
    public const TUS_EXTENSION_TERMINATION = 'termination';
29
30
    /** @const string Tus Checksum Extension */
31
    public const TUS_EXTENSION_CHECKSUM = 'checksum';
32
33
    /** @const string Tus Expiration Extension */
34
    public const TUS_EXTENSION_EXPIRATION = 'expiration';
35
36
    /** @const string Tus Concatenation Extension */
37
    public const TUS_EXTENSION_CONCATENATION = 'concatenation';
38
39
    /** @const array All supported tus extensions */
40
    public const TUS_EXTENSIONS = [
41
        self::TUS_EXTENSION_CREATION,
42
        self::TUS_EXTENSION_TERMINATION,
43
        self::TUS_EXTENSION_CHECKSUM,
44
        self::TUS_EXTENSION_EXPIRATION,
45
        self::TUS_EXTENSION_CONCATENATION,
46
    ];
47
48
    /** @const int 460 Checksum Mismatch */
49
    private const HTTP_CHECKSUM_MISMATCH = 460;
50
51
    /** @const string Default checksum algorithm */
52
    private const DEFAULT_CHECKSUM_ALGORITHM = 'sha256';
53
54
    /** @var Request */
55
    protected $request;
56
57
    /** @var Response */
58
    protected $response;
59
60
    /** @var string */
61
    protected $uploadDir;
62
63
    /** @var string */
64
    protected $uploadKey;
65
66
    /** @var Middleware */
67
    protected $middleware;
68
69
    /**
70
     * @var int Max upload size in bytes
71
     *          Default 0, no restriction.
72
     */
73
    protected $maxUploadSize = 0;
74
75
    /**
76
     * TusServer constructor.
77
     *
78
     * @param Cacheable|string $cacheAdapter
79
     *
80
     * @throws \ReflectionException
81
     */
82 3
    public function __construct($cacheAdapter = 'file')
83
    {
84 3
        $this->request    = new Request;
85 3
        $this->response   = new Response;
86 3
        $this->middleware = new Middleware;
87 3
        $this->uploadDir  = \dirname(__DIR__, 2) . '/' . 'uploads';
88
89 3
        $this->setCache($cacheAdapter);
90 3
    }
91
92
    /**
93
     * Set upload dir.
94
     *
95
     * @param string $path
96
     *
97
     * @return Server
98
     */
99 2
    public function setUploadDir(string $path) : self
100
    {
101 2
        $this->uploadDir = $path;
102
103 2
        return $this;
104
    }
105
106
    /**
107
     * Get upload dir.
108
     *
109
     * @return string
110
     */
111 1
    public function getUploadDir() : string
112
    {
113 1
        return $this->uploadDir;
114
    }
115
116
    /**
117
     * Get request.
118
     *
119
     * @return Request
120
     */
121 1
    public function getRequest() : Request
122
    {
123 1
        return $this->request;
124
    }
125
126
    /**
127
     * Get request.
128
     *
129
     * @return Response
130
     */
131 1
    public function getResponse() : Response
132
    {
133 1
        return $this->response;
134
    }
135
136
    /**
137
     * Get file checksum.
138
     *
139
     * @param string $filePath
140
     *
141
     * @return string
142
     */
143 1
    public function getServerChecksum(string $filePath) : string
144
    {
145 1
        return hash_file($this->getChecksumAlgorithm(), $filePath);
146
    }
147
148
    /**
149
     * Get checksum algorithm.
150
     *
151
     * @return string|null
152
     */
153 1
    public function getChecksumAlgorithm() : ?string
154
    {
155 1
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
156
157 1
        if (empty($checksumHeader)) {
158 1
            return self::DEFAULT_CHECKSUM_ALGORITHM;
159
        }
160
161 1
        [$checksumAlgorithm, /* $checksum */] = explode(' ', $checksumHeader);
162
163 1
        return $checksumAlgorithm;
164
    }
165
166
    /**
167
     * Set upload key.
168
     *
169
     * @param string $key
170
     *
171
     * @return Server
172
     */
173 1
    public function setUploadKey(string $key) : self
174
    {
175 1
        $this->uploadKey = $key;
176
177 1
        return $this;
178
    }
179
180
    /**
181
     * Get upload key from header.
182
     *
183
     * @return string|HttpResponse
184
     */
185 4
    public function getUploadKey()
186
    {
187 4
        if ( ! empty($this->uploadKey)) {
188 1
            return $this->uploadKey;
189
        }
190
191 3
        $key = $this->getRequest()->header('Upload-Key') ?? Uuid::uuid4()->toString();
192
193 3
        if (empty($key)) {
194 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
195
        }
196
197 2
        $this->uploadKey = $key;
198
199 2
        return $this->uploadKey;
200
    }
201
202
    /**
203
     * Set middleware.
204
     *
205
     * @param Middleware $middleware
206
     *
207
     * @return self
208
     */
209 1
    public function setMiddleware(Middleware $middleware) : self
210
    {
211 1
        $this->middleware = $middleware;
212
213 1
        return $this;
214
    }
215
216
    /**
217
     * Get middleware.
218
     *
219
     * @return Middleware
220
     */
221 1
    public function middleware() : Middleware
222
    {
223 1
        return $this->middleware;
224
    }
225
226
    /**
227
     * Set max upload size.
228
     *
229
     * @param int $uploadSize
230
     *
231
     * @return Server
232
     */
233 2
    public function setMaxUploadSize(int $uploadSize) : self
234
    {
235 2
        $this->maxUploadSize = $uploadSize;
236
237 2
        return $this;
238
    }
239
240
    /**
241
     * Get max upload size.
242
     *
243
     * @return int
244
     */
245 1
    public function getMaxUploadSize() : int
246
    {
247 1
        return $this->maxUploadSize;
248
    }
249
250
    /**
251
     * Handle all HTTP request.
252
     *
253
     * @return HttpResponse|BinaryFileResponse
254
     */
255 5
    public function serve()
256
    {
257 5
        $this->applyMiddleware();
258
259 5
        $requestMethod = $this->getRequest()->method();
260
261 5
        if ( ! \in_array($requestMethod, $this->getRequest()->allowedHttpVerbs(), true)) {
262 1
            return $this->response->send(null, HttpResponse::HTTP_METHOD_NOT_ALLOWED);
263
        }
264
265 4
        $clientVersion = $this->getRequest()->header('Tus-Resumable');
266
267 4
        if ($clientVersion && $clientVersion !== self::TUS_PROTOCOL_VERSION) {
268 1
            return $this->response->send(null, HttpResponse::HTTP_PRECONDITION_FAILED, [
269 1
                'Tus-Version' => self::TUS_PROTOCOL_VERSION,
270
            ]);
271
        }
272
273 3
        $method = 'handle' . ucfirst(strtolower($requestMethod));
274
275 3
        return $this->{$method}();
276
    }
277
278
    /**
279
     * Apply middleware.
280
     *
281
     * @return void
282
     */
283 1
    protected function applyMiddleware()
284
    {
285 1
        $middleware = $this->middleware()->list();
286
287 1
        foreach ($middleware as $m) {
288 1
            $m->handle($this->getRequest(), $this->getResponse());
289
        }
290 1
    }
291
292
    /**
293
     * Handle OPTIONS request.
294
     *
295
     * @return HttpResponse
296
     */
297 2
    protected function handleOptions() : HttpResponse
298
    {
299
        $headers = [
300 2
            'Allow' => implode(',', $this->request->allowedHttpVerbs()),
301 2
            'Tus-Version' => self::TUS_PROTOCOL_VERSION,
302 2
            'Tus-Extension' => implode(',', self::TUS_EXTENSIONS),
303 2
            'Tus-Checksum-Algorithm' => $this->getSupportedHashAlgorithms(),
304
        ];
305
306 2
        $maxUploadSize = $this->getMaxUploadSize();
307
308 2
        if ($maxUploadSize > 0) {
309 1
            $headers['Tus-Max-Size'] = $maxUploadSize;
310
        }
311
312 2
        return $this->response->send(null, HttpResponse::HTTP_OK, $headers);
313
    }
314
315
    /**
316
     * Handle HEAD request.
317
     *
318
     * @return HttpResponse
319
     */
320 5
    protected function handleHead() : HttpResponse
321
    {
322 5
        $key = $this->request->key();
323
324 5
        if ( ! $fileMeta = $this->cache->get($key)) {
325 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
326
        }
327
328 4
        $offset = $fileMeta['offset'] ?? false;
329
330 4
        if (false === $offset) {
331 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
332
        }
333
334 3
        return $this->response->send(null, HttpResponse::HTTP_OK, $this->getHeadersForHeadRequest($fileMeta));
335
    }
336
337
    /**
338
     * Handle POST request.
339
     *
340
     * @return HttpResponse
341
     */
342 5
    protected function handlePost() : HttpResponse
343
    {
344 5
        $fileName   = $this->getRequest()->extractFileName();
345 5
        $uploadType = self::UPLOAD_TYPE_NORMAL;
346
347 5
        if (empty($fileName)) {
348 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
349
        }
350
351 4
        if ( ! $this->verifyUploadSize()) {
352 1
            return $this->response->send(null, HttpResponse::HTTP_REQUEST_ENTITY_TOO_LARGE);
353
        }
354
355 3
        $uploadKey = $this->getUploadKey();
356 3
        $filePath  = $this->uploadDir . '/' . $fileName;
357
358 3
        if ($this->getRequest()->isFinal()) {
359 1
            return $this->handleConcatenation($fileName, $filePath);
360
        }
361
362 2
        if ($this->getRequest()->isPartial()) {
363 1
            $filePath   = $this->getPathForPartialUpload($uploadKey) . $fileName;
364 1
            $uploadType = self::UPLOAD_TYPE_PARTIAL;
365
        }
366
367 2
        $checksum = $this->getClientChecksum();
368 2
        $location = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
369
370 2
        $file = $this->buildFile([
371 2
            'name' => $fileName,
372 2
            'offset' => 0,
373 2
            'size' => $this->getRequest()->header('Upload-Length'),
374 2
            'file_path' => $filePath,
375 2
            'location' => $location,
376 2
        ])->setKey($uploadKey)->setChecksum($checksum)->setUploadMetadata($this->getRequest()->extractAllMeta());
377
378 2
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => $uploadType]);
379
380
        $headers = [
381 2
            'Location' => $location,
382 2
            'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
383
        ];
384
385 2
        $this->event()->dispatch(
386 2
            new UploadCreated($file, $this->getRequest(), $this->getResponse()->setHeaders($headers)),
387 2
            UploadCreated::NAME
388
        );
389
390 2
        return $this->response->send(null, HttpResponse::HTTP_CREATED, $headers);
391
    }
392
393
    /**
394
     * Handle file concatenation.
395
     *
396
     * @param string $fileName
397
     * @param string $filePath
398
     *
399
     * @return HttpResponse
400
     */
401 2
    protected function handleConcatenation(string $fileName, string $filePath) : HttpResponse
402
    {
403 2
        $partials  = $this->getRequest()->extractPartials();
404 2
        $uploadKey = $this->getUploadKey();
405 2
        $files     = $this->getPartialsMeta($partials);
406 2
        $filePaths = array_column($files, 'file_path');
407 2
        $location  = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
408
409 2
        $file = $this->buildFile([
410 2
            'name' => $fileName,
411 2
            'offset' => 0,
412 2
            'size' => 0,
413 2
            'file_path' => $filePath,
414 2
            'location' => $location,
415 2
        ])->setFilePath($filePath)->setKey($uploadKey)->setUploadMetadata($this->getRequest()->extractAllMeta());
416
417 2
        $file->setOffset($file->merge($files));
418
419
        // Verify checksum.
420 2
        $checksum = $this->getServerChecksum($filePath);
421
422 2
        if ($checksum !== $this->getClientChecksum()) {
423 1
            return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
424
        }
425
426 1
        $file->setChecksum($checksum);
427 1
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => self::UPLOAD_TYPE_FINAL]);
428
429
        // Cleanup.
430 1
        if ($file->delete($filePaths, true)) {
431 1
            $this->cache->deleteAll($partials);
432
        }
433
434 1
        $this->event()->dispatch(
435 1
            new UploadMerged($file, $this->getRequest(), $this->getResponse()),
436 1
            UploadMerged::NAME
437
        );
438
439 1
        return $this->response->send(
440 1
            ['data' => ['checksum' => $checksum]],
441 1
            HttpResponse::HTTP_CREATED,
442
            [
443 1
                'Location' => $location,
444
            ]
445
        );
446
    }
447
448
    /**
449
     * Handle PATCH request.
450
     *
451
     * @return HttpResponse
452
     */
453 10
    protected function handlePatch() : HttpResponse
454
    {
455 10
        $uploadKey = $this->request->key();
456
457 10
        if ( ! $meta = $this->cache->get($uploadKey)) {
458 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
459
        }
460
461 9
        $status = $this->verifyPatchRequest($meta);
462
463 9
        if (HttpResponse::HTTP_OK !== $status) {
464 3
            return $this->response->send(null, $status);
465
        }
466
467 6
        $file     = $this->buildFile($meta)->setUploadMetadata($meta['metadata'] ?? []);
468 6
        $checksum = $meta['checksum'];
469
470
        try {
471 6
            $fileSize = $file->getFileSize();
472 6
            $offset   = $file->setKey($uploadKey)->setChecksum($checksum)->upload($fileSize);
473
474
            // If upload is done, verify checksum.
475 3
            if ($offset === $fileSize) {
476 2
                if ( ! $this->verifyChecksum($checksum, $meta['file_path'])) {
477 1
                    return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
478
                }
479
480 1
                $this->event()->dispatch(
481 1
                    new UploadComplete($file, $this->getRequest(), $this->getResponse()),
482 1
                    UploadComplete::NAME
483
                );
484
            } else {
485 1
                $this->event()->dispatch(
486 1
                    new UploadProgress($file, $this->getRequest(), $this->getResponse()),
487 2
                    UploadProgress::NAME
488
                );
489
            }
490 3
        } catch (FileException $e) {
491 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
492 2
        } catch (OutOfRangeException $e) {
493 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
494 1
        } catch (ConnectionException $e) {
495 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
496
        }
497
498 2
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
499 2
            'Content-Type' => self::HEADER_CONTENT_TYPE,
500 2
            'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
501 2
            'Upload-Offset' => $offset,
502
        ]);
503
    }
504
505
    /**
506
     * Verify PATCH request.
507
     *
508
     * @param array $meta
509
     *
510
     * @return int
511
     */
512 9
    protected function verifyPatchRequest(array $meta) : int
513
    {
514 9
        if (self::UPLOAD_TYPE_FINAL === $meta['upload_type']) {
515 1
            return HttpResponse::HTTP_FORBIDDEN;
516
        }
517
518 8
        $uploadOffset = $this->request->header('upload-offset');
519
520 8
        if ($uploadOffset && $uploadOffset !== (string) $meta['offset']) {
521 1
            return HttpResponse::HTTP_CONFLICT;
522
        }
523
524 7
        $contentType = $this->request->header('Content-Type');
525
526 7
        if ($contentType !== self::HEADER_CONTENT_TYPE) {
527 1
            return HTTPRESPONSE::HTTP_UNSUPPORTED_MEDIA_TYPE;
528
        }
529
530 6
        return HttpResponse::HTTP_OK;
531
    }
532
533
    /**
534
     * Handle GET request.
535
     *
536
     * As per RFC7231, we need to treat HEAD and GET as an identical request.
537
     * All major PHP frameworks follows the same and silently transforms each
538
     * HEAD requests to GET.
539
     *
540
     * @return BinaryFileResponse|HttpResponse
541
     */
542 6
    protected function handleGet()
543
    {
544
        // We will treat '/files/<key>/get' as a download request.
545 6
        if ('get' === $this->request->key()) {
546 5
            return $this->handleDownload();
547
        }
548
549 1
        return $this->handleHead();
550
    }
551
552
    /**
553
     * Handle Download request.
554
     *
555
     * @return BinaryFileResponse|HttpResponse
556
     */
557 4
    protected function handleDownload()
558
    {
559 4
        $path = explode('/', str_replace('/get', '', $this->request->path()));
560 4
        $key  = end($path);
561
562 4
        if ( ! $fileMeta = $this->cache->get($key)) {
563 2
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
564
        }
565
566 2
        $resource = $fileMeta['file_path'] ?? null;
567 2
        $fileName = $fileMeta['name'] ?? null;
568
569 2
        if ( ! $resource || ! file_exists($resource)) {
570 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
571
        }
572
573 1
        return $this->response->download($resource, $fileName);
574
    }
575
576
    /**
577
     * Handle DELETE request.
578
     *
579
     * @return HttpResponse
580
     */
581 3
    protected function handleDelete() : HttpResponse
582
    {
583 3
        $key      = $this->request->key();
584 3
        $fileMeta = $this->cache->get($key);
585 3
        $resource = $fileMeta['file_path'] ?? null;
586
587 3
        if ( ! $resource) {
588 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
589
        }
590
591 2
        $isDeleted = $this->cache->delete($key);
592
593 2
        if ( ! $isDeleted || ! file_exists($resource)) {
594 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
595
        }
596
597 1
        unlink($resource);
598
599 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
600 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
601
        ]);
602
    }
603
604
    /**
605
     * Get required headers for head request.
606
     *
607
     * @param array $fileMeta
608
     *
609
     * @return array
610
     */
611 4
    protected function getHeadersForHeadRequest(array $fileMeta) : array
612
    {
613
        $headers = [
614 4
            'Upload-Length' => (int) $fileMeta['size'],
615 4
            'Upload-Offset' => (int) $fileMeta['offset'],
616 4
            'Cache-Control' => 'no-store',
617
        ];
618
619 4
        if (self::UPLOAD_TYPE_FINAL === $fileMeta['upload_type'] && $fileMeta['size'] !== $fileMeta['offset']) {
620 2
            unset($headers['Upload-Offset']);
621
        }
622
623 4
        if (self::UPLOAD_TYPE_NORMAL !== $fileMeta['upload_type']) {
624 3
            $headers += ['Upload-Concat' => $fileMeta['upload_type']];
625
        }
626
627 4
        return $headers;
628
    }
629
630
    /**
631
     * Build file object.
632
     *
633
     * @param array $meta
634
     *
635
     * @return File
636
     */
637 1
    protected function buildFile(array $meta) : File
638
    {
639 1
        $file = new File($meta['name'], $this->cache);
640
641 1
        if (\array_key_exists('offset', $meta)) {
642 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
643
        }
644
645 1
        return $file;
646
    }
647
648
    /**
649
     * Get list of supported hash algorithms.
650
     *
651
     * @return string
652
     */
653 1
    protected function getSupportedHashAlgorithms() : string
654
    {
655 1
        $supportedAlgorithms = hash_algos();
656
657 1
        $algorithms = [];
658 1
        foreach ($supportedAlgorithms as $hashAlgo) {
659 1
            if (false !== strpos($hashAlgo, ',')) {
660 1
                $algorithms[] = "'{$hashAlgo}'";
661
            } else {
662 1
                $algorithms[] = $hashAlgo;
663
            }
664
        }
665
666 1
        return implode(',', $algorithms);
667
    }
668
669
    /**
670
     * Verify and get upload checksum from header.
671
     *
672
     * @return string|HttpResponse
673
     */
674 4
    protected function getClientChecksum()
675
    {
676 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
677
678 4
        if (empty($checksumHeader)) {
679 1
            return '';
680
        }
681
682 3
        [$checksumAlgorithm, $checksum] = explode(' ', $checksumHeader);
683
684 3
        $checksum = base64_decode($checksum);
685
686 3
        if (false === $checksum || ! \in_array($checksumAlgorithm, hash_algos(), true)) {
687 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
688
        }
689
690 1
        return $checksum;
691
    }
692
693
    /**
694
     * Get expired but incomplete uploads.
695
     *
696
     * @param array|null $contents
697
     *
698
     * @return bool
699
     */
700 3
    protected function isExpired($contents) : bool
701
    {
702 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
703
704 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
705 3
            return true;
706
        }
707
708 2
        return false;
709
    }
710
711
    /**
712
     * Get path for partial upload.
713
     *
714
     * @param string $key
715
     *
716
     * @return string
717
     */
718 1
    protected function getPathForPartialUpload(string $key) : string
719
    {
720 1
        [$actualKey, /* $partialUploadKey */] = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
721
722 1
        $path = $this->uploadDir . '/' . $actualKey . '/';
723
724 1
        if ( ! file_exists($path)) {
725 1
            mkdir($path);
726
        }
727
728 1
        return $path;
729
    }
730
731
    /**
732
     * Get metadata of partials.
733
     *
734
     * @param array $partials
735
     *
736
     * @return array
737
     */
738 3
    protected function getPartialsMeta(array $partials) : array
739
    {
740 3
        $files = [];
741
742 3
        foreach ($partials as $partial) {
743 3
            $fileMeta = $this->getCache()->get($partial);
744
745 3
            $files[] = $fileMeta;
746
        }
747
748 3
        return $files;
749
    }
750
751
    /**
752
     * Delete expired resources.
753
     *
754
     * @return array
755
     */
756 2
    public function handleExpiration() : array
757
    {
758 2
        $deleted   = [];
759 2
        $cacheKeys = $this->cache->keys();
760
761 2
        foreach ($cacheKeys as $key) {
762 2
            $fileMeta = $this->cache->get($key, true);
763
764 2
            if ( ! $this->isExpired($fileMeta)) {
765 1
                continue;
766
            }
767
768 2
            if ( ! $this->cache->delete($key)) {
769 1
                continue;
770
            }
771
772 1
            if (is_writable($fileMeta['file_path'])) {
773 1
                unlink($fileMeta['file_path']);
774
            }
775
776 1
            $deleted[] = $fileMeta;
777
        }
778
779 2
        return $deleted;
780
    }
781
782
    /**
783
     * Verify max upload size.
784
     *
785
     * @return bool
786
     */
787 1
    protected function verifyUploadSize() : bool
788
    {
789 1
        $maxUploadSize = $this->getMaxUploadSize();
790
791 1
        if ($maxUploadSize > 0 && $this->getRequest()->header('Upload-Length') > $maxUploadSize) {
792 1
            return false;
793
        }
794
795 1
        return true;
796
    }
797
798
    /**
799
     * Verify checksum if available.
800
     *
801
     * @param string $checksum
802
     * @param string $filePath
803
     *
804
     * @return bool
805
     */
806 1
    protected function verifyChecksum(string $checksum, string $filePath) : bool
807
    {
808
        // Skip if checksum is empty.
809 1
        if (empty($checksum)) {
810 1
            return true;
811
        }
812
813 1
        return $checksum === $this->getServerChecksum($filePath);
814
    }
815
816
    /**
817
     * No other methods are allowed.
818
     *
819
     * @param string $method
820
     * @param array  $params
821
     *
822
     * @return HttpResponse
823
     */
824 1
    public function __call(string $method, array $params)
825
    {
826 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
827
    }
828
}
829