Completed
Push — master ( afc775...ef5a6b )
by recca
01:29
created

FileAPI   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 72
ccs 30
cts 30
cp 1
rs 10
c 4
b 1
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B receive() 0 25 3
A getOriginalName() 0 12 2
A parseContentRange() 0 11 2
1
<?php
2
3
namespace Recca0120\Upload;
4
5
class FileAPI extends Api
6
{
7
    /**
8
     * receive.
9
     *
10
     * @param string $name
11
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile
12
     *
13
     * @throws \Recca0120\Upload\Exceptions\ChunkedResponseException
14
     */
15 4
    public function receive($name)
16
    {
17 4
        $contentDisposition = (string) $this->request->header('content-disposition');
18 4
        if (empty($contentDisposition) === true) {
19 1
            return $this->request->file($name);
20
        }
21
22 3
        list($start, $end, $total) = $this->parseContentRange();
23 3
        $originalName = $this->getOriginalName($contentDisposition);
24 3
        $uuid = $this->request->get('token');
25 3
        $completed = $end >= $total - 1;
26
27 3
        $chunkFile = $this->createChunkFile($originalName, $uuid);
28 3
        $chunkFile->appendStream('php://input', $start);
29
30 3
        return $completed === true
31 2
            ? $chunkFile->createUploadedFile()
32 1
            : $chunkFile->throwException([
33
                'files' => [
34 1
                    'name' => $originalName,
35 1
                    'size' => $end,
36 1
                    'type' => $chunkFile->getMimeType(),
37
                ],
38 3
            ], ['X-Last-Known-Byte' => $end]);
39
    }
40
41
    /**
42
     * getOriginalName.
43
     *
44
     * @param string $contentDisposition
45
     * @return string
46
     */
47 3
    protected function getOriginalName($contentDisposition)
48
    {
49 3
        $originalName = (string) $this->request->get('name');
50 3
        if (empty($originalName) === true) {
51 3
            list($originalName) = sscanf(
52 3
                $contentDisposition,
53 3
                'attachment; filename=%s'
54
            );
55
        }
56
57 3
        return preg_replace('/[\'"]/', '', $originalName);
58
    }
59
60
    /**
61
     * parseContentRange.
62
     *
63
     * @return array
64
     */
65 3
    protected function parseContentRange()
66
    {
67 3
        $contentRange = $this->request->header('content-range');
68 3
        if (empty($contentRange) === false) {
69 2
            return sscanf($contentRange, 'bytes %d-%d/%d');
70
        }
71
72 1
        $total = $end = (int) $this->request->header('content-length');
73
74 1
        return [0, $end, $total];
75
    }
76
}
77