Completed
Push — master ( 8e0587...afc775 )
by recca
01:27
created

FileAPI::getMimeType()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.125

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
ccs 4
cts 8
cp 0.5
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
crap 4.125
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 3
30 3
        return $completed === true
31 3
            ? $chunkFile->createUploadedFile()
32 3
            : $chunkFile->throwException([
33 3
                'files' => [
34
                    'name' => $originalName,
35
                    'size' => $end,
36 3
                    'type' => $chunkFile->getMimeType(),
37 3
                ],
38
            ], ['X-Last-Known-Byte' => $end]);
39 1
    }
40 1
41 1
    /**
42 1
     * getOriginalName.
43 3
     *
44
     * @param string $contentDisposition
45
     * @return string
46
     */
47
    protected function getOriginalName($contentDisposition)
48
    {
49
        $originalName = (string) $this->request->get('name');
50
        if (empty($originalName) === true) {
51
            list($originalName) = sscanf(
52 3
                $contentDisposition,
53
                'attachment; filename=%s'
54 3
            );
55 3
        }
56 3
57 3
        return preg_replace('/[\'"]/', '', $originalName);
58
    }
59 3
60 3
    /**
61
     * parseContentRange.
62 3
     *
63
     * @return array
64
     */
65
    protected function parseContentRange()
66
    {
67
        $contentRange = $this->request->header('content-range');
68
        if (empty($contentRange) === false) {
69
            return sscanf($contentRange, 'bytes %d-%d/%d');
70
        }
71 3
72
        $total = $end = (int) $this->request->header('content-length');
73 3
74
        return [0, $end, $total];
75 3
    }
76
}
77